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

Method ServeHTTP

mux.go:63–92  ·  mux.go::Mux.ServeHTTP

ServeHTTP is the single method of the http.Handler interface that makes Mux interoperable with the standard library. It uses a sync.Pool to get and reuse routing contexts for each request.

(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

61// Mux interoperable with the standard library. It uses a sync.Pool to get and
62// reuse routing contexts for each request.
63func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
64 // Ensure the mux has some routes defined on the mux
65 if mx.handler == nil {
66 mx.NotFoundHandler().ServeHTTP(w, r)
67 return
68 }
69
70 // Check if a routing context already exists from a parent router.
71 rctx, _ := r.Context().Value(RouteCtxKey).(*Context)
72 if rctx != nil {
73 mx.handler.ServeHTTP(w, r)
74 return
75 }
76
77 // Fetch a RouteContext object from the sync pool, and call the computed
78 // mx.handler that is comprised of mx.middlewares + mx.routeHTTP.
79 // Once the request is finished, reset the routing context and put it back
80 // into the pool for reuse from another request.
81 rctx = mx.pool.Get().(*Context)
82 rctx.Reset()
83 rctx.Routes = mx
84 rctx.parentCtx = r.Context()
85
86 // NOTE: r.WithContext() causes 2 allocations and context.WithValue() causes 1 allocation
87 r = r.WithContext(context.WithValue(r.Context(), RouteCtxKey, rctx))
88
89 // Serve the request and once its done, put the request context back in the sync pool
90 mx.handler.ServeHTTP(w, r)
91 mx.pool.Put(rctx)
92}
93
94// Use appends a middleware handler to the Mux middleware stack.
95//

Callers 15

MountMethod · 0.45
routeHTTPMethod · 0.45
TestMuxBasicFunction · 0.45
TestMuxNestedNotFoundFunction · 0.45
TestMuxWithFunction · 0.45
TestRouterFromMuxWithFunction · 0.45
TestMuxMiddlewareStackFunction · 0.45
TestMuxRouteGroupsFunction · 0.45
bigMuxFunction · 0.45
TestMuxSubroutesFunction · 0.45
TestSingleHandlerFunction · 0.45

Calls 5

NotFoundHandlerMethod · 0.95
ValueMethod · 0.80
GetMethod · 0.65
ResetMethod · 0.65
PutMethod · 0.65

Tested by 15

TestMuxBasicFunction · 0.36
TestMuxNestedNotFoundFunction · 0.36
TestMuxWithFunction · 0.36
TestRouterFromMuxWithFunction · 0.36
TestMuxMiddlewareStackFunction · 0.36
TestMuxRouteGroupsFunction · 0.36
bigMuxFunction · 0.36
TestMuxSubroutesFunction · 0.36
TestSingleHandlerFunction · 0.36
TestNestedGroupsFunction · 0.36