Repository navigation
Expand file tree
/
Copy pathmount_test.go
More file actions
883 lines (754 loc) · 30.2 KB
/
Copy pathmount_test.go
File metadata and controls
883 lines (754 loc) · 30.2 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
// ⚡️ 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"
"fmt"
"regexp"
"slices"
"testing"
"github.com/gofiber/fiber/v3/internal/apptest"
"github.com/stretchr/testify/require"
)
func Test_App_Mount_PreservesSubAppRegexHandler(t *testing.T) {
t.Parallel()
parent := New(Config{
CaseSensitive: true,
RegexHandler: func(pattern string) *matchOnlyRegexCompiler {
return &matchOnlyRegexCompiler{re: regexp.MustCompile("(?i)" + pattern)}
},
})
sub := New(Config{CaseSensitive: true, RegexHandler: regexp.MustCompile})
sub.Get("/resource/:id<regex(ALLOW)>", func(c Ctx) error { return c.SendStatus(StatusOK) })
parent.Use("/mounted", sub)
apptest.Expect(t, sub, "/resource/ALLOW", StatusOK)
apptest.Expect(t, parent, "/mounted/resource/ALLOW", StatusOK)
apptest.Expect(t, sub, "/resource/allow", StatusNotFound)
apptest.Expect(t, parent, "/mounted/resource/allow", StatusNotFound)
}
func Test_App_Mount(t *testing.T) {
t.Parallel()
micro := New()
micro.Get("/doe", func(c Ctx) error { return c.SendStatus(StatusOK) })
app := New()
app.Use("/john", micro)
apptest.Expect(t, app, "/john/doe", 200)
require.Equal(t, uint32(2), app.handlersCount)
}
func Test_App_Mount_RootPath_Nested(t *testing.T) {
t.Parallel()
app := New()
dynamic := New()
apiserver := New()
apiroutes := apiserver.Group("/v1")
apiroutes.Get("/home", func(c Ctx) error { return c.SendString("home") })
dynamic.Use("/api", apiserver)
app.Use("/", dynamic)
apptest.Expect(t, app, "/api/v1/home", 200)
require.Equal(t, uint32(2), app.handlersCount)
}
func Test_App_Mount_Nested(t *testing.T) {
t.Parallel()
app := New()
one := New()
two := New()
three := New()
two.Use("/three", three)
app.Use("/one", one)
one.Use("/two", two)
one.Get("/doe", func(c Ctx) error { return c.SendStatus(StatusOK) })
two.Get("/nested", func(c Ctx) error { return c.SendStatus(StatusOK) })
three.Get("/test", func(c Ctx) error { return c.SendStatus(StatusOK) })
for _, path := range []string{"/one/doe", "/one/two/nested", "/one/two/three/test"} {
apptest.Expect(t, app, path, 200)
}
require.Equal(t, uint32(6), app.handlersCount)
}
func Test_App_Mount_Express_Behavior(t *testing.T) {
t.Parallel()
createTestHandler := func(body string) func(c Ctx) error { return func(c Ctx) error { return c.SendString(body) } }
app := New()
subApp := New()
subApp.Get("/hello", createTestHandler("subapp hello!"))
subApp.Get("/world", createTestHandler("subapp world!")) // <- wins
app.Get("/hello", createTestHandler("app hello!")) // <- wins
app.Use("/", subApp) // <- subApp registration
app.Get("/world", createTestHandler("app world!"))
app.Get("/bar", createTestHandler("app bar!"))
subApp.Get("/bar", createTestHandler("subapp bar!")) // <- wins
subApp.Get("/foo", createTestHandler("subapp foo!")) // <- wins
app.Get("/foo", createTestHandler("app foo!"))
// 404 Handler
app.Use(func(c Ctx) error { return c.SendStatus(StatusNotFound) })
apptest.ExpectBody(t, app, "/world", StatusOK, "subapp world!")
apptest.ExpectBody(t, app, "/hello", StatusOK, "app hello!")
apptest.ExpectBody(t, app, "/bar", StatusOK, "subapp bar!")
apptest.ExpectBody(t, app, "/foo", StatusOK, "subapp foo!")
apptest.ExpectBody(t, app, "/unknown", StatusNotFound, ErrNotFound.Message)
require.Equal(t, uint32(17), app.handlersCount)
}
func Test_App_Mount_RoutePositions(t *testing.T) {
t.Parallel()
app := New()
subApp1 := New()
subApp2 := New()
app.Use(func(c Ctx) error {
c.Locals("world", "world")
return c.Next()
})
app.Use("/subApp1", subApp1)
app.Use(func(c Ctx) error { return c.Next() })
app.Get("/bar", func(c Ctx) error { return c.SendString("ok") })
app.Use(func(c Ctx) error {
// is overwritten when the positioning is not correct
c.Locals("world", "hello")
return c.Next()
})
methods := subApp2.Group("/subApp2")
methods.Get("/world", func(c Ctx) error {
v, ok := c.Locals("world").(string)
if !ok {
panic("unexpected data type")
}
return c.SendString(v)
})
app.Use("", subApp2)
apptest.ExpectBody(t, app, "/subApp2/world", StatusOK, "hello")
routeStackGET := app.Stack()[0]
require.Len(t, routeStackGET, 5)
for i, want := range []struct {
path string
use bool
}{{"/", true}, {"/", true}, {"/bar", false}, {"/", true}, {"/subapp2/world", false}} {
require.Equal(t, want.use, routeStackGET[i].use, "route %d", i)
require.Equal(t, want.path, routeStackGET[i].path, "route %d", i)
}
}
func Test_App_MountPath(t *testing.T) {
t.Parallel()
app := New()
one := New()
two := New()
three := New()
two.Use("/three", three)
one.Use("/two", two)
app.Use("/one", one)
require.Equal(t, "/one", one.MountPath())
require.Equal(t, "/one/two", two.MountPath())
require.Equal(t, "/one/two/three", three.MountPath())
require.Empty(t, app.MountPath())
}
func Test_App_Mount_ErrorHandler(t *testing.T) {
t.Parallel()
const (
routeErr = "0: GET error"
body = "1: custom error"
)
tests := []struct {
name string
group string // the mounted app is mounted on this group of the parent when set
prefix string // where the mounted app is mounted
route string // the route of the mounted app, which always fails
target string // the request that reaches the failing route
// handledByParent tells which app has the custom error handler: the one mounting or the mounted one.
handledByParent bool
}{
{name: "group mount", group: "/v1", prefix: "/john", route: "/doe", target: "/v1/john/doe"},
{name: "group mount at the root level", group: "/v1", prefix: "/", route: "/john/doe", target: "/v1/john/doe"},
{name: "the mounting app's handler is used", prefix: "/api", route: "/", target: "/api", handledByParent: true},
{name: "the mounted app's handler is used", prefix: "/api", route: "/", target: "/api"},
{name: "the mounted app's handler is used at the root level", prefix: "/", route: "/api", target: "/api"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
errorHandler := func(c Ctx, err error) error {
require.Equal(t, routeErr, err.Error())
return c.Status(StatusInternalServerError).SendString(body)
}
app := New()
micro := New()
if tc.handledByParent {
app = New(Config{ErrorHandler: errorHandler})
} else {
micro = New(Config{ErrorHandler: errorHandler})
}
micro.Get(tc.route, func(_ Ctx) error { return errors.New(routeErr) })
var router Router = app
if tc.group != "" {
router = app.Group(tc.group)
}
router.Use(tc.prefix, micro)
apptest.ExpectBody(t, app, tc.target, StatusInternalServerError, body)
})
}
}
func Test_App_Group_Mount(t *testing.T) {
t.Parallel()
micro := New()
micro.Get("/doe", func(c Ctx) error { return c.SendStatus(StatusOK) })
app := New()
v1 := app.Group("/v1")
v1.Use("/john", micro)
apptest.Expect(t, app, "/v1/john/doe", 200)
require.Equal(t, uint32(2), app.handlersCount)
}
func Test_App_UseMountedErrorHandlerForBestPrefixMatch(t *testing.T) {
t.Parallel()
app := New()
tripleSubFiber := domainTestFailingApp(200, "hi, i'm a custom sub fiber error 2", "/")
subfiber := domainTestFailingApp(200, "hi, i'm a custom sub fiber error", "/")
subfiber.Use("/third", tripleSubFiber)
fiber := domainTestFailingApp(200, "hi, i'm a custom error", "/")
fiber.Use("/sub", subfiber)
app.Use("/api", fiber)
apptest.ExpectBody(t, app, "/api/sub", 200, "hi, i'm a custom sub fiber error")
apptest.ExpectBody(t, app, "/api/sub/third", 200, "hi, i'm a custom sub fiber error 2")
}
func Test_Mount_Route_Names(t *testing.T) {
t.Parallel()
subApp1 := New()
subApp1.Get("/users", func(c Ctx) error {
url, err := c.GetRouteURL("add-user", Map{})
require.NoError(t, err)
require.Equal(t, "/app1/users", url, "handler: app1.add-user") // the prefix is /app1 because of the mount
// if subApp1 is not mounted, expected url just /users
return nil
}).Name("get-users")
subApp1.Post("/users", func(c Ctx) error {
route := c.App().GetRoute("get-users")
require.Equal(t, MethodGet, route.Method, "handler: app1.get-users method")
require.Equal(t, "/app1/users", route.Path, "handler: app1.get-users path")
return nil
}).Name("add-user")
subApp2 := New()
app2Grp := subApp2.Group("/users").Name("users.")
app2Grp.Get("", emptyHandler).Name("get")
app2Grp.Post("", emptyHandler).Name("add")
rootApp := New()
_ = rootApp.Use("/app1", subApp1)
_ = rootApp.Use("/app2", subApp2)
rootApp.startupProcess()
for _, tc := range []struct {
app *App
name string
method string
path string
}{
// take route directly from sub-app
{app: subApp1, name: "get-users", method: MethodGet, path: "/users"},
{app: subApp1, name: "add-user", method: MethodPost, path: "/users"},
// take route directly from sub-app with group
{app: subApp2, name: "users.get", method: MethodGet, path: "/users"},
{app: subApp2, name: "users.add", method: MethodPost, path: "/users"},
// take route from root app (using names of sub-apps)
{app: rootApp, name: "add-user", method: MethodPost, path: "/app1/users"},
{app: rootApp, name: "users.add", method: MethodPost, path: "/app2/users"},
} {
route := tc.app.GetRoute(tc.name)
require.Equal(t, tc.method, route.Method, tc.name)
require.Equal(t, tc.path, route.Path, tc.name)
}
// GetRouteURL inside handler
apptest.Expect(t, rootApp, "/app1/users", StatusOK)
// ctx.App().GetRoute() inside handler
apptest.Expect(t, rootApp, apptest.Req(MethodPost, "/app1/users"), StatusOK)
}
func Test_Ctx_Render_Mount(t *testing.T) {
t.Parallel()
sub := New(Config{Views: domainTestEngine(t, "")})
sub.Get("/:name", func(c Ctx) error { return c.Render("hello_world.tmpl", Map{"Name": c.Params("name")}) })
app := New()
app.Use("/hello", sub)
apptest.ExpectBody(t, app, "/hello/a", StatusOK, "<h1>Hello a!</h1>")
}
func Test_Ctx_Render_Mount_ParentOrSubHasViews(t *testing.T) {
t.Parallel()
sub := New(Config{Views: domainTestEngine(t, "testdata3")})
sub2 := New(Config{Views: domainTestEngine(t, "testdata2")})
app := New(Config{Views: domainTestEngine(t, "")})
app.Get("/test", func(c Ctx) error { return c.Render("index.tmpl", Map{"Title": "Hello, World!"}) })
sub.Get("/world/:name", func(c Ctx) error { return c.Render("hello_world.tmpl", Map{"Name": c.Params("name")}) })
sub2.Get("/moment", func(c Ctx) error { return c.Render("bruh.tmpl", Map{}) })
sub.Use("/bruh", sub2)
app.Use("/hello", sub)
apptest.ExpectBody(t, app, "/hello/world/a", StatusOK, "<h1>Hello a!</h1>")
apptest.ExpectBody(t, app, "/test", StatusOK, "<h1>Hello, World!</h1>")
apptest.ExpectBody(t, app, "/hello/bruh/moment", StatusOK, "<h1>I'm Bruh</h1>")
}
func Test_Ctx_Render_MountGroup(t *testing.T) {
t.Parallel()
micro := New(Config{Views: domainTestEngine(t, "")})
micro.Get("/doe", func(c Ctx) error { return c.Render("hello_world.tmpl", Map{"Name": "doe"}) })
app := New()
v1 := app.Group("/v1")
v1.Use("/john", micro)
apptest.ExpectBody(t, app, "/v1/john/doe", 200, "<h1>Hello doe!</h1>")
}
// Test_App_Mount_FewerRequestMethods verifies that a sub-app serving only some
// of the parent's request methods can be mounted, directly and through another
// mount: the parent must read the sub-app's routes by method, not by its own
// stack index.
func Test_App_Mount_FewerRequestMethods(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name, path string
nested bool // micro is reached through another mount
}{
{name: "direct", path: "/john/doe"},
{name: "nested", path: "/john/v1/doe", nested: true},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
micro := New(Config{RequestMethods: []string{MethodGet}})
micro.Get("/doe", func(c Ctx) error { return c.SendString("doe") })
mounted := micro
if tc.nested {
mounted = New()
mounted.Use("/v1", micro)
}
app := New()
app.Use("/john", mounted)
apptest.ExpectBody(t, app, tc.path, StatusOK, "doe")
})
}
}
// Test_App_Mount_ReorderedRequestMethods verifies that a sub-app which lists
// the same request methods in a different order keeps serving each route under
// the method it was registered with.
func Test_App_Mount_ReorderedRequestMethods(t *testing.T) {
t.Parallel()
// Swap GET and POST, so the two apps' stack indexes disagree.
methods := append([]string{}, DefaultMethods...)
for i, method := range methods {
switch method {
case MethodGet:
methods[i] = MethodPost
case MethodPost:
methods[i] = MethodGet
}
}
micro := New(Config{RequestMethods: methods})
micro.Get("/doe", func(c Ctx) error { return c.SendString("get doe") })
micro.Post("/doe", func(c Ctx) error { return c.SendString("post doe") })
app := New()
app.Use("/john", micro)
apptest.ExpectBody(t, app, "/john/doe", StatusOK, "get doe")
apptest.ExpectBody(t, app, apptest.Req(MethodPost, "/john/doe"), StatusOK, "post doe")
}
// onlyFooConstraint and onlyBarConstraint are custom constraints used to check
// that a mounted app's constraints survive the mount's route expansion.
type onlyFooConstraint struct{}
func (*onlyFooConstraint) Name() string { return "onlyfoo" }
func (*onlyFooConstraint) Execute(param string, _ ...string) bool { return param == "foo" }
type onlyBarConstraint struct{}
func (*onlyBarConstraint) Name() string { return "onlybar" }
func (*onlyBarConstraint) Execute(param string, _ ...string) bool { return param == "bar" }
// mountSameNameConstraint is named "same" whatever value it accepts, as two
// apps mounted side by side are free to give one name different meanings.
type mountSameNameConstraint struct{ allowed string }
func (*mountSameNameConstraint) Name() string { return "same" }
func (c *mountSameNameConstraint) Execute(param string, _ ...string) bool { return param == c.allowed }
// Test_App_Mount_SiblingConstraintNames verifies that a constraint binds only
// the routes of the app that registered it: two apps mounted side by side can
// name one differently, and the app above them must not hold either to the
// other's.
func Test_App_Mount_SiblingConstraintNames(t *testing.T) {
t.Parallel()
// A fresh tree per case: mounting one app on two parents would have the
// first expand it before the second cloned it.
build := func() *App {
handler := func(c Ctx) error { return c.SendString("ok") }
foo := New()
foo.RegisterCustomConstraint(&mountSameNameConstraint{allowed: "foo"})
foo.Get("/:value<same>", handler)
bar := New()
bar.RegisterCustomConstraint(&mountSameNameConstraint{allowed: "bar"})
bar.Get("/:value<same>", handler)
subApp := New()
subApp.Use("/foo", foo)
subApp.Use("/bar", bar)
return subApp
}
plain := New()
plain.Use("/sub", build())
domain := New()
domain.Domain("api.example.com").Use("/sub", build())
want := map[string]int{
"/sub/foo/foo": StatusOK,
"/sub/foo/bar": StatusNotFound,
"/sub/bar/bar": StatusOK,
"/sub/bar/foo": StatusNotFound,
}
for path, status := range want {
resp := apptest.Do(t, plain, path)
require.Equal(t, status, resp.StatusCode, "plain "+path)
resp = apptest.Do(t, domain, apptest.Req(MethodGet, path, apptest.WithHost("api.example.com")))
require.Equal(t, status, resp.StatusCode, "domain "+path)
}
}
// Test_App_Mount_PreservesNestedCustomConstraint verifies that a custom
// constraint registered on an app reached through two mounts still validates.
// Expanding a mount re-parses the routes against the app above, so the
// constraint has to travel with them or it silently stops rejecting anything.
func Test_App_Mount_PreservesNestedCustomConstraint(t *testing.T) {
t.Parallel()
micro := New()
micro.RegisterCustomConstraint(&onlyFooConstraint{})
micro.Get("/doe/:name<onlyfoo>", func(c Ctx) error { return c.SendString(c.Params("name")) })
sub := New()
sub.Use("/v1", micro)
app := New()
app.Use("/john", sub)
apptest.Expect(t, app, "/john/v1/doe/foo", StatusOK)
apptest.Expect(t, app, "/john/v1/doe/bar", StatusNotFound)
}
// Test_App_Mount_CarriesDomainMount verifies that mounting an app which has a
// domain mount of its own carries that mount's config along, host check
// included.
func Test_App_Mount_CarriesDomainMount(t *testing.T) {
t.Parallel()
micro := domainTestFailingApp(596, "micro error", "/doe")
sub := New()
sub.Domain("api.example.com").Use("/v1", micro)
app := New()
app.Use("/john", sub)
apptest.Expect(t, app, apptest.Req(MethodGet, "/john/v1/doe", apptest.WithHost("api.example.com")), 596)
// The route does not match on another host, and the sub-app's error
// handler must not answer for it either.
apptest.Expect(t, app, apptest.Req(MethodGet, "/john/v1/doe", apptest.WithHost("www.example.com")), StatusNotFound)
}
// routerMountVariant is a way to mount an app: mount puts micro into app, prefix is where micro's routes are served
// and host is the Host that reaches them.
type routerMountVariant struct {
mount func(app, micro *App)
host apptest.Option
name string
prefix string
}
// routerMountVariants are the two ways a test mounts an app: plainly under /john, and through a domain router under
// /api on api.example.com.
var routerMountVariants = []routerMountVariant{
{
name: "plain", prefix: "/john", host: apptest.WithHost("example.com"),
mount: func(app, micro *App) { app.Use("/john", micro) },
},
{
name: "domain", prefix: "/api", host: apptest.WithHost("api.example.com"),
mount: func(app, micro *App) { app.Domain("api.example.com").Use("/api", micro) },
},
}
// Test_App_Mount_AutoHeadKeepsMiddleware verifies that a mounted app which does
// not serve HEAD gets no synthesized HEAD routes once its routes are expanded
// into the parent, directly or through a domain router — they would run without
// the middleware it registered.
func Test_App_Mount_AutoHeadKeepsMiddleware(t *testing.T) {
t.Parallel()
// The same behind another mount: once flattened, the app that left HEAD out is no longer walked, only its
// routes' marks are.
apiHost := apptest.WithHost("api.example.com")
flattened := []routerMountVariant{
{name: "inner domain mount", prefix: "/mid/sub", host: apiHost, mount: func(app, micro *App) {
mid := New()
mid.Domain("api.example.com").Use("/sub", micro)
app.Domain("api.example.com").Use("/mid", mid)
}},
{name: "plain mount over a domain mount", prefix: "/mid/sub", host: apiHost, mount: func(app, micro *App) {
inner := New()
inner.Domain("api.example.com").Use("/sub", micro)
mid := New()
mid.Use("/", inner)
app.Domain("api.example.com").Use("/mid", mid)
}},
{name: "started before mounting", prefix: "/mid/sub", host: apiHost, mount: func(app, micro *App) {
mid := New()
mid.Use("/sub", micro)
mid.Handler()
app.Domain("api.example.com").Use("/mid", mid)
}},
}
for _, tc := range slices.Concat(routerMountVariants, flattened) {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
micro := New(Config{RequestMethods: []string{MethodGet, MethodPost}})
micro.Use(func(c Ctx) error { return c.SendStatus(StatusUnauthorized) })
micro.Get("/doe", func(c Ctx) error {
c.Set("X-Secret", "leaked")
return c.SendString("doe")
})
app := New()
tc.mount(app, micro)
target := tc.prefix + "/doe"
apptest.Expect(t, app, apptest.Req(MethodGet, target, tc.host), StatusUnauthorized)
// Twice: app.Test runs the startup process on every call, and the second
// pass sees the mount already expanded into the parent's stack.
for range 2 {
resp := apptest.Expect(t, app, apptest.Req(MethodHead, target, tc.host), StatusMethodNotAllowed)
require.Empty(t, resp.Header.Get("X-Secret"))
}
})
}
}
// Test_App_Mount_ParentDisableHeadAutoRegister verifies that an app that turned the automatic HEAD
// routes off takes none from the apps mounted into it: a guard it registered with Get has no HEAD
// companion, so a HEAD route flattened from a sub-app would run the handler without it.
func Test_App_Mount_ParentDisableHeadAutoRegister(t *testing.T) {
t.Parallel()
// The shared variants, plus the shapes a parent's opt-out has to reach: a group, a nested
// mount, and apps started before they were mounted.
host := apptest.WithHost("example.com")
extra := []routerMountVariant{
{name: "group", prefix: "/admin", host: host, mount: func(app, sub *App) { app.Group("/admin").Use("/", sub) }},
{name: "nested", prefix: "/admin", host: host, mount: func(app, sub *App) {
mid := New()
mid.Use("/", sub)
app.Use("/admin", mid)
}},
{name: "started before mounting", prefix: "/admin", host: host, mount: func(app, sub *App) {
sub.Handler()
app.Use("/admin", sub)
}},
{name: "domain started before mounting", prefix: "/admin", host: apptest.WithHost("api.example.com"), mount: func(app, sub *App) {
sub.Handler()
app.Domain("api.example.com").Use("/admin", sub)
}},
}
for _, tc := range slices.Concat(routerMountVariants, extra) {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
app := New(Config{DisableHeadAutoRegister: true})
app.Get(tc.prefix+"/*", func(c Ctx) error {
c.Set("X-Guard", "ran")
return c.Next()
})
sub := New()
sub.Get("/x", func(c Ctx) error {
c.Set("X-Secret", "leaked")
return c.SendString("admin")
})
tc.mount(app, sub)
target := tc.prefix + "/x"
resp := apptest.ExpectBody(t, app, apptest.Req(MethodGet, target, tc.host), StatusOK, "admin")
require.Equal(t, "ran", resp.Header.Get("X-Guard"))
// Twice: the second pass sees the mount already expanded into the parent's stack.
for range 2 {
resp = apptest.Expect(t, app, apptest.Req(MethodHead, target, tc.host), StatusMethodNotAllowed)
require.Empty(t, resp.Header.Get("X-Secret"))
}
require.Empty(t, app.Stack()[app.methodInt(MethodHead)])
})
}
}
// Test_App_Mount_RootMountKeepsParentAutoHead verifies that a mounted app which
// does not serve HEAD only withholds automatic HEAD routes from its own routes.
// A mount at "/" covers every path, and the app above keeps its own.
func Test_App_Mount_RootMountKeepsParentAutoHead(t *testing.T) {
t.Parallel()
micro := New(Config{RequestMethods: []string{MethodGet, MethodPost}})
micro.Get("/doe", func(c Ctx) error { return c.SendString("doe") })
app := New()
app.Get("/own", func(c Ctx) error { return c.SendString("own") })
app.Use("/", micro)
// the app's own route keeps its HEAD route
apptest.Expect(t, app, apptest.Req(MethodHead, "/own"), StatusOK)
// the mounted app serves no HEAD
apptest.Expect(t, app, apptest.Req(MethodHead, "/doe"), StatusMethodNotAllowed)
}
// Test_App_Mount_ParametricPrefix verifies that a mount prefix carrying a
// parameter is matched as a pattern, also when an outer mount applies the
// prefix a second time. The prefix rewrites every route of the mounted app, so
// the parameters it introduces have to be rebuilt onto them.
func Test_App_Mount_ParametricPrefix(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
name, param, path string
nested bool // micro is mounted under the prefix by an app that is mounted itself
}{
{name: "direct", param: "Version", path: "/v1/42/doe"},
{name: "nested", param: "version", path: "/john/v1/42/doe", nested: true},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
micro := New()
micro.Get("/doe", func(c Ctx) error { return c.SendString("version=" + c.Params(tc.param)) })
app := New()
if tc.nested {
sub := New()
sub.Use("/v1/:"+tc.param, micro)
app.Use("/john", sub)
} else {
app.Use("/v1/:"+tc.param, micro)
}
apptest.ExpectBody(t, app, tc.path, StatusOK, "version=42")
})
}
}
// Test_App_Mount_CaseInsensitivePath verifies that a mount path is matched by
// the app's own routing rules when its config is resolved: a case-insensitive
// app serves "/api/doe" from a mount registered as "/API", so the mounted app's
// error handler has to answer for it too.
func Test_App_Mount_CaseInsensitivePath(t *testing.T) {
t.Parallel()
micro := domainTestFailingApp(599, "micro error", "/doe")
app := New()
app.Use("/API", micro)
apptest.Expect(t, app, "/api/doe", 599)
// A case-sensitive app keeps the two apart.
strict := New(Config{CaseSensitive: true})
strict.Use("/API", micro)
apptest.Expect(t, strict, "/API/doe", 599)
apptest.Expect(t, strict, "/api/doe", StatusNotFound)
}
// Test_App_Mount_ViewsPathOnly verifies that a mounted app's views are chosen
// by the request path, not by its mount path appearing anywhere in the URL — a
// query string carrying it must not select them.
func Test_App_Mount_ViewsPathOnly(t *testing.T) {
t.Parallel()
for _, tc := range routerMountVariants {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
micro := New(Config{Views: domainTestEngine(t, "testdata2")})
micro.Get("/view", func(c Ctx) error { return c.Render("bruh.tmpl", Map{}) })
app := New(Config{Views: domainTestEngine(t, "")})
tc.mount(app, micro)
app.Get("/elsewhere", func(c Ctx) error { return c.Render("index.tmpl", Map{"Title": "parent"}) })
req := apptest.Req(MethodGet, "/elsewhere?next="+tc.prefix+"/view", tc.host)
apptest.ExpectBody(t, app, req, StatusOK, "<h1>parent</h1>")
})
}
}
// Test_App_Mount_ParametricPrefixConstraint verifies that a constraint named in
// a mount prefix is enforced. The prefix belongs to the app doing the mounting,
// so its constraints have to reach the re-parse of the mounted routes.
func Test_App_Mount_ParametricPrefixConstraint(t *testing.T) {
t.Parallel()
micro := New()
micro.Get("/doe", func(c Ctx) error { return c.SendString("name=" + c.Params("name")) })
app := New()
app.RegisterCustomConstraint(&onlyFooConstraint{})
app.Use("/:name<onlyfoo>", micro)
apptest.Expect(t, app, "/foo/doe", StatusOK)
// the prefix constraint still rejects
apptest.Expect(t, app, "/bar/doe", StatusNotFound)
}
// routerPrefixSpellings are mount prefixes whose syntax the router has to take as written: an escaped colon or
// asterisk, a custom constraint and regular expression constraints. covered is a path the prefix names and outside
// are paths it does not.
var routerPrefixSpellings = []struct {
prefix, covered string
outside []string
}{
{prefix: `/v1\:internal`, covered: "/v1:internal", outside: []string{"/v1foo", "/v1"}},
{prefix: `/a\*`, covered: "/a*", outside: []string{"/a", "/a/b"}},
{prefix: "/even/:n<isEven>", covered: "/even/4", outside: []string{"/even/3", "/even/abc"}},
{prefix: "/code/:code<regex(^[A-Z]{2}$)>", covered: "/code/US", outside: []string{"/code/us"}},
{prefix: `/num/:n<regex(^\d+$)>`, covered: "/num/12", outside: []string{"/num/dd"}},
}
// Test_App_Mount_PrefixAsWritten verifies that mounted routes are re-parsed with
// the mount prefix as written, so they answer only where middleware on it runs.
func Test_App_Mount_PrefixAsWritten(t *testing.T) {
t.Parallel()
mounts := map[string]func(app *App, prefix string, guard Handler, micro *App){
"app": func(app *App, prefix string, guard Handler, micro *App) {
app.Use(prefix, guard)
app.Use(prefix, micro)
},
"group": func(app *App, prefix string, guard Handler, micro *App) {
grp := app.Group("/")
grp.Use(prefix, guard)
grp.Use(prefix, micro)
},
"domain": func(app *App, prefix string, guard Handler, micro *App) {
app.Use(prefix, guard)
app.Domain("example.com").Use(prefix, micro)
},
"nested in domain": func(app *App, prefix string, guard Handler, micro *App) {
mid := New()
mid.RegisterCustomConstraint(&evenConstraint{})
mid.Use(prefix, guard)
mid.Use(prefix, micro)
app.Domain("example.com").Use("/", mid)
},
}
for name, mount := range mounts {
for _, tc := range routerPrefixSpellings {
t.Run(name+" "+tc.prefix, func(t *testing.T) {
t.Parallel()
micro := New()
micro.Get("/doe", func(c Ctx) error { return c.SendString("doe") })
app := New()
app.RegisterCustomConstraint(&evenConstraint{})
mount(app, tc.prefix, func(c Ctx) error { return c.SendStatus(StatusUnauthorized) }, micro)
routerTestExpect(t, app, tc.covered+"/doe", StatusUnauthorized)
for _, outside := range tc.outside {
routerTestExpect(t, app, outside+"/doe", StatusNotFound)
}
})
}
}
}
// Test_App_Mount_NestedPrefixKeepsCase verifies that a nested mount keeps the
// case of its prefix when only the top-level app is case-sensitive.
func Test_App_Mount_NestedPrefixKeepsCase(t *testing.T) {
t.Parallel()
sub := New()
sub.Get("/secret", func(c Ctx) error { return c.SendString("secret") })
mid := New()
mid.Use("/Admin", sub)
app := New(Config{CaseSensitive: true})
app.Use("/v1/Admin", func(c Ctx) error { return c.SendStatus(StatusUnauthorized) })
app.Use("/v1", mid)
apptest.Expect(t, app, "/v1/Admin/secret", StatusUnauthorized)
apptest.Expect(t, app, "/v1/admin/secret", StatusNotFound)
}
func Test_App_Mount_StrictRouting(t *testing.T) {
t.Parallel()
tests := []struct {
path string
strict int
loose int
}{
{path: "/api/sub", strict: StatusOK, loose: StatusOK},
{path: "/api/sub/", strict: StatusNotFound, loose: StatusOK},
{path: "/api/p/7", strict: StatusOK, loose: StatusOK},
{path: "/api/p/7/", strict: StatusNotFound, loose: StatusOK},
}
for _, strict := range []bool{false, true} {
app := New(Config{StrictRouting: strict})
sub := New()
sub.Get("/sub", func(c Ctx) error { return c.SendString("plain") })
sub.Get("/p/:id", func(c Ctx) error { return c.SendString("param") })
app.Use("/api", sub)
for _, tc := range tests {
want := tc.loose
if strict {
want = tc.strict
}
resp := apptest.Do(t, app, tc.path)
require.Equal(t, want, resp.StatusCode, "strict=%v path=%q", strict, tc.path)
}
}
}
// Test_App_Mount_StrictRouting_RootMiddleware pins that a mounted app's root
// middleware runs for "/users", which "/users/:id?" answers under StrictRouting too.
func Test_App_Mount_StrictRouting_RootMiddleware(t *testing.T) {
t.Parallel()
for _, strict := range []bool{false, true} {
// "/u/" is as long as a tree hash, which "/u" is too short to carry
for prefix, mounted := range map[string]string{"/users": "/users", "/u": "/u", "/t/:tenant": "/t/acme"} {
for _, pattern := range []string{"/:id?", "/*"} {
t.Run(fmt.Sprintf("strict=%v/%s/%s", strict, prefix, pattern), func(t *testing.T) {
t.Parallel()
users := New()
users.Use(func(c Ctx) error { return c.SendStatus(StatusUnauthorized) })
users.Get(pattern, func(c Ctx) error { return c.SendString("users") })
app := New(Config{StrictRouting: strict})
app.Use(prefix, users)
routerTestExpectStatus(t, app, MethodGet, StatusUnauthorized, mounted, mounted+"/", mounted+"/7")
routerTestExpect(t, app, "/other", StatusNotFound)
})
}
}
}
}