-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_size.go
49 lines (43 loc) · 1.19 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
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"
)
// 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.Wrap(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 {
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)
}