Repository navigation
Expand file tree
/
Copy pathdomain_test.go
More file actions
2249 lines (1928 loc) · 87.4 KB
/
Copy pathdomain_test.go
File metadata and controls
2249 lines (1928 loc) · 87.4 KB
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
// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 GitHub Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
package fiber
import (
"errors"
"net/http"
"strings"
"sync"
"testing"
"time"
"github.com/gofiber/fiber/v3/internal/apptest"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp"
)
// domainTestExpect sends a GET request for path with the given Host through app
// and fails the test unless the response has the given status. The response is
// returned for assertions on its headers.
func domainTestExpect(t *testing.T, app *App, host, path string, status int) *http.Response {
t.Helper()
return routerDomainExpectMethod(t, app, MethodGet, host, path, status)
}
// routerDomainExpectMethod is domainTestExpect for a request of the given method.
func routerDomainExpectMethod(t *testing.T, app *App, method, host, path string, status int) *http.Response {
t.Helper()
return apptest.Expect(t, app, apptest.Req(method, path, apptest.WithHost(host)), status)
}
// domainTestExpectBody is domainTestExpect that also checks the response body.
func domainTestExpectBody(t *testing.T, app *App, host, path string, status int, body string) {
t.Helper()
apptest.ExpectBody(t, app, apptest.Req(MethodGet, path, apptest.WithHost(host)), status, body)
}
// domainTestApp returns a new app, configured with cfg, whose only route
// answers GET path with body.
func domainTestApp(path, body string, cfg ...Config) *App {
app := New(cfg...)
app.Get(path, func(c Ctx) error { return c.SendString(body) })
return app
}
// domainTestRenderApp returns a new app, configured with cfg, whose only route
// answers GET path by rendering the template tmpl with data.
func domainTestRenderApp(path, tmpl string, data Map, cfg ...Config) *App {
app := New(cfg...)
app.Get(path, func(c Ctx) error { return c.Render(tmpl, data) })
return app
}
// domainTestBoom is a handler that always fails, to reach the error handler of
// the app it is registered on.
func domainTestBoom(_ Ctx) error {
return errors.New("boom")
}
// domainTestErrorHandler returns an error handler that answers every error with
// the given status and body, so a test can tell whose handler ran.
func domainTestErrorHandler(status int, body string) ErrorHandler {
return func(c Ctx, _ error) error { return c.Status(status).SendString(body) }
}
// domainTestTag returns a handler that names itself in the X-Handler header and answers 200 with no body, so a
// test can tell which handler ran.
func domainTestTag(name string) Handler {
return func(c Ctx) error {
c.Set("X-Handler", name)
return nil
}
}
// domainTestFailingApp returns a new app whose only route, GET path, fails and
// whose error handler answers with the given status and body.
func domainTestFailingApp(status int, body, path string) *App {
app := New(Config{ErrorHandler: domainTestErrorHandler(status, body)})
app.Get(path, domainTestBoom)
return app
}
// routerDomainMount returns a new app, configured with cfg, that serves sub under /api on api.example.com.
func routerDomainMount(sub *App, cfg ...Config) *App {
app := New(cfg...)
app.Domain("api.example.com").Use("/api", sub)
return app
}
// routerDomainWith returns a new app that has sub mounted under prefix.
func routerDomainWith(prefix string, sub *App) *App {
app := New()
app.Use(prefix, sub)
return app
}
// domainTestEngine returns a loaded template engine for the templates in
// .github/<dir>, or for the default set when dir is empty.
func domainTestEngine(t *testing.T, dir string) *testTemplateEngine {
t.Helper()
engine := &testTemplateEngine{path: dir}
require.NoError(t, engine.Load())
return engine
}
// Test_Domain_Routing registers routes through the domain router API on a new
// app per row and sends the row's requests, each with its Host.
func Test_Domain_Routing(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
register func(app *App)
name string
checks []routerReq
}{
{name: "basic", register: func(app *App) {
app.Domain("api.example.com").Get("/hello", func(c Ctx) error { return c.SendString("api hello") })
}, checks: []routerReq{
{host: "api.example.com", path: "/hello", status: StatusOK, body: "api hello"},
{host: "www.example.com", path: "/hello", status: StatusNotFound},
}},
{name: "multiple domains", register: func(app *App) {
app.Domain("api.example.com").Get("/", func(c Ctx) error { return c.SendString("api") })
app.Domain("www.example.com").Get("/", func(c Ctx) error { return c.SendString("www") })
}, checks: []routerReq{
{host: "api.example.com", path: "/", status: StatusOK, body: "api"},
{host: "www.example.com", path: "/", status: StatusOK, body: "www"},
{host: "other.example.com", path: "/", status: StatusNotFound},
}},
{name: "group of a domain", register: func(app *App) {
app.Domain("api.example.com").Group("/api").Get("/users", func(c Ctx) error {
return c.SendString("users list")
})
}, checks: []routerReq{
{host: "api.example.com", path: "/api/users", status: StatusOK, body: "users list"},
{host: "www.example.com", path: "/api/users", status: StatusNotFound},
}},
{name: "domain of a group", register: func(app *App) {
app.Group("/api").Domain("api.example.com").Get("/users", func(c Ctx) error {
return c.SendString("users from group domain")
})
}, checks: []routerReq{
{host: "api.example.com", path: "/api/users", status: StatusOK, body: "users from group domain"},
{host: "www.example.com", path: "/api/users", status: StatusNotFound},
}},
{name: "domain of a domain", register: func(app *App) {
// replaces the pattern of the domain router it is created from
other := app.Domain("api.example.com").Domain("www.example.com")
other.Get("/", func(c Ctx) error { return c.SendString("www") })
}, checks: []routerReq{{host: "www.example.com", path: "/", status: StatusOK, body: "www"}}},
{name: "nested groups", register: func(app *App) {
users := app.Domain("api.example.com").Group("/v1").Group("/users")
users.Get("/", func(c Ctx) error { return c.SendString("v1 users") })
}, checks: []routerReq{{host: "api.example.com", path: "/v1/users/", status: StatusOK, body: "v1 users"}}},
{name: "path params", register: func(app *App) {
app.Domain(":tenant.example.com").Get("/users/:id", func(c Ctx) error {
return c.SendString(DomainParam(c, "tenant") + ":" + c.Params("id"))
})
}, checks: []routerReq{{host: "acme.example.com", path: "/users/42", status: StatusOK, body: "acme:42"}}},
{name: "stale domain params cleared", register: func(app *App) {
app.Domain(":tenant.example.com").Use(func(c Ctx) error {
c.Set("X-Tenant", DomainParam(c, "tenant"))
return c.Next()
})
// a static domain (no params) must clear the params the parametric one set
app.Domain("static.example.com").Get("/check", func(c Ctx) error {
return c.SendString("tenant=" + DomainParam(c, "tenant"))
})
}, checks: []routerReq{{host: "static.example.com", path: "/check", status: StatusOK, body: "tenant="}}},
{name: "fallback to a route without domain", register: func(app *App) {
// the domain route is registered first
app.Domain("api.example.com").Get("/", func(c Ctx) error { return c.SendString("api") })
app.Get("/", func(c Ctx) error { return c.SendString("fallback") })
}, checks: []routerReq{
{host: "api.example.com", path: "/", status: StatusOK, body: "api"},
{host: "www.example.com", path: "/", status: StatusOK, body: "fallback"},
}},
{name: "HEAD route", register: func(app *App) {
app.Domain("api.example.com").Head("/test", func(c Ctx) error {
c.Set("X-Custom", "head")
return c.SendStatus(StatusOK)
})
}, checks: []routerReq{{method: MethodHead, host: "api.example.com", path: "/test", status: StatusOK}}},
// A HEAD route on another Domain pattern, or in a mounted app, runs behind the automatic route of an earlier
// GET.
{name: "Domain HEAD after GET", register: func(app *App) {
app.Get("/x", domainTestTag("get"))
app.Domain("admin.example.com").Head("/x", domainTestTag("domain head"))
}, checks: []routerReq{
{method: MethodHead, host: "admin.example.com", path: "/x", header: "X-Handler", value: "get"},
{method: MethodHead, host: "other.example.com", path: "/x", header: "X-Handler", value: "get"},
}},
{name: "HEAD after Domain GET", register: func(app *App) {
app.Domain("admin.example.com").Get("/x", domainTestTag("domain get"))
app.Head("/x", domainTestTag("head"))
}, checks: []routerReq{
{method: MethodHead, host: "admin.example.com", path: "/x", header: "X-Handler", value: "domain get"},
{method: MethodHead, host: "other.example.com", path: "/x", header: "X-Handler", value: "head"},
}},
{name: "mounted HEAD after GET", register: func(app *App) {
app.Get("/x", domainTestTag("get"))
sub := New()
sub.Head("/x", domainTestTag("sub head"))
app.Use("/", sub)
}, checks: []routerReq{
{method: MethodHead, host: "admin.example.com", path: "/x", header: "X-Handler", value: "get"},
}},
{name: "Domain-mounted HEAD after GET", register: func(app *App) {
app.Get("/x", domainTestTag("get"))
sub := New()
sub.Head("/x", domainTestTag("sub head"))
app.Domain("admin.example.com").Use("/", sub)
}, checks: []routerReq{
{method: MethodHead, host: "admin.example.com", path: "/x", header: "X-Handler", value: "get"},
{method: MethodHead, host: "other.example.com", path: "/x", header: "X-Handler", value: "get"},
}},
{name: "All", register: func(app *App) {
app.Domain("api.example.com").All("/test", func(c Ctx) error { return c.SendString("all methods") })
}, checks: []routerReq{
{host: "api.example.com", path: "/test", status: StatusOK},
{method: MethodPost, host: "api.example.com", path: "/test", status: StatusOK},
{method: MethodPut, host: "api.example.com", path: "/test", status: StatusOK},
{method: MethodDelete, host: "api.example.com", path: "/test", status: StatusOK},
}},
{name: "Add", register: func(app *App) {
app.Domain("api.example.com").Add([]string{MethodGet, MethodPost}, "/test", func(c Ctx) error {
return c.SendString("ok")
})
}, checks: []routerReq{
{host: "api.example.com", path: "/test", status: StatusOK},
{method: MethodPost, host: "api.example.com", path: "/test", status: StatusOK},
}},
{name: "chained registration", register: func(app *App) {
// the methods return the domain router for chaining
app.Domain("api.example.com").Get("/a", func(c Ctx) error { return c.SendString("a") }).
Post("/b", func(c Ctx) error { return c.SendString("b") })
}, checks: []routerReq{
{host: "api.example.com", path: "/a", status: StatusOK},
{method: MethodPost, host: "api.example.com", path: "/b", status: StatusOK},
}},
{name: "Route", register: func(app *App) {
app.Domain("api.example.com").Route("/api", func(router Router) {
router.Get("/users", func(c Ctx) error { return c.SendString("users") })
router.Get("/posts", func(c Ctx) error { return c.SendString("posts") })
})
}, checks: []routerReq{
{host: "api.example.com", path: "/api/users", status: StatusOK, body: "users"},
{host: "api.example.com", path: "/api/posts", status: StatusOK, body: "posts"},
{host: "www.example.com", path: "/api/users", status: StatusNotFound},
}},
{name: "RouteChain", register: func(app *App) {
app.Domain("api.example.com").RouteChain("/api/users").
Get(func(c Ctx) error { return c.SendString("get users") }).
Post(func(c Ctx) error { return c.SendString("create user") })
}, checks: []routerReq{
{host: "api.example.com", path: "/api/users", status: StatusOK, body: "get users"},
{method: MethodPost, host: "api.example.com", path: "/api/users", status: StatusOK, body: "create user"},
{host: "www.example.com", path: "/api/users", status: StatusNotFound},
}},
{name: "nested RouteChain", register: func(app *App) {
app.Domain("api.example.com").RouteChain("/api").RouteChain("/v1").
Get(func(c Ctx) error { return c.SendString("v1") })
}, checks: []routerReq{{host: "api.example.com", path: "/api/v1", status: StatusOK, body: "v1"}}},
{name: "mounted sub-app", register: func(app *App) {
subApp := New()
subApp.Get("/users", func(c Ctx) error { return c.SendString("users list") })
subApp.Get("/posts", func(c Ctx) error { return c.SendString("posts list") })
app.Domain("api.example.com").Use("/api", subApp)
}, checks: []routerReq{
{host: "api.example.com", path: "/api/users", status: StatusOK, body: "users list"},
{host: "api.example.com", path: "/api/posts", status: StatusOK, body: "posts list"},
{host: "www.example.com", path: "/api/users", status: StatusNotFound},
}},
{name: "sub-app mounted at the root", register: func(app *App) {
app.Domain("api.example.com").Use(domainTestApp("/users", "users list"))
}, checks: []routerReq{
{host: "api.example.com", path: "/users", status: StatusOK, body: "users list"},
{host: "www.example.com", path: "/users", status: StatusNotFound},
}},
{name: "sub-app mounted through a group", register: func(app *App) {
app.Group("/api").Domain("api.example.com").Use("/v1", domainTestApp("/data", "data response"))
}, checks: []routerReq{
// the group prefix, then the mount prefix
{host: "api.example.com", path: "/api/v1/data", status: StatusOK, body: "data response"},
{host: "www.example.com", path: "/api/v1/data", status: StatusNotFound},
}},
{name: "middleware", register: func(app *App) {
domain := app.Domain("api.example.com")
domain.Use(func(c Ctx) error {
c.Set("X-Domain", "api")
return c.Next()
})
domain.Get("/", func(c Ctx) error { return c.SendString("ok") })
}, checks: []routerReq{
{host: "api.example.com", path: "/", status: StatusOK, header: "X-Domain", value: "api"},
{host: "www.example.com", path: "/", status: StatusNotFound, header: "X-Domain"},
}},
{name: "middleware under a prefix", register: func(app *App) {
domain := app.Domain("api.example.com")
domain.Use("/api", func(c Ctx) error {
c.Set("X-API", "true")
return c.Next()
})
domain.Get("/api/data", func(c Ctx) error { return c.SendString("data") })
}, checks: []routerReq{
{host: "api.example.com", path: "/api/data", status: StatusOK, header: "X-API", value: "true"},
}},
{name: "middleware under several prefixes", register: func(app *App) {
domain := app.Domain("api.example.com")
domain.Use([]string{"/a", "/b"}, func(c Ctx) error {
c.Set("X-Domain-MW", "true")
return c.Next()
})
domain.Get("/a/test", func(c Ctx) error { return c.SendString("a") })
domain.Get("/b/test", func(c Ctx) error { return c.SendString("b") })
}, checks: []routerReq{
{host: "api.example.com", path: "/a/test", status: StatusOK, header: "X-Domain-MW", value: "true"},
{host: "api.example.com", path: "/b/test", status: StatusOK, header: "X-Domain-MW", value: "true"},
}},
{name: "group middleware", register: func(app *App) {
api := app.Domain("api.example.com").Group("/api", func(c Ctx) error {
c.Set("X-Group-MW", "yes")
return c.Next()
})
api.Get("/data", func(c Ctx) error { return c.SendString("data") })
}, checks: []routerReq{
{host: "api.example.com", path: "/api/data", status: StatusOK, header: "X-Group-MW", value: "yes"},
{host: "www.example.com", path: "/api/data", status: StatusNotFound, header: "X-Group-MW"},
}},
{name: "several handlers", register: func(app *App) {
app.Domain("api.example.com").Get("/test", func(c Ctx) error {
c.Set("X-First", "true")
return c.Next()
}, func(c Ctx) error { return c.SendString("final") })
}, checks: []routerReq{
{host: "api.example.com", path: "/test", status: StatusOK, body: "final", header: "X-First", value: "true"},
{host: "www.example.com", path: "/test", status: StatusNotFound, header: "X-First"},
}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
tc.register(app)
routerTestExpectAll(t, app, tc.checks...)
})
}
}
// Test_Domain_Params registers one domain route per row, answering with what
// DomainParam reads from the request's Host, and requests it with that host.
func Test_Domain_Params(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
reply func(c Ctx) string
name string
pattern string
host string
want string
}{
{
name: "single parameter", pattern: ":user.blog.example.com", host: "john.blog.example.com", want: "blog of john",
reply: func(c Ctx) string { return "blog of " + DomainParam(c, "user") },
},
{
name: "multiple parameters", pattern: ":sub.:region.example.com", host: "api.us-east.example.com", want: "api-us-east",
reply: func(c Ctx) string { return DomainParam(c, "sub") + "-" + DomainParam(c, "region") },
},
{
// Use mixed-case param name ":User" — DomainParam should find it by exact name
name: "parameter name case preserved", pattern: ":User.example.com", host: "alice.example.com", want: "alice",
reply: func(c Ctx) string { return DomainParam(c, "User") },
},
{
// No domain params set, should return default
name: "default value", pattern: "example.com", host: "example.com", want: "default",
reply: func(c Ctx) string { return DomainParam(c, "user", "default") },
},
{
name: "no default", pattern: "example.com", host: "example.com", want: "user=",
reply: func(c Ctx) string { return "user=" + DomainParam(c, "user") },
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
app.Domain(tc.pattern).Get("/", func(c Ctx) error { return c.SendString(tc.reply(c)) })
domainTestExpectBody(t, app, tc.host, "/", StatusOK, tc.want)
})
}
}
// Test_Domain_HostMatching registers one domain route answering "ok" per row and
// sends a request with the row's Host: the route must answer when matched is
// set and must not be reached (404) otherwise.
func Test_Domain_HostMatching(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
pattern string
host string
matched bool
}{
{name: "case-insensitive pattern", pattern: "API.Example.COM", host: "api.example.com", matched: true},
// Fully-qualified domain name with trailing dot should match
{name: "trailing dot", pattern: "api.example.com", host: "api.example.com.", matched: true},
// Host with port - Hostname() strips the port
{name: "host with port", pattern: "api.example.com", host: "api.example.com:8080", matched: true},
// Different number of domain parts
{name: "fewer parts", pattern: "api.example.com", host: "example.com"},
{name: "more parts", pattern: "api.example.com", host: "sub.api.example.com"},
// Empty host should not match
{name: "empty host", pattern: "api.example.com", host: ""},
// Hostname with too many labels should not match (DoS protection)
{name: "too many labels", pattern: "example.com", host: strings.Repeat("sub.", 19) + "sub"},
// Hostname exceeding 253 characters should not match (DoS protection)
{name: "hostname longer than 253 characters", pattern: "example.com", host: strings.Repeat("a", 254) + ".com"},
// Label exceeding 63 characters should not match (DoS protection)
{name: "label longer than 63 characters", pattern: "example.com", host: strings.Repeat("a", 64) + ".example.com"},
{name: "empty hostname label", pattern: "example.com", host: "example..com"},
// Non-ASCII hostnames are rejected at runtime (DNS names are ASCII-only)
{name: "non-ASCII hostname", pattern: ":sub.example.com", host: "ünïcödé.example.com"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
app.Domain(tc.pattern).Get("/", func(c Ctx) error { return c.SendString("ok") })
if tc.matched {
domainTestExpectBody(t, app, tc.host, "/", StatusOK, "ok")
} else {
domainTestExpect(t, app, tc.host, "/", StatusNotFound)
}
})
}
}
func Test_Domain_HTTPMethods(t *testing.T) {
t.Parallel()
methods := []struct {
reg func(Router, string, any, ...any) Router
method string
}{
{method: MethodGet, reg: func(r Router, p string, h any, hs ...any) Router { return r.Get(p, h, hs...) }},
{method: MethodPost, reg: func(r Router, p string, h any, hs ...any) Router { return r.Post(p, h, hs...) }},
{method: MethodPut, reg: func(r Router, p string, h any, hs ...any) Router { return r.Put(p, h, hs...) }},
{method: MethodDelete, reg: func(r Router, p string, h any, hs ...any) Router { return r.Delete(p, h, hs...) }},
{method: MethodPatch, reg: func(r Router, p string, h any, hs ...any) Router { return r.Patch(p, h, hs...) }},
{method: MethodQuery, reg: func(r Router, p string, h any, hs ...any) Router { return r.Query(p, h, hs...) }},
{method: MethodOptions, reg: func(r Router, p string, h any, hs ...any) Router { return r.Options(p, h, hs...) }},
{method: MethodConnect, reg: func(r Router, p string, h any, hs ...any) Router { return r.Connect(p, h, hs...) }},
{method: MethodTrace, reg: func(r Router, p string, h any, hs ...any) Router { return r.Trace(p, h, hs...) }},
}
for _, m := range methods {
t.Run(m.method, func(t *testing.T) {
t.Parallel()
app := New()
domain := app.Domain("api.example.com")
m.reg(domain, "/test", func(c Ctx) error { return c.SendString(m.method) })
routerDomainExpectMethod(t, app, m.method, "api.example.com", "/test", StatusOK)
})
}
}
// One path on two patterns is two routes: merged into one, both hostnames would
// run under the name given last, and c.Route() could not tell them apart.
func Test_Domain_SamePathKeepsItsOwnRoute(t *testing.T) {
t.Parallel()
app := New()
served := func(c Ctx) error { return c.SendString(c.Route().Name) }
app.Domain("admin.example.com").Get("/test", served).Name("admin")
app.Domain("www.example.com").Get("/test", served).Name("www")
app.Get("/test", served).Name("any")
// One pattern twice is still one route
app.Domain("api.example.com").Get("/merged", func(c Ctx) error { return c.Next() })
app.Domain("API.example.com.").Get("/merged", served).Name("api")
domainTestExpectBody(t, app, "admin.example.com", "/test", StatusOK, "admin")
domainTestExpectBody(t, app, "www.example.com", "/test", StatusOK, "www")
domainTestExpectBody(t, app, "other.example.com", "/test", StatusOK, "any")
var merged []Route
for _, route := range app.GetRoutes(true) {
if route.Method == MethodGet && route.Path == "/merged" {
merged = append(merged, route)
}
}
require.Len(t, merged, 1)
require.Len(t, merged[0].Handlers, 2)
}
// The automatic HEAD route of one pattern declines every other hostname, so it
// cannot stand in for the GET route another pattern has on the same path.
func Test_Domain_AutoHeadPerPattern(t *testing.T) {
t.Parallel()
app := New()
served := func(c Ctx) error {
c.Set("X-Served", c.Route().Name)
return c.SendStatus(StatusOK)
}
app.Domain("admin.example.com").Get("/test", served).Name("admin")
app.Domain("www.example.com").Get("/test", served).Name("www")
app.Domain("api.example.com").Head("/test", served).Name("api.head")
app.Get("/test", served).Name("any")
head := func(host string) string {
return routerDomainExpectMethod(t, app, MethodHead, host, "/test", StatusOK).Header.Get("X-Served")
}
require.Equal(t, "admin", head("admin.example.com"))
require.Equal(t, "www", head("www.example.com"))
require.Equal(t, "api.head", head("api.example.com"), "renamed by another host's GET route")
require.Equal(t, "any", head("other.example.com"))
// Removing one pattern's GET route takes its own companion along, not another's
app.RemoveRouteByName("admin", MethodGet)
app.RebuildTree()
require.Equal(t, "any", head("admin.example.com"))
require.Equal(t, "www", head("www.example.com"))
}
func Test_Domain_Name(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
register func(app *App)
name string
want string
}{
{name: "route", want: "api-test", register: func(app *App) {
app.Domain("api.example.com").Get("/test", func(c Ctx) error { return c.SendString("ok") }).Name("api-test")
}},
// When Domain is used with Route(prefix, fn, name), the group Name()
// should apply properly via delegation to the underlying group.
{name: "group", want: "v1.items-list", register: func(app *App) {
app.Domain("api.example.com").Route("/v1", func(r Router) {
r.Get("/items", func(c Ctx) error { return c.SendString("items") }).Name("items-list")
}, "v1.")
}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
tc.register(app)
var found bool
for _, routes := range app.Stack() {
for _, route := range routes {
found = found || route.Name == tc.want
}
}
require.True(t, found, "route should be named %q", tc.want)
})
}
}
func Test_Domain_RoutePanic(t *testing.T) {
t.Parallel()
app := New()
require.Panics(t, func() { app.Domain("api.example.com").Route("/test", nil) })
}
func Test_Domain_RouteChainAllMethods(t *testing.T) {
t.Parallel()
app := New()
rc := app.Domain("api.example.com").RouteChain("/test")
rc.All(func(c Ctx) error {
c.Set("X-All", "yes")
return c.Next()
})
rc.Head(func(c Ctx) error { return c.SendStatus(StatusOK) })
rc.Put(func(c Ctx) error { return c.SendString("put") })
rc.Delete(func(c Ctx) error { return c.SendString("delete") })
rc.Connect(func(c Ctx) error { return c.SendString("connect") })
rc.Options(func(c Ctx) error { return c.SendString("options") })
rc.Trace(func(c Ctx) error { return c.SendString("trace") })
rc.Patch(func(c Ctx) error { return c.SendString("patch") })
rc.Query(func(c Ctx) error { return c.SendString("query") })
for _, method := range []string{MethodPut, MethodDelete, MethodPatch, MethodOptions, MethodQuery} {
routerDomainExpectMethod(t, app, method, "api.example.com", "/test", StatusOK)
}
}
func Test_parseDomainPattern(t *testing.T) {
t.Parallel()
tests := []struct {
name string
pattern string
paramNames []string
numParts int
}{
{name: "simple", pattern: "example.com", numParts: 2},
{name: "with subdomain", pattern: "api.example.com", numParts: 3},
{name: "single param", pattern: ":sub.example.com", numParts: 3, paramNames: []string{"sub"}},
{name: "multiple params", pattern: ":sub.:region.example.com", numParts: 4, paramNames: []string{"sub", "region"}},
{name: "case insensitive", pattern: "API.Example.COM", numParts: 3},
{name: "single part", pattern: "localhost", numParts: 1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
m := parseDomainPattern(tt.pattern)
require.Equal(t, tt.numParts, m.numParts)
if tt.paramNames == nil {
require.Empty(t, m.paramNames)
} else {
require.Equal(t, tt.paramNames, m.paramNames)
}
})
}
}
func Test_domainMatcher_match(t *testing.T) {
t.Parallel()
tests := []struct {
name string
pattern string
hostname string
values []string
matched bool
}{
{name: "exact match", pattern: "api.example.com", hostname: "api.example.com", matched: true},
{name: "case mismatch", pattern: "api.example.com", hostname: "API.EXAMPLE.COM", matched: true},
{name: "wrong subdomain", pattern: "api.example.com", hostname: "www.example.com"},
{name: "wrong part count", pattern: "api.example.com", hostname: "example.com"},
{name: "with param", pattern: ":sub.example.com", hostname: "api.example.com", matched: true, values: []string{"api"}},
{name: "multi param", pattern: ":a.:b.com", hostname: "x.y.com", matched: true, values: []string{"x", "y"}},
{name: "param no match const", pattern: ":a.example.com", hostname: "x.other.com"},
{name: "empty hostname", pattern: "example.com", hostname: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
m := parseDomainPattern(tt.pattern)
matched, values := m.match(tt.hostname)
require.Equal(t, tt.matched, matched)
if tt.values == nil {
if matched && len(m.paramIdx) == 0 {
require.Empty(t, values)
}
} else {
require.Equal(t, tt.values, values)
}
})
}
}
// Test_Domain_HandlerTypes verifies that the domain router is compatible with
// all handler types defined in adapter.go.
func Test_Domain_HandlerTypes(t *testing.T) {
t.Parallel()
// Handlers that are the only one of their route.
for _, tc := range []struct {
handler any
name string
header string // response header the handler sets, if it does
value string // the value that header must have
body string // response body the handler writes, if it is checked
}{
{name: "fiber handler", body: "fiber", handler: func(c Ctx) error { return c.SendString("fiber") }},
{name: "fiber handler no error", header: "X-Handler", value: "no-error", handler: func(c Ctx) {
c.Set("X-Handler", "no-error")
}},
{name: "express req res error", body: "express-err", handler: func(_ Req, res Res) error {
return res.SendString("express-err")
}},
{name: "express req res no error", header: "X-Express", value: "ok", handler: func(_ Req, res Res) {
res.Set("X-Express", "ok")
}},
{name: "net/http HandlerFunc", handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})},
{name: "net/http HandlerFunc writing a body", body: "net/http handler", handler: http.HandlerFunc(
func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("net/http handler"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})},
{name: "net/http func handler", handler: func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}},
{name: "fasthttp RequestHandler", handler: fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(fasthttp.StatusOK)
ctx.SetBodyString("fasthttp")
})},
{name: "fasthttp handler with error", handler: func(ctx *fasthttp.RequestCtx) error {
ctx.SetStatusCode(fasthttp.StatusOK)
ctx.SetBodyString("fasthttp-err")
return nil
}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
app.Domain("api.example.com").Get("/test", tc.handler)
resp := domainTestExpect(t, app, "api.example.com", "/test", StatusOK)
if tc.header != "" {
require.Equal(t, tc.value, resp.Header.Get(tc.header))
}
if tc.body != "" {
require.Equal(t, tc.body, apptest.Body(t, resp))
}
})
}
// Express-style middleware in front of a final fiber handler: it sets X-MW
// and hands over, so the final handler must have run too.
for _, tc := range []struct {
middleware any
name string
}{
{name: "express next-err returns-err", middleware: func(_ Req, res Res, next func() error) error {
res.Set("X-MW", "yes")
return next()
}},
{name: "express with next error", middleware: func(_ Req, res Res, next func() error) {
res.Set("X-MW", "yes")
_ = next() //nolint:errcheck // test
}},
{name: "express with noarg next error", middleware: func(_ Req, res Res, next func()) error {
res.Set("X-MW", "yes")
next()
return nil
}},
{name: "express with noarg next", middleware: func(_ Req, res Res, next func()) {
res.Set("X-MW", "yes")
next()
}},
{name: "express with error next", middleware: func(_ Req, res Res, next func(error)) {
res.Set("X-MW", "yes")
next(nil)
}},
{name: "express with error next error", middleware: func(_ Req, res Res, next func(error)) error {
res.Set("X-MW", "yes")
next(nil)
return nil
}},
{name: "express errnext-err returns-err", middleware: func(_ Req, res Res, next func(error) error) {
res.Set("X-MW", "yes")
_ = next(nil) //nolint:errcheck // test
}},
{name: "express errnext-err returns-err err", middleware: func(_ Req, res Res, next func(error) error) error {
res.Set("X-MW", "yes")
return next(nil)
}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
app.Domain("api.example.com").Get(
"/test",
tc.middleware,
func(c Ctx) error { return c.SendString("chained") },
)
resp := domainTestExpect(t, app, "api.example.com", "/test", StatusOK)
require.Equal(t, "yes", resp.Header.Get("X-MW"))
require.Equal(t, "chained", apptest.Body(t, resp))
})
}
t.Run("non-matching domain skips all handler types", func(t *testing.T) {
t.Parallel()
app := New()
app.Domain("api.example.com").Get(
"/test",
func(c Ctx) error {
c.Set("X-Handler", "ran")
return c.SendString("should-not-run")
},
)
resp := domainTestExpect(t, app, "wrong.example.com", "/test", StatusNotFound)
require.Empty(t, resp.Header.Get("X-Handler"))
})
}
func Test_Domain_UseHandlerTypes(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
middleware any
name string
want string
}{
{name: "fiber handler middleware", want: "fiber", middleware: func(c Ctx) error {
c.Set("X-MW", "fiber")
return c.Next()
}},
{name: "express middleware", want: "express", middleware: func(_ Req, res Res, next func() error) error {
res.Set("X-MW", "express")
return next()
}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
domain := app.Domain("api.example.com")
domain.Use(tc.middleware)
domain.Get("/test", func(c Ctx) error { return c.SendString("ok") })
resp := domainTestExpect(t, app, "api.example.com", "/test", StatusOK)
require.Equal(t, tc.want, resp.Header.Get("X-MW"))
})
}
}
func Benchmark_Domain_Match(b *testing.B) {
m := parseDomainPattern(":tenant.api.example.com")
b.ResetTimer()
b.ReportAllocs()
for b.Loop() {
m.match("acme.api.example.com")
}
}
func Benchmark_Domain_Route(b *testing.B) {
app := New()
app.Domain("api.example.com").Get("/test", func(c Ctx) error { return c.SendString("ok") })
req := apptest.Req(MethodGet, "/test", apptest.WithHost("api.example.com"))
b.ResetTimer()
b.ReportAllocs()
for b.Loop() {
resp, err := app.Test(req)
if err != nil {
b.Fatal(err)
}
resp.Body.Close() //nolint:errcheck // benchmark
}
}
func Benchmark_Domain_NoImpact(b *testing.B) {
// Benchmark regular routes to ensure domain feature has zero impact
app := New()
app.Get("/test", func(c Ctx) error { return c.SendString("ok") })
req := apptest.Req(MethodGet, "/test")
b.ResetTimer()
b.ReportAllocs()
for b.Loop() {
resp, err := app.Test(req)
if err != nil {
b.Fatal(err)
}
resp.Body.Close() //nolint:errcheck // benchmark
}
}
// Test_Domain_Security_Patterns checks which domain patterns are rejected when
// the domain router is created, and that valid parameter names are accepted.
func Test_Domain_Security_Patterns(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name string
pattern string
valid bool
}{
{name: "empty", pattern: ""},
{name: "blank", pattern: " "},
{name: "empty label in the middle", pattern: "example..com"},
{name: "empty leading label", pattern: ".example.com"},
{name: "empty parameter name", pattern: ":.example.com"},
{name: "parameter name with at sign", pattern: ":user@host.example.com"},
{name: "parameter name with dollar sign", pattern: ":user$.example.com"},
{name: "parameter name with space", pattern: ":user name.example.com"},
{name: "label with dollar sign", pattern: "example$.com"},
{name: "label with at sign", pattern: "example@domain.com"},
{name: "label with space", pattern: &quo
9F48
t;example domain.com"},
// DoS protection against excessive domain labels
{name: "too many parts", pattern: strings.Repeat("sub.", 19) + "sub"},
// Non-ASCII characters are rejected in both domain labels and parameter
// names (DNS names are ASCII-only).
{name: "non-ASCII label", pattern: "ünïcödé.example.com"},
{name: "non-ASCII parameter name", pattern: ":üser.example.com"},
{name: "alphanumeric parameter name", pattern: ":user123.example.com", valid: true},
{name: "parameter name with underscore", pattern: ":user_name.example.com", valid: true},
{name: "parameter name with hyphen", pattern: ":user-name.example.com", valid: true},
{name: "mixed parameter name", pattern: ":user_123-name.example.com", valid: true},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if tc.valid {
require.NotPanics(t, func() { parseDomainPattern(tc.pattern) })
return
}
require.Panics(t, func() { parseDomainPattern(tc.pattern) })
})
}
}
func Test_Domain_Security_InvalidHostnameChars(t *testing.T) {
t.Parallel()
// Note: Some invalid chars (like spaces) are rejected by httptest.NewRequest itself
for _, tc := range []struct {
name string
host string
}{
{name: "dollar sign", host: "example$.com"},
{name: "at sign", host: "example@domain.com"},
{name: "NUL", host: "example\x00.com"},
{name: "newline", host: "example\n.com"},
{name: "semicolon", host: "example;.com"},
{name: "slash", host: "example/.com"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New()
app.Domain("example.com").Get("/", func(c Ctx) error { return c.SendString("ok") })
resp, err := app.Test(apptest.Req(MethodGet, "/", apptest.WithHost(tc.host)))
if err == nil {
require.Equal(t, StatusNotFound, resp.StatusCode, "Should reject hostname: %s", tc.host)
}
// If there's an error, the validation happened at an earlier layer which is also acceptable
})
}
}
// Test_Domain_UseMountReusable verifies that mounting the same sub-app on
// multiple domain routers does not double-wrap handlers (the original sub-app
// is not mutated).
func Test_Domain_UseMountReusable(t *testing.T) {
t.Parallel()
app := New()
subApp := domainTestApp("/data", "data response")
app.Domain("api.example.com").Use("/v1", subApp)
app.Domain("admin.example.com").Use("/v1", subApp)
domainTestExpectBody(t, app, "api.example.com", "/v1/data", StatusOK, "data response")
domainTestExpectBody(t, app, "admin.example.com", "/v1/data", StatusOK, "data response")
domainTestExpect(t, app, "www.example.com", "/v1/data", StatusNotFound)
}
// Test_Domain_UseMountRoutesAfterMount verifies that routes added to a sub-app
// after it has been mounted on a domain router are NOT domain-filtered (since
// mount clones routes at mount time).
func Test_Domain_UseMountRoutesAfterMount(t *testing.T) {
t.Parallel()
app := New()
subApp := domainTestApp("/before", "before mount")
app.Domain("api.example.com").Use("/api", subApp)
// Register a route AFTER mounting — this will NOT be domain-filtered
// because mount() clones routes at mount time.
subApp.Get("/after", func(c Ctx) error { return c.SendString("after mount") })
domainTestExpectBody(t, app, "api.example.com", "/api/before", StatusOK, "before mount")
domainTestExpect(t, app, "www.example.com", "/api/before", StatusNotFound)
// Route registered after mount on the original sub-app is NOT included
// in the wrapper. Since the mount group references the wrapper, the
// after-mount route is never expanded into the parent app.
domainTestExpect(t, app, "api.example.com", "/api/after", StatusNotFound)
}
// Test_Domain_UseMountNested verifies that a sub-app that itself mounts another
// app can be mounted on a domain router: the nested routes are served under the
// domain and are filtered by host like any other domain-mounted route.
func Test_Domain_UseMountNested(t *testing.T) {
t.Parallel()
child := domainTestApp("/x", "nested x")
subApp := routerDomainWith("/v1", child)
subApp.Get("/flat", func(c Ctx) error { return c.SendString("flat") })
app := routerDomainMount(subApp)
domainTestExpectBody(t, app, "api.example.com", "/api/v1/x", StatusOK, "nested x")
// The sub-app's own routes still work alongside the nested ones
domainTestExpectBody(t, app, "api.example.com", "/api/flat", StatusOK, "flat")
domainTestExpect(t, app, "www.example.com", "/api/v1/x", StatusNotFound)
domainTestExpect(t, app, "www.example.com", "/api/flat", StatusNotFound)
}