MCPcopy
hub / github.com/go-chi/chi / TestRouteHeaders

Function TestRouteHeaders

middleware/route_headers_test.go:10–185  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

8)
9
10func TestRouteHeaders(t *testing.T) {
11 t.Run("empty router should call next handler exactly once", func(t *testing.T) {
12 var callCount atomic.Int32
13
14 hr := RouteHeaders()
15
16 handler := hr.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
17 callCount.Add(1)
18 w.WriteHeader(http.StatusOK)
19 }))
20
21 req := httptest.NewRequest("GET", "/", nil)
22 rec := httptest.NewRecorder()
23
24 handler.ServeHTTP(rec, req)
25
26 if callCount.Load() != 1 {
27 t.Errorf("expected next handler to be called exactly once, but was called %d times", callCount.Load())
28 }
29 })
30
31 t.Run("matching header should route to correct middleware", func(t *testing.T) {
32 var matchedRoute string
33
34 hr := RouteHeaders().
35 Route("Host", "example.com", func(next http.Handler) http.Handler {
36 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
37 matchedRoute = "example.com"
38 next.ServeHTTP(w, r)
39 })
40 }).
41 Route("Host", "other.com", func(next http.Handler) http.Handler {
42 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
43 matchedRoute = "other.com"
44 next.ServeHTTP(w, r)
45 })
46 })
47
48 handler := hr.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
49 w.WriteHeader(http.StatusOK)
50 }))
51
52 req := httptest.NewRequest("GET", "/", nil)
53 req.Host = "example.com"
54 req.Header.Set("Host", "example.com")
55 rec := httptest.NewRecorder()
56
57 handler.ServeHTTP(rec, req)
58
59 if matchedRoute != "example.com" {
60 t.Errorf("expected matched route to be 'example.com', got '%s'", matchedRoute)
61 }
62 })
63
64 t.Run("wildcard pattern should match", func(t *testing.T) {
65 var matched bool
66
67 hr := RouteHeaders().

Callers

nothing calls this directly

Calls 9

RouteHeadersFunction · 0.85
HandlerFuncMethod · 0.80
AddMethod · 0.80
RouteDefaultMethod · 0.80
RouteAnyMethod · 0.80
RouteMethod · 0.65
HandlerMethod · 0.45
WriteHeaderMethod · 0.45
ServeHTTPMethod · 0.45

Tested by

no test coverage detected