-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhandler_factory.go
56 lines (48 loc) · 1.57 KB
/
handler_factory.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
package sizelimit
import (
"bytes"
"fmt"
"io"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
apierrors "github.com/kivra/kivra-api-errors"
"github.com/luraproject/lura/v2/config"
"github.com/luraproject/lura/v2/proxy"
krakendgin "github.com/luraproject/lura/v2/router/gin"
)
func ExceedsSizeLimit(c *gin.Context, limit int64) bool {
contentLength := c.Request.Header.Get("Content-Length")
size, _ := strconv.ParseInt(contentLength, 10, 64)
if size > limit { // trust Content-Length header only if it exceeds MaxSize
return true
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
bodyBuffer := new(bytes.Buffer)
_, err := io.Copy(bodyBuffer, c.Request.Body)
c.Request.Body = io.NopCloser(bodyBuffer)
return err != nil
}
func LimiterFactory(limit int64, handlerFunc gin.HandlerFunc) gin.HandlerFunc {
apierrors.Load()
apiError := apierrors.FromStatusOrFallback(http.StatusRequestEntityTooLarge)
apiError.Payload.LongMessage = fmt.Sprintf("Content length should not exceed %d B", limit)
return func(c *gin.Context) {
if ExceedsSizeLimit(c, limit) {
c.Writer.Header().Set(apierrors.ErrorCodeHeader, apiError.Payload.Code)
c.AbortWithStatusJSON(apiError.StatusCode, apiError.Payload)
return
}
handlerFunc(c)
}
}
func HandlerFactory(next krakendgin.HandlerFactory) krakendgin.HandlerFactory {
return func(remote *config.EndpointConfig, p proxy.Proxy) gin.HandlerFunc {
handlerFunc := next(remote, p)
cfg, ok := ConfigGetter(remote.ExtraConfig)
if !ok {
return handlerFunc
}
return LimiterFactory(cfg.MaxSize, handlerFunc)
}
}