77 lines
1.7 KiB
Go
Raw Normal View History

2024-12-04 23:24:46 +08:00
package middleware
import (
"compress/gzip"
"io"
"net/http"
"github.com/QuantumNous/new-api/constant"
"github.com/andybalholm/brotli"
"github.com/gin-gonic/gin"
2024-12-04 23:24:46 +08:00
)
type readCloser struct {
io.Reader
closeFn func() error
}
func (rc *readCloser) Close() error {
if rc.closeFn != nil {
return rc.closeFn()
}
return nil
}
2024-12-04 23:53:02 +08:00
func DecompressRequestMiddleware() gin.HandlerFunc {
2024-12-04 23:24:46 +08:00
return func(c *gin.Context) {
2024-12-04 23:53:02 +08:00
if c.Request.Body == nil || c.Request.Method == http.MethodGet {
c.Next()
return
}
maxMB := constant.MaxRequestBodyMB
if maxMB <= 0 {
maxMB = 32
}
maxBytes := int64(maxMB) << 20
origBody := c.Request.Body
wrapMaxBytes := func(body io.ReadCloser) io.ReadCloser {
return http.MaxBytesReader(c.Writer, body, maxBytes)
}
2024-12-04 23:53:02 +08:00
switch c.GetHeader("Content-Encoding") {
case "gzip":
gzipReader, err := gzip.NewReader(origBody)
2024-12-04 23:24:46 +08:00
if err != nil {
_ = origBody.Close()
2024-12-04 23:24:46 +08:00
c.AbortWithStatus(http.StatusBadRequest)
return
}
// Replace the request body with the decompressed data, and enforce a max size (post-decompression).
c.Request.Body = wrapMaxBytes(&readCloser{
Reader: gzipReader,
closeFn: func() error {
_ = gzipReader.Close()
return origBody.Close()
},
})
2024-12-04 23:53:02 +08:00
c.Request.Header.Del("Content-Encoding")
case "br":
reader := brotli.NewReader(origBody)
c.Request.Body = wrapMaxBytes(&readCloser{
Reader: reader,
closeFn: func() error {
return origBody.Close()
},
})
2024-12-04 23:53:02 +08:00
c.Request.Header.Del("Content-Encoding")
default:
// Even for uncompressed bodies, enforce a max size to avoid huge request allocations.
c.Request.Body = wrapMaxBytes(origBody)
2024-12-04 23:24:46 +08:00
}
// Continue processing the request
c.Next()
}
}