forked from uptrace/bunrouter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router_test.go
831 lines (681 loc) · 22.3 KB
/
router_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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
package bunrouter
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
"github.com/stretchr/testify/require"
)
func simpleHandler(w http.ResponseWriter, req Request) error {
return nil
}
type TestScenario struct {
description string
}
var scenarios = []TestScenario{
{"Test with URL.Path and normal ServeHTTP"},
}
func TestRequestWithContext(t *testing.T) {
router := New()
router.GET("/user/:param", func(w http.ResponseWriter, req Request) error {
value1 := req.Param("param")
require.Equal(t, "hello", value1)
value2 := req.WithContext(context.TODO()).Param("param")
require.Equal(t, value1, value2)
return nil
})
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/user/hello", nil)
router.ServeHTTP(w, req)
}
func TestMethods(t *testing.T) {
for _, scenario := range scenarios {
t.Log(scenario.description)
testMethods(t)
}
}
func testMethods(t *testing.T) {
var result string
makeHandler := func(method string) HandlerFunc {
return func(w http.ResponseWriter, r Request) error {
result = method
return nil
}
}
router := New()
router.GET("/user/:param", makeHandler("GET"))
router.POST("/user/:param", makeHandler("POST"))
router.PATCH("/user/:param", makeHandler("PATCH"))
router.PUT("/user/:param", makeHandler("PUT"))
router.DELETE("/user/:param", makeHandler("DELETE"))
testMethod := func(method, expect string) {
result = "" // reset
w := httptest.NewRecorder()
r, _ := http.NewRequest(method, "/user/"+method, nil)
router.ServeHTTP(w, r)
if expect == "" {
require.Equal(t, http.StatusMethodNotAllowed, w.Code)
} else {
require.Equal(t, expect, result)
}
}
testMethod("GET", "GET")
testMethod("POST", "POST")
testMethod("PATCH", "PATCH")
testMethod("PUT", "PUT")
testMethod("DELETE", "DELETE")
testMethod("HEAD", "")
router.HEAD("/user/:param", makeHandler("HEAD"))
testMethod("HEAD", "HEAD")
}
func TestNotFound(t *testing.T) {
calledNotFound := false
notFoundHandler := func(w http.ResponseWriter, r Request) error {
calledNotFound = true
return nil
}
router := New()
router.GET("/user/abc", simpleHandler)
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/abc/", nil)
router.ServeHTTP(w, r)
if w.Code != http.StatusNotFound {
t.Errorf("Expected error 404 from built-in not found handler but saw %d", w.Code)
}
// Now try with a custome handler.
router = New(WithNotFoundHandler(notFoundHandler))
router.GET("/user/abc", simpleHandler)
router.ServeHTTP(w, r)
if !calledNotFound {
t.Error("Custom not found handler was not called")
}
}
func TestRedirect(t *testing.T) {
for _, scenario := range scenarios {
t.Log(scenario.description)
testRedirect(t)
}
}
func testRedirect(t *testing.T) {
redirHandler := func(w http.ResponseWriter, r Request) error {
// Returning this instead of 200 makes it easy to verify that the handler is actually getting called.
w.WriteHeader(http.StatusNoContent)
return nil
}
router := New()
expectedCodeMap := map[string]int{
"GET": http.StatusMovedPermanently,
"POST": http.StatusMovedPermanently,
"PUT": http.StatusMovedPermanently,
}
router.GET("/slash/", redirHandler)
router.GET("/noslash", redirHandler)
router.POST("/slash/", redirHandler)
router.POST("/noslash", redirHandler)
router.PUT("/slash/", redirHandler)
router.PUT("/noslash", redirHandler)
for method, expectedCode := range expectedCodeMap {
t.Logf("Testing method %s, expecting code %d", method, expectedCode)
w := httptest.NewRecorder()
r, _ := http.NewRequest(method, "/slash", nil)
router.ServeHTTP(w, r)
if w.Code != expectedCode {
t.Errorf("/slash expected code %d, saw %d", expectedCode, w.Code)
}
if expectedCode != http.StatusNoContent && w.Header().Get("Location") != "/slash/" {
t.Errorf("/slash was not redirected to /slash/")
}
r, _ = http.NewRequest(method, "/noslash/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != expectedCode {
t.Errorf("/noslash/ expected code %d, saw %d", expectedCode, w.Code)
}
if expectedCode != http.StatusNoContent && w.Header().Get("Location") != "/noslash" {
t.Errorf("/noslash/ was redirected to `%s` instead of /noslash", w.Header().Get("Location"))
}
r, _ = http.NewRequest(method, "//noslash/", nil)
if r.RequestURI == "//noslash/" { // http.NewRequest parses this out differently
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != expectedCode {
t.Errorf("//noslash/ expected code %d, saw %d", expectedCode, w.Code)
}
if expectedCode != http.StatusNoContent && w.Header().Get("Location") != "/noslash" {
t.Errorf("//noslash/ was redirected to %s, expected /noslash", w.Header().Get("Location"))
}
}
// Test nonredirect cases
r, _ = http.NewRequest(method, "/noslash", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusNoContent {
t.Errorf("/noslash (non-redirect) expected code %d, saw %d", http.StatusNoContent, w.Code)
}
r, _ = http.NewRequest(method, "/noslash?a=1&b=2", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusNoContent {
t.Errorf("/noslash (non-redirect) expected code %d, saw %d", http.StatusNoContent, w.Code)
}
r, _ = http.NewRequest(method, "/slash/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusNoContent {
t.Errorf("/slash/ (non-redirect) expected code %d, saw %d", http.StatusNoContent, w.Code)
}
r, _ = http.NewRequest(method, "/slash/?a=1&b=2", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusNoContent {
t.Errorf("/slash/?a=1&b=2 expected code %d, saw %d", http.StatusNoContent, w.Code)
}
// Test querystring and fragment cases
r, _ = http.NewRequest(method, "/slash?a=1&b=2", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != expectedCode {
t.Errorf("/slash?a=1&b=2 expected code %d, saw %d", expectedCode, w.Code)
}
if expectedCode != http.StatusNoContent && w.Header().Get("Location") != "/slash/?a=1&b=2" {
t.Errorf("/slash?a=1&b=2 was redirected to %s", w.Header().Get("Location"))
}
r, _ = http.NewRequest(method, "/noslash/?a=1&b=2", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != expectedCode {
t.Errorf("/noslash/?a=1&b=2 expected code %d, saw %d", expectedCode, w.Code)
}
if expectedCode != http.StatusNoContent && w.Header().Get("Location") != "/noslash?a=1&b=2" {
t.Errorf("/noslash/?a=1&b=2 was redirected to %s", w.Header().Get("Location"))
}
}
}
func TestRedirectClean(t *testing.T) {
router := New()
router.GET("/slash/", simpleHandler)
router.GET("/noslash", simpleHandler)
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", "/slash", nil)
router.ServeHTTP(w, r)
require.Equal(t, http.StatusMovedPermanently, w.Code)
r, _ = http.NewRequest("GET", "/noslash/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
require.Equal(t, http.StatusMovedPermanently, w.Code)
r, _ = http.NewRequest("GET", "//noslash", nil)
r.URL.Path = "//noslash"
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
require.Equal(t, http.StatusMovedPermanently, w.Code)
}
func TestRoot(t *testing.T) {
for _, scenario := range scenarios {
t.Log(scenario.description)
var handlerCalled bool
handler := func(w http.ResponseWriter, r Request) error {
handlerCalled = true
return nil
}
router := New()
router.GET("/", handler)
req, err := http.NewRequest("GET", "/", nil)
require.NoError(t, err)
w := new(mockResponseWriter)
router.ServeHTTP(w, req)
if !handlerCalled {
t.Error("Handler not called for root path")
}
}
}
func TestWildcardAtSplitNode(t *testing.T) {
var suppliedParam string
simpleHandler := func(w http.ResponseWriter, r Request) error {
t.Log(r.Params().Map())
suppliedParam, _ = r.Params().Get("slug")
return nil
}
router := New()
router.GET("/pumpkin", simpleHandler)
router.GET("/passing", simpleHandler)
router.GET("/:slug", simpleHandler)
router.GET("/:slug/abc", simpleHandler)
r, _ := http.NewRequest("GET", "/patch", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if suppliedParam != "patch" {
t.Errorf("Expected param patch, saw %s", suppliedParam)
}
if w.Code != http.StatusOK {
t.Errorf("Expected status 200 for path /patch, saw %d", w.Code)
}
suppliedParam = ""
r, _ = http.NewRequest("GET", "/patch/abc", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if suppliedParam != "patch" {
t.Errorf("Expected param patch, saw %s", suppliedParam)
}
if w.Code != http.StatusOK {
t.Errorf("Expected status 200 for path /patch/abc, saw %d", w.Code)
}
r, _ = http.NewRequest("GET", "/patch/def", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
require.Equal(t, http.StatusNotFound, w.Code)
}
func TestQueryString(t *testing.T) {
var param string
handler := func(w http.ResponseWriter, r Request) error {
param = r.Params().ByName("param")
return nil
}
router := New()
router.GET("/static", handler)
router.GET("/named/:param", handler)
router.GET("/wildcard/*param", handler)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/static?abc=def&ghi=jkl", nil)
router.ServeHTTP(w, req)
require.Equal(t, "", param)
req, _ = http.NewRequest("GET", "/named/aaa?abc=def", nil)
router.ServeHTTP(w, req)
require.Equal(t, "aaa", param)
req, _ = http.NewRequest("GET", "/wildcard/bbb?abc=def", nil)
router.ServeHTTP(w, req)
require.Equal(t, "bbb", param)
}
func TestRedirectEscapedPath(t *testing.T) {
router := New()
testHandler := func(w http.ResponseWriter, r Request) error {
return nil
}
router.GET("/:escaped/", testHandler)
w := httptest.NewRecorder()
u, err := url.Parse("/Test P@th")
require.NoError(t, err)
req, _ := http.NewRequest("GET", u.String(), nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusMovedPermanently, w.Code)
location := w.Header().Get("Location")
require.Equal(t, "/Test%20P@th/", location)
}
func TestMiddleware(t *testing.T) {
var execLog []string
record := func(s string) {
execLog = append(execLog, s)
}
newHandler := func(name string) HandlerFunc {
return func(w http.ResponseWriter, r Request) error {
record(name)
return nil
}
}
newMiddleware := func(name string) MiddlewareFunc {
return func(next HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r Request) error {
record(name)
return next(w, r)
}
}
}
router := New()
w := httptest.NewRecorder()
// No middlewares.
{
router.GET("/h1", newHandler("h1"))
req, _ := http.NewRequest("GET", "/h1", nil)
router.ServeHTTP(w, req)
require.Equal(t, []string{"h1"}, execLog)
}
g := router.NewGroup("", WithMiddleware(newMiddleware("m1")))
g.GET("/h2", newHandler("h2"))
// Test route with and without middleware.
{
execLog = nil
req, _ := http.NewRequest("GET", "/h1", nil)
router.ServeHTTP(w, req)
req, _ = http.NewRequest("GET", "/h2", nil)
router.ServeHTTP(w, req)
require.Equal(t, []string{"h1", "m1", "h2"}, execLog)
}
// NewGroup inherits middlewares but has its own stack.
{
execLog = nil
g := g.NewGroup("/g1", WithMiddleware(newMiddleware("m2")))
g.GET("/h3", newHandler("h3"))
req, _ := http.NewRequest("GET", "/h2", nil)
router.ServeHTTP(w, req)
req, _ = http.NewRequest("GET", "/g1/h3", nil)
router.ServeHTTP(w, req)
require.Equal(t, []string{"m1", "h2", "m1", "m2", "h3"}, execLog)
}
{
execLog = nil
g := g.NewGroup("/g2", WithMiddleware(func(next HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r Request) error {
record("m4")
return next(w, r)
}
}))
g.GET("/h6", func(w http.ResponseWriter, r Request) error {
record("h6")
return nil
})
req, _ := http.NewRequest("GET", "/g2/h6", nil)
router.ServeHTTP(w, req)
require.Equal(t, []string{"m1", "m4", "h6"}, execLog)
}
// Middleware can serve request without calling next.
{
execLog = nil
g := g.NewGroup("", WithMiddleware(func(_ HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, r Request) error {
record("m3")
w.WriteHeader(http.StatusBadRequest)
_, err := w.Write([]byte("pong"))
return err
}
}))
g.GET("/h5", newHandler("h5"))
req, _ := http.NewRequest("GET", "/h5", nil)
router.ServeHTTP(w, req)
require.Equal(t, []string{"m1", "m3"}, execLog)
if w.Code != http.StatusBadRequest {
t.Fatalf("got %d, wanted %d", w.Code, http.StatusBadRequest)
}
if w.Body.String() != "pong" {
t.Fatalf("got %s, wanted %s", w.Body.String(), "pong")
}
}
}
func TestCORSMiddleware(t *testing.T) {
corsMiddleware := func(next HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, req Request) error {
if req.Method == http.MethodOptions {
return nil
}
return next(w, req)
}
}
router := New()
router.NewGroup("/api",
// Install CORS only for this group.
WithMiddleware(corsMiddleware),
WithGroup(func(g *Group) {
g.GET("/users", simpleHandler)
}))
t.Run("normal request", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, "/api/users", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
})
t.Run("CORS request", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodOptions, "/api/users", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
})
t.Run("CORS to non-existant route", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodOptions, "/api", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
})
t.Run("not allowed method", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodPost, "/api/users", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusMethodNotAllowed, w.Code)
})
}
// When we find a node with a matching path but no handler for a method,
// we should fall through and continue searching the tree for a less specific
// match, i.e. a wildcard or catchall, that does have a handler for that method.
func TestMethodNotAllowedFallthrough(t *testing.T) {
var matchedMethod string
var matchedPath string
var matchedParams map[string]string
router := New()
addRoute := func(method, path string) {
router.Handle(method, path, func(w http.ResponseWriter, req Request) error {
matchedMethod = method
matchedPath = path
matchedParams = req.Params().Map()
return nil
})
}
checkRoute := func(method, path, expectedMethod, expectedPath string,
expectedCode int, expectedParams map[string]string) {
matchedMethod = ""
matchedPath = ""
matchedParams = nil
w := httptest.NewRecorder()
r, _ := http.NewRequest(method, path, nil)
router.ServeHTTP(w, r)
if expectedCode != w.Code {
t.Errorf("%s %s expected code %d, saw %d", method, path, expectedCode, w.Code)
}
if w.Code == 200 {
if matchedMethod != method || matchedPath != expectedPath {
t.Errorf("%s %s expected %s %s, saw %s %s", method, path,
expectedMethod, expectedPath, matchedMethod, matchedPath)
}
if !reflect.DeepEqual(matchedParams, expectedParams) {
t.Errorf("%s %s expected params %+v, saw %+v", method, path, expectedParams, matchedParams)
}
}
}
addRoute("GET", "/apple/banana/cat")
addRoute("GET", "/apple/potato")
addRoute("POST", "/apple/banana/:abc")
addRoute("POST", "/apple/ban/def")
addRoute("DELETE", "/apple/:seed")
addRoute("DELETE", "/apple/*path")
addRoute("OPTIONS", "/apple/*path")
checkRoute("GET", "/apple/banana/cat", "GET", "/apple/banana/cat", 200, nil)
checkRoute("POST", "/apple/banana/cat", "POST", "/apple/banana/:abc", 200,
map[string]string{"abc": "cat"})
checkRoute("POST", "/apple/banana/dog", "POST", "/apple/banana/:abc", 200,
map[string]string{"abc": "dog"})
// Wildcards should be checked before catchalls
checkRoute("DELETE", "/apple/banana", "DELETE", "/apple/:seed", 200,
map[string]string{"seed": "banana"})
checkRoute("DELETE", "/apple/banana/cat", "DELETE", "/apple/*path", 200,
map[string]string{"path": "banana/cat"})
checkRoute("POST", "/apple/ban/def", "POST", "/apple/ban/def", 200, nil)
checkRoute("OPTIONS", "/apple/ban/def", "OPTIONS", "/apple/*path", 200,
map[string]string{"path": "ban/def"})
checkRoute("GET", "/apple/ban/def", "", "", 405, nil)
// Always fallback to the matching handler no matter how many other
// nodes without proper handlers are found on the way.
checkRoute("OPTIONS", "/apple/banana/cat", "OPTIONS", "/apple/*path", 200,
map[string]string{"path": "banana/cat"})
checkRoute("OPTIONS", "/apple/bbbb", "OPTIONS", "/apple/*path", 200,
map[string]string{"path": "bbbb"})
// Nothing matches on patch
checkRoute("PATCH", "/apple/banana/cat", "", "", 405, nil)
checkRoute("PATCH", "/apple/potato", "", "", 405, nil)
// And some 404 tests for good measure
checkRoute("GET", "/abc", "", "", 404, nil)
checkRoute("OPTIONS", "/apple", "", "", 301, nil)
}
func TestWildcardNode(t *testing.T) {
var route string
var params map[string]string
handler := func(w http.ResponseWriter, req Request) error {
route = req.Params().Route()
params = req.Params().Map()
return nil
}
router := New()
router.GET("/*path", handler)
router.GET("/static/*path", handler)
type Test struct {
path string
params map[string]string
}
for _, test := range []Test{
{"/", map[string]string{"path": ""}},
{"/foo", map[string]string{"path": "foo"}},
{"/foo/bar", map[string]string{"path": "foo/bar"}},
{"/static", map[string]string{"path": "static"}},
} {
t.Run(fmt.Sprintf("path=%s", test.path), func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, test.path, nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "/*path", route)
require.Equal(t, test.params, params)
})
}
for _, test := range []Test{
{"/static/", map[string]string{"path": ""}},
{"/static/foo", map[string]string{"path": "foo"}},
{"/static/foo/bar", map[string]string{"path": "foo/bar"}},
} {
t.Run(fmt.Sprintf("path=%s", test.path), func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest(http.MethodGet, test.path, nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "/static/*path", route)
require.Equal(t, test.params, params)
})
}
}
func TestFiveColonRoute(t *testing.T) {
router := New()
router.GET("/", simpleHandler)
router.GET("/:a/:b/:c/:d/:e", simpleHandler)
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/test/test/test/test/test", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
}
func TestRoutesWithCommonPrefix(t *testing.T) {
router := New()
router.GET("/campaigns", simpleHandler)
router.GET("/causes", simpleHandler)
{
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/ca", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
}
{
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
}
}
func TestNotAllowedMiddleware(t *testing.T) {
var stack []string
middleware := func(next HandlerFunc) HandlerFunc {
return func(w http.ResponseWriter, req Request) error {
stack = append(stack, "middleware")
return next(w, req)
}
}
handler := func(w http.ResponseWriter, req Request) error {
stack = append(stack, "handler")
return nil
}
router := New()
router.NewGroup("/hello",
WithMiddleware(middleware),
WithGroup(func(group *Group) {
group.GET("", handler)
}),
)
t.Run("existing route", func(t *testing.T) {
stack = nil
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/hello", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, []string{"middleware", "handler"}, stack)
})
t.Run("not allowed method", func(t *testing.T) {
stack = nil
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/hello", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusMethodNotAllowed, w.Code)
require.Equal(t, []string{"middleware"}, stack)
})
t.Run("not found route", func(t *testing.T) {
stack = nil
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/hello/world", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
require.Nil(t, stack)
})
}
func TestNamedAndWildcard(t *testing.T) {
router := New()
router.GET("/api/internal", func(w http.ResponseWriter, req Request) error {
require.Equal(t, "/api/internal", req.Route())
return nil
})
router.GET("/api/internal/*params", func(w http.ResponseWriter, req Request) error {
require.Equal(t, "/api/internal/*params", req.Route())
return nil
})
t.Run("named route", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/internal", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
})
t.Run("empty wildcard route", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/internal/", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
})
t.Run("non-empty wildcard route", func(t *testing.T) {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/api/internal/foo/bar", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
})
}
func TestSplitRoute(t *testing.T) {
type Test struct {
route string
parts []string
params map[string]int
}
tests := []Test{
{"/", []string{}, nil},
{"/static", []string{"static"}, nil},
{"/static/", []string{"static/"}, nil},
{"/static/foo", []string{"static/foo"}, nil},
{"/static/:foo", []string{"static/", ":"}, map[string]int{"foo": 0}},
{"/static/:foo/bar", []string{"static/", ":", "/bar"}, map[string]int{"foo": 0}},
{"/static/*path", []string{"static/", "*"}, map[string]int{"path": 0}},
{"/*path", []string{"*"}, map[string]int{"path": 0}},
{"/:foo/*path", []string{":", "/", "*"}, map[string]int{"foo": 0, "path": 1}},
{"/:foo/static/*path", []string{":", "/static/", "*"}, map[string]int{"foo": 0, "path": 1}},
{
"/:a/:b/:c/:d/:e",
[]string{":", "/", ":", "/", ":", "/", ":", "/", ":"},
map[string]int{"a": 0, "b": 1, "c": 2, "d": 3, "e": 4},
},
}
for _, test := range tests {
t.Run(fmt.Sprintf("route=%s", test.route), func(t *testing.T) {
parts, params := splitRoute(test.route)
require.Equal(t, test.parts, parts)
require.Equal(t, test.params, params)
})
}
}