Skip to content

Commit cc3ba39

Browse files
committed
feat(gin): improve request body handling and error reporting
1 parent 4ee595c commit cc3ba39

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

common/gin.go

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package common
22

33
import (
44
"bytes"
5-
"errors"
5+
"fmt"
66
"io"
77
"mime"
88
"mime/multipart"
@@ -12,6 +12,7 @@ import (
1212
"time"
1313

1414
"github.com/QuantumNous/new-api/constant"
15+
"github.com/pkg/errors"
1516

1617
"github.com/gin-gonic/gin"
1718
)
@@ -39,8 +40,15 @@ func GetRequestBody(c *gin.Context) ([]byte, error) {
3940
}
4041
}
4142
maxMB := constant.MaxRequestBodyMB
42-
if maxMB <= 0 {
43-
maxMB = 32
43+
if maxMB < 0 {
44+
// no limit
45+
body, err := io.ReadAll(c.Request.Body)
46+
_ = c.Request.Body.Close()
47+
if err != nil {
48+
return nil, err
49+
}
50+
c.Set(KeyRequestBody, body)
51+
return body, nil
4452
}
4553
maxBytes := int64(maxMB) << 20
4654

@@ -49,13 +57,13 @@ func GetRequestBody(c *gin.Context) ([]byte, error) {
4957
if err != nil {
5058
_ = c.Request.Body.Close()
5159
if IsRequestBodyTooLargeError(err) {
52-
return nil, ErrRequestBodyTooLarge
60+
return nil, errors.Wrap(ErrRequestBodyTooLarge, fmt.Sprintf("request body exceeds %d MB", maxMB))
5361
}
5462
return nil, err
5563
}
5664
_ = c.Request.Body.Close()
5765
if int64(len(body)) > maxBytes {
58-
return nil, ErrRequestBodyTooLarge
66+
return nil, errors.Wrap(ErrRequestBodyTooLarge, fmt.Sprintf("request body exceeds %d MB", maxMB))
5967
}
6068
c.Set(KeyRequestBody, body)
6169
return body, nil

0 commit comments

Comments
 (0)