feat: Implement Gzip compression for successful log API responses (#11063)

* feat: Implement Gzip compression for successful API responses

* refactor: Optimize Gzip compression handling in API responses using sync.Pool
This commit is contained in:
KOMATA 2025-11-25 13:39:08 +08:00 committed by GitHub
parent 48e2e01a57
commit dda83b6307
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 45 additions and 1 deletions

View file

@ -841,7 +841,11 @@ func (b *BaseApi) ReadFileByLine(c *gin.Context) {
helper.InternalServer(c, err) helper.InternalServer(c, err)
return return
} }
helper.SuccessWithData(c, res) if res.TotalLines > 100 {
helper.SuccessWithDataGzipped(c, res)
} else {
helper.SuccessWithData(c, res)
}
} }
// @Tags File // @Tags File

View file

@ -1,10 +1,14 @@
package helper package helper
import ( import (
"compress/gzip"
"context" "context"
"encoding/json"
"fmt" "fmt"
"net/http" "net/http"
"strconv" "strconv"
"strings"
"sync"
"github.com/1Panel-dev/1Panel/agent/global" "github.com/1Panel-dev/1Panel/agent/global"
"gorm.io/gorm" "gorm.io/gorm"
@ -46,6 +50,42 @@ func SuccessWithData(ctx *gin.Context, data interface{}) {
ctx.Abort() ctx.Abort()
} }
var gzipWriterPool = sync.Pool{
New: func() interface{} {
return gzip.NewWriter(nil)
},
}
func SuccessWithDataGzipped(ctx *gin.Context, data interface{}) {
if !strings.Contains(ctx.GetHeader("Accept-Encoding"), "gzip") {
SuccessWithData(ctx, data)
return
}
if data == nil {
data = gin.H{}
}
res := dto.Response{
Code: http.StatusOK,
Data: data,
}
jsonBytes, err := json.Marshal(res)
if err != nil {
ErrorWithDetail(ctx, http.StatusInternalServerError, "ErrInternalServer", err)
return
}
ctx.Header("Content-Encoding", "gzip")
ctx.Header("Content-Type", "application/json; charset=utf-8")
ctx.Status(http.StatusOK)
gz := gzipWriterPool.Get().(*gzip.Writer)
gz.Reset(ctx.Writer)
_, _ = gz.Write(jsonBytes)
_ = gz.Close()
gzipWriterPool.Put(gz)
ctx.Abort()
}
func Success(ctx *gin.Context) { func Success(ctx *gin.Context) {
res := dto.Response{ res := dto.Response{
Code: http.StatusOK, Code: http.StatusOK,