diff --git a/echo.go b/echo.go index 8a77acf3..4453253c 100644 --- a/echo.go +++ b/echo.go @@ -476,7 +476,6 @@ func (e *Echo) add(method, path string, handler HandlerFunc, middleware ...Middl Handler: name, } e.router.routes[method+path] = r - // e.router.routes = append(e.router.routes, r) } // Group creates a new router group with prefix and optional group-level middleware. diff --git a/group.go b/group.go index 66706a8e..421b9465 100644 --- a/group.go +++ b/group.go @@ -126,8 +126,10 @@ func (g *Group) Match(methods []string, path string, handler HandlerFunc, middle } // Group creates a new sub-group with prefix and optional sub-group-level middleware. -func (g *Group) Group(prefix string, m ...MiddlewareFunc) *Group { - m = append(g.middleware, m...) +func (g *Group) Group(prefix string, middleware ...MiddlewareFunc) *Group { + m := []MiddlewareFunc{} + m = append(m, g.middleware...) + m = append(m, middleware...) return g.echo.Group(g.prefix+prefix, m...) } @@ -142,6 +144,11 @@ func (g *Group) File(path, file string) { } func (g *Group) add(method, path string, handler HandlerFunc, middleware ...MiddlewareFunc) { - middleware = append(g.middleware, middleware...) - g.echo.add(method, g.prefix+path, handler, middleware...) + // Combine into a new slice, to avoid accidentally passing the same + // slice for multiple routes, which would lead to later add() calls overwriting + // the middleware from earlier calls + m := []MiddlewareFunc{} + m = append(m, g.middleware...) + m = append(m, middleware...) + g.echo.add(method, g.prefix+path, handler, m...) } diff --git a/group_test.go b/group_test.go index fccfbe65..0d131c60 100644 --- a/group_test.go +++ b/group_test.go @@ -1,6 +1,9 @@ package echo -import "testing" +import ( + "github.com/stretchr/testify/assert" + "testing" +) // TODO: Fix me func TestGroup(t *testing.T) { @@ -29,3 +32,23 @@ func TestGroup(t *testing.T) { g.Static("/static", "/tmp") g.File("/walle", "_fixture/images//walle.png") } + +func TestGroupRouteMiddleware(t *testing.T) { + // Ensure middleware slices are not re-used + e := New() + g := e.Group("/group") + h := func(Context) error { return nil } + m1 := WrapMiddleware(func(c Context) error { return nil }) + m2 := WrapMiddleware(func(c Context) error { return nil }) + m3 := WrapMiddleware(func(c Context) error { return nil }) + m4 := WrapMiddleware(func(c Context) error { return c.NoContent(404) }) + m5 := WrapMiddleware(func(c Context) error { return c.NoContent(405) }) + g.Use(m1, m2, m3) + g.GET("/404", h, m4) + g.GET("/405", h, m5) + + c, _ := request(GET, "/group/404", e) + assert.Equal(t, 404, c) + c, _ = request(GET, "/group/405", e) + assert.Equal(t, 405, c) +}