Skip to content

Commit 903cff2

Browse files
authored
Propagate inline middlewares across mounted subrouters (#1049)
* add tests to cover broken scenarios * fix missing middlewares in Walk function
1 parent 142fada commit 903cff2

2 files changed

Lines changed: 62 additions & 0 deletions

File tree

‎tree.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -841,6 +841,12 @@ func walk(r Routes, walkFn WalkFunc, parentRoute string, parentMw ...func(http.H
841841
mws = append(mws, r.Middlewares()...)
842842

843843
if route.SubRoutes != nil {
844+
if handler, ok := route.Handlers["*"]; ok {
845+
if chain, ok := handler.(*ChainHandler); ok {
846+
mws = append(mws, chain.Middlewares...)
847+
}
848+
}
849+
844850
if err := walk(route.SubRoutes, walkFn, parentRoute+route.Pattern, mws...); err != nil {
845851
return err
846852
}

‎tree_test.go‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -521,3 +521,59 @@ func TestWalker(t *testing.T) {
521521
t.Error(err)
522522
}
523523
}
524+
525+
func TestWalkInlineMiddlewaresAcrossSubrouter(t *testing.T) {
526+
mw := func(next http.Handler) http.Handler { return next }
527+
handler := func(w http.ResponseWriter, r *http.Request) {}
528+
529+
tests := []struct {
530+
name string
531+
setup func() Router
532+
expected int
533+
}{
534+
{
535+
name: "With+Group wrapping Route+With",
536+
setup: func() Router {
537+
r := NewMux()
538+
r.With(mw).Group(func(r Router) {
539+
r.Route("/foo", func(r Router) {
540+
r.With(mw).Post("/bar", handler)
541+
})
542+
})
543+
return r
544+
},
545+
expected: 2,
546+
},
547+
{
548+
name: "Use on subrouter combined with outer With",
549+
setup: func() Router {
550+
r := NewMux()
551+
r.With(mw).Group(func(r Router) {
552+
r.Route("/foo", func(r Router) {
553+
r.Use(mw)
554+
r.With(mw).Post("/bar", handler)
555+
})
556+
})
557+
return r
558+
},
559+
expected: 3,
560+
},
561+
}
562+
563+
for _, tt := range tests {
564+
t.Run(tt.name, func(t *testing.T) {
565+
r := tt.setup()
566+
var middlewareCount int
567+
err := Walk(r, func(method, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
568+
middlewareCount = len(middlewares)
569+
return nil
570+
})
571+
if err != nil {
572+
t.Fatal(err)
573+
}
574+
if middlewareCount != tt.expected {
575+
t.Fatalf("expected %d middlewares, got %d", tt.expected, middlewareCount)
576+
}
577+
})
578+
}
579+
}

0 commit comments

Comments
 (0)