Skip to content

Commit dda83b6

Browse files
authored
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
1 parent 48e2e01 commit dda83b6

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

agent/app/api/v2/file.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -841,7 +841,11 @@ func (b *BaseApi) ReadFileByLine(c *gin.Context) {
841841
helper.InternalServer(c, err)
842842
return
843843
}
844-
helper.SuccessWithData(c, res)
844+
if res.TotalLines > 100 {
845+
helper.SuccessWithDataGzipped(c, res)
846+
} else {
847+
helper.SuccessWithData(c, res)
848+
}
845849
}
846850

847851
// @Tags File

agent/app/api/v2/helper/helper.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
package helper
22

33
import (
4+
"compress/gzip"
45
"context"
6+
"encoding/json"
57
"fmt"
68
"net/http"
79
"strconv"
10+
"strings"
11+
"sync"
812

913
"github.com/1Panel-dev/1Panel/agent/global"
1014
"gorm.io/gorm"
@@ -46,6 +50,42 @@ func SuccessWithData(ctx *gin.Context, data interface{}) {
4650
ctx.Abort()
4751
}
4852

53+
var gzipWriterPool = sync.Pool{
54+
New: func() interface{} {
55+
return gzip.NewWriter(nil)
56+
},
57+
}
58+
59+
func SuccessWithDataGzipped(ctx *gin.Context, data interface{}) {
60+
if !strings.Contains(ctx.GetHeader("Accept-Encoding"), "gzip") {
61+
SuccessWithData(ctx, data)
62+
return
63+
}
64+
if data == nil {
65+
data = gin.H{}
66+
}
67+
res := dto.Response{
68+
Code: http.StatusOK,
69+
Data: data,
70+
}
71+
jsonBytes, err := json.Marshal(res)
72+
if err != nil {
73+
ErrorWithDetail(ctx, http.StatusInternalServerError, "ErrInternalServer", err)
74+
return
75+
}
76+
77+
ctx.Header("Content-Encoding", "gzip")
78+
ctx.Header("Content-Type", "application/json; charset=utf-8")
79+
ctx.Status(http.StatusOK)
80+
81+
gz := gzipWriterPool.Get().(*gzip.Writer)
82+
gz.Reset(ctx.Writer)
83+
_, _ = gz.Write(jsonBytes)
84+
_ = gz.Close()
85+
gzipWriterPool.Put(gz)
86+
ctx.Abort()
87+
}
88+
4989
func Success(ctx *gin.Context) {
5090
res := dto.Response{
5191
Code: http.StatusOK,

0 commit comments

Comments
 (0)