| 50 | } |
| 51 | |
| 52 | func TestGroup_ScopedMiddleware(t *testing.T) { |
| 53 | app := New() |
| 54 | |
| 55 | var groupMwCalled bool |
| 56 | groupMw := func(next Handler) Handler { |
| 57 | return func(c *Ctx) error { |
| 58 | groupMwCalled = true |
| 59 | return next(c) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | api := app.Group("/api", groupMw) |
| 64 | api.Get("/protected", func(c *Ctx) error { return c.SendString("ok") }) |
| 65 | app.Get("/public", func(c *Ctx) error { return c.SendString("public") }) |
| 66 | |
| 67 | // Group route → middleware must run. |
| 68 | groupMwCalled = false |
| 69 | req := httptest.NewRequest(http.MethodGet, "/api/protected", nil) |
| 70 | httptest.NewRecorder() |
| 71 | rr := httptest.NewRecorder() |
| 72 | app.ServeHTTP(rr, req) |
| 73 | if !groupMwCalled { |
| 74 | t.Error("expected group middleware to run on /api/protected") |
| 75 | } |
| 76 | |
| 77 | // Route outside group → middleware must NOT run. |
| 78 | groupMwCalled = false |
| 79 | req2 := httptest.NewRequest(http.MethodGet, "/public", nil) |
| 80 | rr2 := httptest.NewRecorder() |
| 81 | app.ServeHTTP(rr2, req2) |
| 82 | if groupMwCalled { |
| 83 | t.Error("group middleware ran on a route outside the group") |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | func TestGroup_MiddlewareOrder(t *testing.T) { |
| 88 | app := New() |