@@ -83,3 +83,92 @@ func TestBodyLimitReader(t *testing.T) {
83
83
assert .Equal (t , 2 , n )
84
84
assert .Equal (t , nil , err )
85
85
}
86
+
87
+ func TestBodyLimitWithConfig_Skipper (t * testing.T ) {
88
+ e := echo .New ()
89
+ h := func (c echo.Context ) error {
90
+ body , err := io .ReadAll (c .Request ().Body )
91
+ if err != nil {
92
+ return err
93
+ }
94
+ return c .String (http .StatusOK , string (body ))
95
+ }
96
+ mw := BodyLimitWithConfig (BodyLimitConfig {
97
+ Skipper : func (c echo.Context ) bool {
98
+ return true
99
+ },
100
+ Limit : "2B" , // if not skipped this limit would make request to fail limit check
101
+ })
102
+
103
+ hw := []byte ("Hello, World!" )
104
+ req := httptest .NewRequest (http .MethodPost , "/" , bytes .NewReader (hw ))
105
+ rec := httptest .NewRecorder ()
106
+ c := e .NewContext (req , rec )
107
+
108
+ err := mw (h )(c )
109
+ assert .NoError (t , err )
110
+ assert .Equal (t , http .StatusOK , rec .Code )
111
+ assert .Equal (t , hw , rec .Body .Bytes ())
112
+ }
113
+
114
+ func TestBodyLimitWithConfig (t * testing.T ) {
115
+ var testCases = []struct {
116
+ name string
117
+ givenLimit string
118
+ whenBody []byte
119
+ expectBody []byte
120
+ expectError string
121
+ }{
122
+ {
123
+ name : "ok, body is less than limit" ,
124
+ givenLimit : "10B" ,
125
+ whenBody : []byte ("123456789" ),
126
+ expectBody : []byte ("123456789" ),
127
+ expectError : "" ,
128
+ },
129
+ {
130
+ name : "nok, body is more than limit" ,
131
+ givenLimit : "9B" ,
132
+ whenBody : []byte ("1234567890" ),
133
+ expectBody : []byte (nil ),
134
+ expectError : "code=413, message=Request Entity Too Large" ,
135
+ },
136
+ }
137
+
138
+ for _ , tc := range testCases {
139
+ t .Run (tc .name , func (t * testing.T ) {
140
+ e := echo .New ()
141
+ h := func (c echo.Context ) error {
142
+ body , err := io .ReadAll (c .Request ().Body )
143
+ if err != nil {
144
+ return err
145
+ }
146
+ return c .String (http .StatusOK , string (body ))
147
+ }
148
+ mw := BodyLimitWithConfig (BodyLimitConfig {
149
+ Limit : tc .givenLimit ,
150
+ })
151
+
152
+ req := httptest .NewRequest (http .MethodPost , "/" , bytes .NewReader (tc .whenBody ))
153
+ rec := httptest .NewRecorder ()
154
+ c := e .NewContext (req , rec )
155
+
156
+ err := mw (h )(c )
157
+ if tc .expectError != "" {
158
+ assert .EqualError (t , err , tc .expectError )
159
+ } else {
160
+ assert .NoError (t , err )
161
+ }
162
+ // not testing status as middlewares return error instead of committing it and OK cases are anyway 200
163
+ assert .Equal (t , tc .expectBody , rec .Body .Bytes ())
164
+ })
165
+ }
166
+ }
167
+
168
+ func TestBodyLimit_panicOnInvalidLimit (t * testing.T ) {
169
+ assert .PanicsWithError (
170
+ t ,
171
+ "echo: invalid body-limit=" ,
172
+ func () { BodyLimit ("" ) },
173
+ )
174
+ }
0 commit comments