feat(gin): improve request body handling and error reporting
Some checks failed
Publish Docker image (Multi Registries, native amd64+arm64) / Build & push (amd64) [native] (push) Has been cancelled
Publish Docker image (Multi Registries, native amd64+arm64) / Build & push (arm64) [native] (push) Has been cancelled
Publish Docker image (Multi Registries, native amd64+arm64) / Create multi-arch manifests (Docker Hub) (push) Has been cancelled
Build Electron App / build (windows-latest) (push) Has been cancelled
Build Electron App / release (push) Has been cancelled
Release (Linux, macOS, Windows) / Linux Release (push) Has been cancelled
Release (Linux, macOS, Windows) / macOS Release (push) Has been cancelled
Release (Linux, macOS, Windows) / Windows Release (push) Has been cancelled

This commit is contained in:
CaIon 2025-12-20 13:34:10 +08:00
parent 3523acfc2c
commit c2a6193497

View File

@ -2,7 +2,7 @@ package common
import ( import (
"bytes" "bytes"
"errors" "fmt"
"io" "io"
"mime" "mime"
"mime/multipart" "mime/multipart"
@ -12,6 +12,7 @@ import (
"time" "time"
"github.com/QuantumNous/new-api/constant" "github.com/QuantumNous/new-api/constant"
"github.com/pkg/errors"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -39,8 +40,15 @@ func GetRequestBody(c *gin.Context) ([]byte, error) {
} }
} }
maxMB := constant.MaxRequestBodyMB maxMB := constant.MaxRequestBodyMB
if maxMB <= 0 { if maxMB < 0 {
maxMB = 32 // no limit
body, err := io.ReadAll(c.Request.Body)
_ = c.Request.Body.Close()
if err != nil {
return nil, err
}
c.Set(KeyRequestBody, body)
return body, nil
} }
maxBytes := int64(maxMB) << 20 maxBytes := int64(maxMB) << 20
@ -49,13 +57,13 @@ func GetRequestBody(c *gin.Context) ([]byte, error) {
if err != nil { if err != nil {
_ = c.Request.Body.Close() _ = c.Request.Body.Close()
if IsRequestBodyTooLargeError(err) { if IsRequestBodyTooLargeError(err) {
return nil, ErrRequestBodyTooLarge return nil, errors.Wrap(ErrRequestBodyTooLarge, fmt.Sprintf("request body exceeds %d MB", maxMB))
} }
return nil, err return nil, err
} }
_ = c.Request.Body.Close() _ = c.Request.Body.Close()
if int64(len(body)) > maxBytes { if int64(len(body)) > maxBytes {
return nil, ErrRequestBodyTooLarge return nil, errors.Wrap(ErrRequestBodyTooLarge, fmt.Sprintf("request body exceeds %d MB", maxMB))
} }
c.Set(KeyRequestBody, body) c.Set(KeyRequestBody, body)
return body, nil return body, nil