feat: support zstd request decompression (#6545)

This commit is contained in:
Seefs
2026-07-31 11:17:55 +08:00
committed by GitHub
parent 66ee6b8f98
commit 0f9f668c60
2 changed files with 24 additions and 3 deletions
+23 -2
View File
@@ -8,6 +8,7 @@ import (
"github.com/QuantumNous/new-api/constant"
"github.com/andybalholm/brotli"
"github.com/gin-gonic/gin"
"github.com/klauspost/compress/zstd"
)
type readCloser struct {
@@ -38,6 +39,7 @@ func DecompressRequestMiddleware() gin.HandlerFunc {
wrapMaxBytes := func(body io.ReadCloser) io.ReadCloser {
return http.MaxBytesReader(c.Writer, body, maxBytes)
}
decompressed := false
switch c.GetHeader("Content-Encoding") {
case "gzip":
@@ -55,7 +57,7 @@ func DecompressRequestMiddleware() gin.HandlerFunc {
return origBody.Close()
},
})
c.Request.Header.Del("Content-Encoding")
decompressed = true
case "br":
reader := brotli.NewReader(origBody)
c.Request.Body = wrapMaxBytes(&readCloser{
@@ -64,12 +66,31 @@ func DecompressRequestMiddleware() gin.HandlerFunc {
return origBody.Close()
},
})
c.Request.Header.Del("Content-Encoding")
decompressed = true
case "zstd":
reader, err := zstd.NewReader(origBody)
if err != nil {
_ = origBody.Close()
c.AbortWithStatus(http.StatusBadRequest)
return
}
c.Request.Body = wrapMaxBytes(&readCloser{
Reader: reader,
closeFn: func() error {
reader.Close()
return origBody.Close()
},
})
decompressed = true
default:
// Even for uncompressed bodies, enforce a max size to avoid huge request allocations.
c.Request.Body = wrapMaxBytes(origBody)
}
if decompressed {
c.Request.Header.Del("Content-Encoding")
}
// Continue processing the request
c.Next()
}