@@ -12,6 +12,7 @@ import (
12
12
"github.com/labstack/gommon/log"
13
13
"github.com/rs/zerolog"
14
14
"github.com/stretchr/testify/assert"
15
+
15
16
"github.com/ziflex/lecho/v3"
16
17
)
17
18
@@ -161,4 +162,64 @@ func TestMiddleware(t *testing.T) {
161
162
assert .Contains (t , str , `"level":"info"` )
162
163
assert .NotContains (t , str , `"level":"warn"` )
163
164
})
165
+
166
+ t .Run ("should skip middleware before calling next handler when Skipper func returns true" , func (t * testing.T ) {
167
+ e := echo .New ()
168
+ req := httptest .NewRequest (http .MethodGet , "/skip" , nil )
169
+ req .Header .Set (echo .HeaderContentType , echo .MIMEApplicationJSON )
170
+ rec := httptest .NewRecorder ()
171
+ c := e .NewContext (req , rec )
172
+
173
+ b := & bytes.Buffer {}
174
+ l := lecho .New (b )
175
+ l .SetLevel (log .INFO )
176
+ m := lecho .Middleware (lecho.Config {
177
+ Logger : l ,
178
+ Skipper : func (c echo.Context ) bool {
179
+ return c .Request ().URL .Path == "/skip"
180
+ },
181
+ })
182
+
183
+ next := func (c echo.Context ) error {
184
+ return nil
185
+ }
186
+
187
+ handler := m (next )
188
+ err := handler (c )
189
+
190
+ assert .NoError (t , err , "should not return error" )
191
+
192
+ str := b .String ()
193
+ assert .Empty (t , str , "should not log anything" )
194
+ })
195
+
196
+ t .Run ("should skip middleware after calling next handler when AfterNextSkipper func returns true" , func (t * testing.T ) {
197
+ e := echo .New ()
198
+ req := httptest .NewRequest (http .MethodGet , "/" , nil )
199
+ req .Header .Set (echo .HeaderContentType , echo .MIMEApplicationJSON )
200
+ rec := httptest .NewRecorder ()
201
+ c := e .NewContext (req , rec )
202
+
203
+ b := & bytes.Buffer {}
204
+ l := lecho .New (b )
205
+ l .SetLevel (log .INFO )
206
+ m := lecho .Middleware (lecho.Config {
207
+ Logger : l ,
208
+ AfterNextSkipper : func (c echo.Context ) bool {
209
+ return c .Response ().Status == http .StatusMovedPermanently
210
+ },
211
+ })
212
+
213
+ next := func (c echo.Context ) error {
214
+ return c .Redirect (http .StatusMovedPermanently , "/other" )
215
+ }
216
+
217
+ handler := m (next )
218
+ err := handler (c )
219
+
220
+ assert .NoError (t , err , "should not return error" )
221
+
222
+ str := b .String ()
223
+ assert .Empty (t , str , "should not log anything" )
224
+ })
164
225
}
0 commit comments