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
60
61
62
63
64
65
66
67
68
69
70
|
package urilimiter
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestNewMiddleware(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "hello")
})
tests := map[string]struct {
limit int
url string
expectedStatus int
}{
"with_disabled_middleware": {
limit: 0,
url: "/index.html",
expectedStatus: http.StatusOK,
},
"with_limit_set_to_request_length": {
limit: 17,
url: "/index.html?q=a#b",
expectedStatus: http.StatusOK,
},
"with_uri_length_exceeding_the_limit": {
limit: 17,
url: "/index1.html?q=a#b",
expectedStatus: http.StatusRequestURITooLong,
},
"with_uri_length_exceeding_the_limit_with_query": {
limit: 17,
url: "/index.html?q=aa#b",
expectedStatus: http.StatusRequestURITooLong,
},
"with_uri_length_exceeding_the_limit_with_fragment": {
limit: 17,
url: "/index.html?q=a#bb",
expectedStatus: http.StatusRequestURITooLong,
},
}
for tn, tt := range tests {
t.Run(tn, func(t *testing.T) {
middleware := NewMiddleware(handler, tt.limit)
ww := httptest.NewRecorder()
rr := httptest.NewRequest(http.MethodGet, tt.url, nil)
middleware.ServeHTTP(ww, rr)
res := ww.Result()
defer res.Body.Close()
require.Equal(t, tt.expectedStatus, res.StatusCode)
if tt.expectedStatus == http.StatusOK {
b, err := io.ReadAll(res.Body)
require.NoError(t, err)
require.Equal(t, "hello", string(b))
}
})
}
}
|