-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsize_test.go
59 lines (52 loc) · 1.35 KB
/
size_test.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
59
package limits
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestRequestSizeLimiterOK(t *testing.T) {
router := gin.New()
router.Use(RequestSizeLimiter(10))
router.POST("/test_ok", func(c *gin.Context) {
_, _ = ioutil.ReadAll(c.Request.Body)
if len(c.Errors) > 0 {
return
}
c.Request.Body.Close()
c.String(http.StatusOK, "OK")
})
resp := performRequest(http.MethodPost, "/test_ok", "big=abc", router)
if resp.Code != http.StatusOK {
t.Fatalf("error posting - http status %v", resp.Code)
}
}
func TestRequestSizeLimiterOver(t *testing.T) {
router := gin.New()
router.Use(RequestSizeLimiter(10))
router.POST("/test_large", func(c *gin.Context) {
_, _ = ioutil.ReadAll(c.Request.Body)
if len(c.Errors) > 0 {
return
}
c.Request.Body.Close()
c.String(http.StatusOK, "OK")
})
resp := performRequest(http.MethodPost, "/test_large", "big=abcdefghijklmnop", router)
if resp.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("error posting - http status %v", resp.Code)
}
}
func performRequest(method, target, body string, router *gin.Engine) *httptest.ResponseRecorder {
var buf *bytes.Buffer
if body != "" {
buf = new(bytes.Buffer)
buf.WriteString(body)
}
r := httptest.NewRequest(method, target, buf)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
return w
}