mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-09-11 14:41:21 +00:00
feat: support zstd request decompression (#6545)
This commit is contained in:
+23
-2
@@ -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()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user