diff --git a/agent/app/api/v2/file.go b/agent/app/api/v2/file.go index 15a7df0c1..44753f332 100644 --- a/agent/app/api/v2/file.go +++ b/agent/app/api/v2/file.go @@ -841,7 +841,11 @@ func (b *BaseApi) ReadFileByLine(c *gin.Context) { helper.InternalServer(c, err) return } - helper.SuccessWithData(c, res) + if res.TotalLines > 100 { + helper.SuccessWithDataGzipped(c, res) + } else { + helper.SuccessWithData(c, res) + } } // @Tags File diff --git a/agent/app/api/v2/helper/helper.go b/agent/app/api/v2/helper/helper.go index 6a4f0e8c8..3439a9893 100644 --- a/agent/app/api/v2/helper/helper.go +++ b/agent/app/api/v2/helper/helper.go @@ -1,10 +1,14 @@ package helper import ( + "compress/gzip" "context" + "encoding/json" "fmt" "net/http" "strconv" + "strings" + "sync" "github.com/1Panel-dev/1Panel/agent/global" "gorm.io/gorm" @@ -46,6 +50,42 @@ func SuccessWithData(ctx *gin.Context, data interface{}) { 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) { res := dto.Response{ Code: http.StatusOK,