-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_size.go
58 lines (50 loc) · 1.45 KB
/
middleware_size.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package ginKit
import (
limits "github.com/gin-contrib/size"
"github.com/gin-gonic/gin"
"github.com/richelieu-yang/chimera/v3/src/core/errorKit"
"github.com/richelieu-yang/chimera/v3/src/validateKit"
"net/http"
)
var (
RequestTooLargeError = errorKit.Newf("HTTP request too large")
)
// NewSizeLimiterMiddleware 参考了echo中的 middleware.BodyLimit()
/*
@param limit (1) 单位: MiB
(2) 必须 > 0
*/
func NewSizeLimiterMiddleware(limit int64) (gin.HandlerFunc, error) {
if err := validateKit.Var(limit, "gt=0"); err != nil {
return nil, errorKit.Wrapf(err, "invalid limit(%d)", limit)
}
// bodyLimit 单位: B
bodyLimit := limit << 20
return func(ctx *gin.Context) {
// (1) do nothing
if ctx.Request.Body == nil || ctx.Request.Body == http.NoBody {
ctx.Next()
return
}
// (2) Based on content length
if ctx.Request.ContentLength > bodyLimit {
// 参考: github.com/gin-contrib/size
_ = ctx.Error(RequestTooLargeError)
ctx.Header("connection", "close")
ctx.String(http.StatusRequestEntityTooLarge, "request too large")
ctx.AbortWithStatus(http.StatusRequestEntityTooLarge)
return
}
// (3) Based on content read
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, bodyLimit)
ctx.Next()
}, nil
}
// NewSizeLimiterMiddleware1
/*
gin-contrib/size
https://github.com/gin-contrib/size
*/
func NewSizeLimiterMiddleware1(limit int64) gin.HandlerFunc {
return limits.RequestSizeLimiter(limit)
}