(t *testing.T)
| 1390 | } |
| 1391 | |
| 1392 | func TestNestedGroups(t *testing.T) { |
| 1393 | handlerPrintCounter := func(w http.ResponseWriter, r *http.Request) { |
| 1394 | counter, _ := r.Context().Value(ctxKey{"counter"}).(int) |
| 1395 | w.Write([]byte(fmt.Sprintf("%v", counter))) |
| 1396 | } |
| 1397 | |
| 1398 | mwIncreaseCounter := func(next http.Handler) http.Handler { |
| 1399 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 1400 | ctx := r.Context() |
| 1401 | counter, _ := ctx.Value(ctxKey{"counter"}).(int) |
| 1402 | counter++ |
| 1403 | ctx = context.WithValue(ctx, ctxKey{"counter"}, counter) |
| 1404 | next.ServeHTTP(w, r.WithContext(ctx)) |
| 1405 | }) |
| 1406 | } |
| 1407 | |
| 1408 | // Each route represents value of its counter (number of applied middlewares). |
| 1409 | r := NewRouter() // counter == 0 |
| 1410 | r.Get("/0", handlerPrintCounter) |
| 1411 | r.Group(func(r Router) { |
| 1412 | r.Use(mwIncreaseCounter) // counter == 1 |
| 1413 | r.Get("/1", handlerPrintCounter) |
| 1414 | |
| 1415 | // r.Handle(GET, "/2", Chain(mwIncreaseCounter).HandlerFunc(handlerPrintCounter)) |
| 1416 | r.With(mwIncreaseCounter).Get("/2", handlerPrintCounter) |
| 1417 | |
| 1418 | r.Group(func(r Router) { |
| 1419 | r.Use(mwIncreaseCounter, mwIncreaseCounter) // counter == 3 |
| 1420 | r.Get("/3", handlerPrintCounter) |
| 1421 | }) |
| 1422 | r.Route("/", func(r Router) { |
| 1423 | r.Use(mwIncreaseCounter, mwIncreaseCounter) // counter == 3 |
| 1424 | |
| 1425 | // r.Handle(GET, "/4", Chain(mwIncreaseCounter).HandlerFunc(handlerPrintCounter)) |
| 1426 | r.With(mwIncreaseCounter).Get("/4", handlerPrintCounter) |
| 1427 | |
| 1428 | r.Group(func(r Router) { |
| 1429 | r.Use(mwIncreaseCounter, mwIncreaseCounter) // counter == 5 |
| 1430 | r.Get("/5", handlerPrintCounter) |
| 1431 | // r.Handle(GET, "/6", Chain(mwIncreaseCounter).HandlerFunc(handlerPrintCounter)) |
| 1432 | r.With(mwIncreaseCounter).Get("/6", handlerPrintCounter) |
| 1433 | |
| 1434 | }) |
| 1435 | }) |
| 1436 | }) |
| 1437 | |
| 1438 | ts := httptest.NewServer(r) |
| 1439 | defer ts.Close() |
| 1440 | |
| 1441 | for _, route := range []string{"0", "1", "2", "3", "4", "5", "6"} { |
| 1442 | if _, body := testRequest(t, ts, "GET", "/"+route, nil); body != route { |
| 1443 | t.Errorf("expected %v, got %v", route, body) |
| 1444 | } |
| 1445 | } |
| 1446 | } |
| 1447 | |
| 1448 | func TestMiddlewarePanicOnLateUse(t *testing.T) { |
| 1449 | handler := func(w http.ResponseWriter, r *http.Request) { |
nothing calls this directly
no test coverage detected