-
Notifications
You must be signed in to change notification settings - Fork 0
/
router_test.go
1169 lines (952 loc) · 28.5 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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package router
import (
"bytes"
"fmt"
"io/ioutil"
"math/rand"
"net"
"net/http"
"net/http/httptest"
"os"
"reflect"
"runtime"
"strings"
"testing"
"time"
)
type readWriter struct {
net.Conn
r bytes.Buffer
w bytes.Buffer
}
var httpMethods = []string{
http.MethodGet,
http.MethodHead,
http.MethodPost,
http.MethodPut,
http.MethodPatch,
http.MethodDelete,
http.MethodConnect,
http.MethodOptions,
http.MethodTrace,
MethodWild,
"CUSTOM",
}
func randomHTTPMethod() string {
method := httpMethods[rand.Intn(len(httpMethods)-1)]
for method == MethodWild {
method = httpMethods[rand.Intn(len(httpMethods)-1)]
}
return method
}
func buildLocation(host, path string) string {
// return fmt.Sprintf("http://%s%s", host, path)
return path
}
var zeroTCPAddr = &net.TCPAddr{
IP: net.IPv4zero,
}
func (rw *readWriter) Close() error {
return nil
}
func (rw *readWriter) Read(b []byte) (int, error) {
return rw.r.Read(b)
}
func (rw *readWriter) Write(b []byte) (int, error) {
return rw.w.Write(b)
}
func (rw *readWriter) RemoteAddr() net.Addr {
return zeroTCPAddr
}
func (rw *readWriter) LocalAddr() net.Addr {
return zeroTCPAddr
}
func (rw *readWriter) SetReadDeadline(t time.Time) error {
return nil
}
func (rw *readWriter) SetWriteDeadline(t time.Time) error {
return nil
}
type assertFn func(rw *readWriter)
func assertWithTestServer(t *testing.T, uri string, handler http.HandlerFunc, fn assertFn) {
s := &http.Server{Handler: handler}
l, _ := net.Listen("tcp", "")
rw := &readWriter{}
ch := make(chan error)
conn, err := net.DialTCP("tcp", nil, l.Addr().(*net.TCPAddr))
if err != nil {
t.Fatalf("dial tcp %s", err)
}
conn.Write([]byte(uri))
go func() {
_, err := conn.Read(rw.r.Bytes())
if err != nil {
t.Fail()
}
}()
go func() {
ch <- s.Serve(l)
}()
select {
case err := <-ch:
if err != nil {
t.Fatalf("return error %s", err)
}
case <-time.After(5000 * time.Millisecond):
t.Fatalf("timeout")
}
fn(rw)
}
func catchPanic(testFunc func()) (recv interface{}) {
defer func() {
recv = recover()
}()
testFunc()
return
}
func TestRouter(t *testing.T) {
router := New()
routed := false
router.Handle(http.MethodGet, "/user/{name}", func(w http.ResponseWriter, r *http.Request) {
routed = true
want := "gopher"
param := UserValue(r, "name")
if param != want {
t.Fatalf("wrong wildcard values: want %s, got %s", want, param)
}
})
r := httptest.NewRequest("GET", "/user/gopher", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !routed {
t.Fatal("routing failed")
}
}
func TestRouterAPI(t *testing.T) {
var handled, get, head, post, put, patch, delete, connect, options, trace, any bool
httpHandler := func(w http.ResponseWriter, r *http.Request) {
handled = true
}
router := New()
router.GET("/GET", func(w http.ResponseWriter, r *http.Request) {
get = true
})
router.HEAD("/HEAD", func(w http.ResponseWriter, r *http.Request) {
head = true
})
router.POST("/POST", func(w http.ResponseWriter, r *http.Request) {
post = true
})
router.PUT("/PUT", func(w http.ResponseWriter, r *http.Request) {
put = true
})
router.PATCH("/PATCH", func(w http.ResponseWriter, r *http.Request) {
patch = true
})
router.DELETE("/DELETE", func(w http.ResponseWriter, r *http.Request) {
delete = true
})
router.CONNECT("/CONNECT", func(w http.ResponseWriter, r *http.Request) {
connect = true
})
router.OPTIONS("/OPTIONS", func(w http.ResponseWriter, r *http.Request) {
options = true
})
router.TRACE("/TRACE", func(w http.ResponseWriter, r *http.Request) {
trace = true
})
router.ANY("/ANY", func(w http.ResponseWriter, r *http.Request) {
any = true
})
router.Handle(http.MethodGet, "/Handler", httpHandler)
var request = func(method, path string) {
r := httptest.NewRequest(method, path, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
}
request(http.MethodGet, "/GET")
if !get {
t.Error("routing GET failed")
}
request(http.MethodHead, "/HEAD")
if !head {
t.Error("routing HEAD failed")
}
request(http.MethodPost, "/POST")
if !post {
t.Error("routing POST failed")
}
request(http.MethodPut, "/PUT")
if !put {
t.Error("routing PUT failed")
}
request(http.MethodPatch, "/PATCH")
if !patch {
t.Error("routing PATCH failed")
}
request(http.MethodDelete, "/DELETE")
if !delete {
t.Error("routing DELETE failed")
}
request(http.MethodConnect, "/CONNECT")
if !connect {
t.Error("routing CONNECT failed")
}
request(http.MethodOptions, "/OPTIONS")
if !options {
t.Error("routing OPTIONS failed")
}
request(http.MethodTrace, "/TRACE")
if !trace {
t.Error("routing TRACE failed")
}
request(http.MethodGet, "/Handler")
if !handled {
t.Error("routing Handler failed")
}
for _, method := range httpMethods {
request(method, "/ANY")
if !any {
t.Errorf("routing ANY failed - Method: %s", method)
}
any = false
}
}
func TestRouterInvalidInput(t *testing.T) {
router := New()
handle := func(w http.ResponseWriter, r *http.Request) {}
recv := catchPanic(func() {
router.Handle("", "/", handle)
})
if recv == nil {
t.Fatal("registering empty method did not panic")
}
recv = catchPanic(func() {
router.GET("", handle)
})
if recv == nil {
t.Fatal("registering empty path did not panic")
}
recv = catchPanic(func() {
router.GET("noSlashRoot", handle)
})
if recv == nil {
t.Fatal("registering path not beginning with '/' did not panic")
}
recv = catchPanic(func() {
router.GET("/", nil)
})
if recv == nil {
t.Fatal("registering nil handler did not panic")
}
}
func TestRouterRegexUserValues(t *testing.T) {
mux := New()
mux.GET("/metrics", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
v4 := mux.Group("/v4")
id := v4.Group("/{id:^[1-9]\\d*}")
var v1 interface{}
id.GET("/click", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
v1 = UserValue(r, "id")
})
r := httptest.NewRequest("GET", "/v4/123/click", nil)
mux.ServeHTTP(httptest.NewRecorder(), r)
if v1 != "123" {
t.Fatalf(`expected "123" in user value, got %q`, v1)
}
r = httptest.NewRequest("GET", "/metrics", nil)
mux.ServeHTTP(httptest.NewRecorder(), r)
if v1 != "123" {
t.Fatalf(`expected "123" in user value, got %q`, v1)
}
}
func TestRouterChaining(t *testing.T) {
router1 := New()
router2 := New()
router1.NotFound = router2.ServeHTTP
fooHit := false
router1.POST("/foo", func(w http.ResponseWriter, r *http.Request) {
fooHit = true
w.WriteHeader(http.StatusOK)
})
barHit := false
router2.POST("/bar", func(w http.ResponseWriter, r *http.Request) {
barHit = true
w.WriteHeader(http.StatusOK)
})
r := httptest.NewRequest("POST", "/foo", nil)
w := httptest.NewRecorder()
router1.ServeHTTP(w, r)
if !(w.Code == http.StatusOK && fooHit) {
t.Errorf("Regular routing failed with router chaining.")
t.FailNow()
}
r = httptest.NewRequest("POST", "/bar", nil)
w = httptest.NewRecorder()
router1.ServeHTTP(w, r)
if !(w.Code == http.StatusOK && barHit) {
t.Errorf("Chained routing failed with router chaining.")
t.FailNow()
}
r = httptest.NewRequest("POST", "/qax", nil)
w = httptest.NewRecorder()
router1.ServeHTTP(w, r)
if !(w.Code == http.StatusNotFound) {
t.Errorf("NotFound behavior failed with router chaining.")
t.FailNow()
}
}
func TestRouterMutable(t *testing.T) {
handler1 := func(w http.ResponseWriter, r *http.Request) {}
handler2 := func(w http.ResponseWriter, r *http.Request) {}
router := New()
router.Mutable(true)
if !router.treeMutable {
t.Errorf("Router.treesMutables is false")
}
for _, method := range httpMethods {
router.Handle(method, "/", handler1)
}
for method := range router.trees {
if !router.trees[method].Mutable {
t.Errorf("Method %d - Mutable == %v, want %v", method, router.trees[method].Mutable, true)
}
}
routes := []string{
"/",
"/api/{version}",
"/{filepath:*}",
"/user{user:.*}",
}
router = New()
for _, route := range routes {
for _, method := range httpMethods {
router.Handle(method, route, handler1)
}
for _, method := range httpMethods {
err := catchPanic(func() {
router.Handle(method, route, handler2)
})
if err == nil {
t.Errorf("Mutable 'false' - Method %s - Route %s - Expected panic", method, route)
}
h, _ := router.Lookup(method, route, nil)
if reflect.ValueOf(h).Pointer() != reflect.ValueOf(handler1).Pointer() {
t.Errorf("Mutable 'false' - Method %s - Route %s - Handler updated", method, route)
}
}
router.Mutable(true)
for _, method := range httpMethods {
err := catchPanic(func() {
router.Handle(method, route, handler2)
})
if err != nil {
t.Errorf("Mutable 'true' - Method %s - Route %s - Unexpected panic: %v", method, route, err)
}
h, _ := router.Lookup(method, route, nil)
if reflect.ValueOf(h).Pointer() != reflect.ValueOf(handler2).Pointer() {
t.Errorf("Method %s - Route %s - Handler is not updated", method, route)
}
}
router.Mutable(false)
}
}
func TestRouterOPTIONS(t *testing.T) {
handlerFunc := func(w http.ResponseWriter, r *http.Request) {}
router := New()
router.POST("/path", handlerFunc)
var checkHandling = func(path, expectedAllowed string, expectedStatusCode int) {
r := httptest.NewRequest(http.MethodOptions, path, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == expectedStatusCode) {
t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, "w.Header")
} else if allow := w.Header().Get("Allow"); allow != expectedAllowed {
t.Error("unexpected Allow header value: " + allow)
}
}
// test not allowed
// * (server)
checkHandling("*", "OPTIONS, POST", http.StatusOK)
// path
checkHandling("/path", "OPTIONS, POST", http.StatusOK)
r := httptest.NewRequest(http.MethodOptions, "/doesnotexist", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == http.StatusNotFound) {
t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, r.Header)
}
// add another method
router.GET("/path", handlerFunc)
// set a global OPTIONS handler
router.GlobalOPTIONS = func(w http.ResponseWriter, r *http.Request) {
// Adjust status code to 204
w.WriteHeader(http.StatusNoContent)
}
// test again
// * (server)
checkHandling("*", "GET, OPTIONS, POST", http.StatusNoContent)
// path
checkHandling("/path", "GET, OPTIONS, POST", http.StatusNoContent)
// custom handler
var custom bool
router.OPTIONS("/path", func(w http.ResponseWriter, r *http.Request) {
custom = true
})
// test again
// * (server)
checkHandling("*", "GET, OPTIONS, POST", http.StatusNoContent)
if custom {
t.Error("custom handler called on *")
}
// path
r = httptest.NewRequest(http.MethodOptions, "/path", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == http.StatusOK) {
t.Errorf("OPTIONS handling failed: Code=%d, Header=%v", w.Code, "w.Header")
}
if !custom {
t.Error("custom handler not called")
}
}
func TestRouterNotAllowed(t *testing.T) {
handlerFunc := func(w http.ResponseWriter, r *http.Request) {}
router := New()
router.POST("/path", handlerFunc)
var checkHandling = func(path, expectedAllowed string, expectedStatusCode int) {
r := httptest.NewRequest("GET", path, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == expectedStatusCode) {
t.Errorf("NotAllowed handling failed:: Code=%d, Header=%v", w.Code, "w.Header")
} else if allow := w.Header().Get("Allow"); allow != expectedAllowed {
t.Error("unexpected Allow header value: " + allow)
}
}
// test not allowed
checkHandling("/path", "OPTIONS, POST", http.StatusMethodNotAllowed)
// add another method
router.DELETE("/path", handlerFunc)
router.OPTIONS("/path", handlerFunc) // must be ignored
// test again
checkHandling("/path", "DELETE, OPTIONS, POST", http.StatusMethodNotAllowed)
// test custom handler
responseText := "custom method"
router.MethodNotAllowed = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot)
w.Write([]byte(responseText))
}
r := httptest.NewRequest("foo", "/path", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if got := w.Body.String(); !(got == responseText) {
t.Errorf("unexpected response got %q want %q", got, responseText)
}
if w.Code != http.StatusTeapot {
t.Errorf("unexpected response code %d want %d", w.Code, http.StatusTeapot)
}
if allow := string(w.Header().Get("Allow")); allow != "DELETE, OPTIONS, POST" {
t.Error("unexpected Allow header value: " + allow)
}
}
func testRouterNotFoundByMethod(t *testing.T, method string) {
handlerFunc := func(w http.ResponseWriter, r *http.Request) {}
host := "fast"
router := New()
router.Handle(method, "/path", handlerFunc)
router.Handle(method, "/dir/", handlerFunc)
router.Handle(method, "/", handlerFunc)
router.Handle(method, "/{proc}/StaTus", handlerFunc)
router.Handle(method, "/USERS/{name}/enTRies/", handlerFunc)
router.Handle(method, "/static/{filepath:*}", handlerFunc)
reqMethod := method
if method == MethodWild {
reqMethod = randomHTTPMethod()
}
// Moved Permanently, request with GET method
expectedCode := http.StatusMovedPermanently
switch {
case reqMethod == http.MethodConnect:
// CONNECT method does not allow redirects, so Not Found (404)
expectedCode = http.StatusNotFound
case reqMethod != http.MethodGet:
// Permanent Redirect, request with same method
expectedCode = http.StatusPermanentRedirect
}
type testRoute struct {
route string
code int
location string
}
testRoutes := []testRoute{
// {"", http.StatusOK, ""}, // TSR +/ (Not clean by router, this path is cleaned by fasthttp `ctx.Path()`)
// {"/../path", expectedCode, buildLocation(host, "/path")}, // CleanPath (Not clean by router, this path is cleaned by fasthttp `ctx.Path()`)
{"/nope", http.StatusNotFound, ""}, // NotFound
}
if method != http.MethodConnect {
testRoutes = append(testRoutes, []testRoute{
{"/path/", expectedCode, buildLocation(host, "/path")}, // TSR -/
{"/dir", expectedCode, buildLocation(host, "/dir/")}, // TSR +/
// {"/PATH", expectedCode, buildLocation(host, "/path")}, // Fixed Case
// {"/DIR/", expectedCode, buildLocation(host, "/dir/")}, // Fixed Case
// {"/PATH/", expectedCode, buildLocation(host, "/path")}, // Fixed Case -/
// {"/DIR", expectedCode, buildLocation(host, "/dir/")}, // Fixed Case +/
// {"/paTh/?name=foo", expectedCode, buildLocation(host, "/path?name=foo")}, // Fixed Case With Query Params +/
// {"/paTh?name=foo", expectedCode, buildLocation(host, "/path?name=foo")}, // Fixed Case With Query Params +/
// {"/sergio/status/", expectedCode, buildLocation(host, "/sergio/StaTus")}, // Fixed Case With Params -/
// {"/users/atreugo/eNtriEs", expectedCode, buildLocation(host, "/USERS/atreugo/enTRies/")}, // Fixed Case With Params +/
// {"/STatiC/test.go", expectedCode, buildLocation(host, "/static/test.go")}, // Fixed Case Wildcard
}...)
}
for _, tr := range testRoutes {
r := httptest.NewRequest(reqMethod, tr.route, nil)
r.Host = host
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
statusCode := w.Code
location := string(w.Header().Get("Location"))
if !(statusCode == tr.code && (statusCode == http.StatusNotFound || location == tr.location)) {
fn := t.Errorf
msg := "NotFound handling route '%s' failed: Method=%s, ReqMethod=%s, Code=%d, ExpectedCode=%d, Header=%v"
if runtime.GOOS == "windows" && strings.HasPrefix(tr.route, "/../") {
// See: https://github.com/valyala/fasthttp/issues/1226
// Not fail, because it is a known issue.
fn = t.Logf
msg = "ERROR: " + msg
}
fn(msg, tr.route, method, reqMethod, statusCode, tr.code, location)
}
}
// Test custom not found handler
var notFound bool
router.NotFound = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
notFound = true
}
r := httptest.NewRequest(reqMethod, "/nope", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == http.StatusNotFound && notFound == true) {
t.Errorf(
"Custom NotFound handling failed: Method=%s, ReqMethod=%s, Code=%d, Header=%v",
method, reqMethod, w.Code, "w.Header",
)
}
}
func TestRouterNotFound(t *testing.T) {
for _, method := range httpMethods {
testRouterNotFoundByMethod(t, method)
}
router := New()
handlerFunc := func(w http.ResponseWriter, r *http.Request) {}
host := "fast"
// Test other method than GET (want 308 instead of 301)
router.PATCH("/path", handlerFunc)
r := httptest.NewRequest(http.MethodPatch, "/path/?key=val", nil)
r.Host = host
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == http.StatusPermanentRedirect) &&
w.Header().Get("Location") == buildLocation(host, "/path?key=val") {
t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, "w.Header")
}
// Test special case where no node for the prefix "/" exists
router = New()
router.GET("/a", handlerFunc)
r = httptest.NewRequest(http.MethodPatch, "/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if !(w.Code == http.StatusNotFound) {
t.Errorf("NotFound handling route / failed: Code=%d", w.Code)
}
}
func TestRouterNotFound_MethodWild(t *testing.T) {
postFound, anyFound := false, false
router := New()
router.ANY("/{path:*}", func(w http.ResponseWriter, r *http.Request) { anyFound = true })
router.POST("/specific", func(w http.ResponseWriter, r *http.Request) { postFound = true })
for i := 0; i < 100; i++ {
router.Handle(
randomHTTPMethod(),
fmt.Sprintf("/%d", rand.Int63()),
func(w http.ResponseWriter, r *http.Request) {},
)
}
var request = func(method, path string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
return w
}
for _, method := range httpMethods {
w := request(method, "/specific")
if method == http.MethodPost {
if !postFound {
t.Errorf("Method '%s': not found", method)
}
} else {
if !anyFound {
t.Errorf("Method 'ANY' not found with request method %s", method)
}
}
status := w.Code
if status != http.StatusOK {
t.Errorf("Response status code == %d, want %d", status, http.StatusOK)
}
postFound, anyFound = false, false
}
}
func TestRouterPanicHandler(t *testing.T) {
router := New()
panicHandled := false
router.PanicHandler = func(w http.ResponseWriter, r *http.Request, p interface{}) {
panicHandled = true
}
router.Handle(http.MethodPut, "/user/{name}", func(w http.ResponseWriter, r *http.Request) {
panic("oops!")
})
r := httptest.NewRequest(http.MethodPut, "/user/gopher", nil)
w := httptest.NewRecorder()
defer func() {
if rcv := recover(); rcv != nil {
t.Fatal("handling panic failed")
}
}()
router.ServeHTTP(w, r)
if !panicHandled {
t.Fatal("simulating failed")
}
}
func testRouterLookupByMethod(t *testing.T, method string) {
reqMethod := method
if method == MethodWild {
reqMethod = randomHTTPMethod()
}
routed := false
wantHandle := func(w http.ResponseWriter, r *http.Request) {
routed = true
}
wantParams := map[string]string{"name": "gopher"}
r := httptest.NewRequest("GET", "/nope", nil)
router := New()
// try empty router first
handle, tsr := router.Lookup(reqMethod, "/nope", r)
if handle != nil {
t.Fatalf("Got handle for unregistered pattern: %v", handle)
}
if tsr {
t.Error("Got wrong TSR recommendation!")
}
// insert route and try again
router.Handle(method, "/user/{name}", wantHandle)
handle, _ = router.Lookup(reqMethod, "/user/gopher", r)
w := httptest.NewRecorder()
if handle == nil {
t.Fatal("Got no handle!")
} else {
handle(w, r)
if !routed {
t.Fatal("Routing failed!")
}
}
for expectedKey, expectedVal := range wantParams {
_ = expectedKey
_ = expectedVal
// if ctx.UserValue(expectedKey) != expectedVal {
// t.Errorf("The values %s = %s is not save in context", expectedKey, expectedVal)
// }
}
routed = false
// route without param
router.Handle(method, "/user", wantHandle)
handle, _ = router.Lookup(reqMethod, "/user", r)
if handle == nil {
t.Fatal("Got no handle!")
} else {
handle(w, r)
if !routed {
t.Fatal("Routing failed!")
}
}
for expectedKey, expectedVal := range wantParams {
_ = expectedKey
_ = expectedVal
// if ctx.UserValue(expectedKey) != expectedVal {
// t.Errorf("The values %s = %s is not save in context", expectedKey, expectedVal)
// }
}
handle, tsr = router.Lookup(reqMethod, "/user/gopher/", r)
if handle != nil {
t.Fatalf("Got handle for unregistered pattern: %v", handle)
}
if !tsr {
t.Error("Got no TSR recommendation!")
}
handle, tsr = router.Lookup(reqMethod, "/nope", r)
if handle != nil {
t.Fatalf("Got handle for unregistered pattern: %v", handle)
}
if tsr {
t.Error("Got wrong TSR recommendation!")
}
}
func TestRouterLookup(t *testing.T) {
for _, method := range httpMethods {
testRouterLookupByMethod(t, method)
}
}
func TestRouterMatchedRoutePath(t *testing.T) {
route1 := "/user/{name}"
routed1 := false
handle1 := func(w http.ResponseWriter, r *http.Request) {
route := UserValue(r, MatchedRoutePathParam)
if route != route1 {
t.Fatalf("Wrong matched route: want %s, got %s", route1, route)
}
routed1 = true
}
route2 := "/user/{name}/details"
routed2 := false
handle2 := func(w http.ResponseWriter, r *http.Request) {
route := UserValue(r, MatchedRoutePathParam)
if route != route2 {
t.Fatalf("Wrong matched route: want %s, got %s", route2, route)
}
routed2 = true
}
route3 := "/"
routed3 := false
handle3 := func(w http.ResponseWriter, r *http.Request) {
route := UserValue(r, MatchedRoutePathParam)
if route != route3 {
t.Fatalf("Wrong matched route: want %s, got %s", route3, route)
}
routed3 = true
}
router := New()
router.SaveMatchedRoutePath = true
router.Handle(http.MethodGet, route1, handle1)
router.Handle(http.MethodGet, route2, handle2)
router.Handle(http.MethodGet, route3, handle3)
r := httptest.NewRequest(http.MethodGet, "/user/gopher", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if !routed1 || routed2 || routed3 {
t.Fatal("Routing failed!")
}
r = httptest.NewRequest(http.MethodGet, "/user/gopher/details", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if !routed2 || routed3 {
t.Fatal("Routing failed!")
}
r = httptest.NewRequest(http.MethodGet, "/", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if !routed3 {
t.Fatal("Routing failed!")
}
}
func TestRouterServeFiles(t *testing.T) {
router := New()
body := []byte("fake ico")
ioutil.WriteFile(os.TempDir()+"/favicon.ico", body, 0644)
router.ServeFiles("/{filepath:*}", os.TempDir())
r := httptest.NewRequest("GET", "/favicon.ico", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("Unexpected status code %d. Expected %d", w.Code, 200)
}
if !bytes.Equal(w.Body.Bytes(), body) {
t.Fatalf("Unexpected body %q. Expected %q", w.Body.Bytes(), string(body))
}
r = httptest.NewRequest("GET", "/notfound", nil)
w = httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != 404 {
t.Fatalf("Unexpected status code %d. Expected %d", w.Code, 404)
}
}
func TestRouterList(t *testing.T) {
expected := map[string][]string{
"GET": {"/bar"},
"PATCH": {"/foo"},
"POST": {"/v1/users/{name}/{surname?}"},
"DELETE": {"/v1/users/{id?}"},
}
r := New()
r.GET("/bar", func(w http.ResponseWriter, r *http.Request) {})
r.PATCH("/foo", func(w http.ResponseWriter, r *http.Request) {})
v1 := r.Group("/v1")
v1.POST("/users/{name}/{surname?}", func(w http.ResponseWriter, r *http.Request) {})
v1.DELETE("/users/{id?}", func(w http.ResponseWriter, r *http.Request) {})
result := r.List()
if !reflect.DeepEqual(result, expected) {
t.Errorf("Router.List() == %v, want %v", result, expected)
}
}
func TestRouterSamePrefixParamRoute(t *testing.T) {
var id1, id2, id3, pageSize, page, iid string
var routed1, routed2, routed3 bool
router := New()
v1 := router.Group("/v1")
v1.GET("/foo/{id}/{pageSize}/{page}", func(w http.ResponseWriter, r *http.Request) {
id1 = UserValue(r, "id")
pageSize = UserValue(r, "pageSize")
page = UserValue(r, "page")
routed1 = true
})
v1.GET("/foo/{id}/{iid}", func(w http.ResponseWriter, r *http.Request) {
id2 = UserValue(r, "id")
iid = UserValue(r, "iid")
routed2 = true
})
v1.GET("/foo/{id}", func(w http.ResponseWriter, r *http.Request) {
id3 = UserValue(r, "id")
routed3 = true
})
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/v1/foo/1/20/4", nil))
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/v1/foo/2/3", nil))
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/v1/foo/v3", nil))
if !routed1 {
t.Error("/foo/{id}/{pageSize}/{page} not routed.")
}
if !routed2 {
t.Error("/foo/{id}/{iid} not routed")
}