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)
| 61 | // Mux interoperable with the standard library. It uses a sync.Pool to get and |
| 62 | // reuse routing contexts for each request. |
| 63 | func (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 | // |