Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions group.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,21 @@ type Group struct {
// `/*` NotFound routes for itself. If this kind of behavior is not needed, then create an Echo instance with the ` noAutoRegisterRoutes `
// flag set to true. Example `echo.NewWithConfig(echo.Config{NoGroupAutoRegister404Routes: true})`.
func (g *Group) Use(middleware ...MiddlewareFunc) {
// Track whether this is the first non-empty middleware attachment so we only
// auto-register 404 catch-alls once. Re-registering on every Use() panics when
// AllowOverwritingRoute is false (#3047).
hadMiddleware := len(g.middleware) > 0
g.middleware = append(g.middleware, middleware...)
if len(g.middleware) == 0 {
return
}
if g.noAutoRegisterRoutes {
return
}
if hadMiddleware {
// 404 routes already registered by a previous Use()/Group(...middleware).
return
}
// group level middlewares are different from Echo `Pre` and `Use` middlewares (those are global). Group level middlewares
// are only executed if they are added to the Router with route.
// So we register catch all route (404 is a safe way to emulate route match) for this group and now during routing the
Expand Down
33 changes: 33 additions & 0 deletions group_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -866,3 +866,36 @@ func TestGroup_RouteNotFoundWithMiddleware(t *testing.T) {
})
}
}


func TestGroup_UseMultipleTimesDoesNotPanic(t *testing.T) {
// Repro for #3047: second Use() used to re-register 404 routes and panic when
// AllowOverwritingRoute is false.
e := NewWithConfig(Config{
Router: NewRouter(RouterConfig{AllowOverwritingRoute: false}),
})

mw := func(next HandlerFunc) HandlerFunc {
return func(c *Context) error { return next(c) }
}

// Case 1: sequential Use on empty group
g1 := e.Group("/api")
assert.NotPanics(t, func() {
g1.Use(mw)
g1.Use(mw)
})

// Case 2: Group created with middleware, then Use again
g2 := e.Group("/v2", mw)
assert.NotPanics(t, func() {
g2.Use(mw)
})

// Case 3: nested group inherits middleware then Use
api := e.Group("/nested", mw)
res := api.Group("/resource")
assert.NotPanics(t, func() {
res.Use(mw)
})
}