diff --git a/route/route.go b/route/route.go index dbec638e5..742e57547 100644 --- a/route/route.go +++ b/route/route.go @@ -46,6 +46,10 @@ func (r *Router) WithPrefix(prefix string) *Router { // handle turns a HandlerFunc into an httprouter.Handle. func (r *Router) handle(handlerName string, h http.HandlerFunc) httprouter.Handle { + if r.instrh != nil { + // This needs to be outside the closure to avoid data race when reading and writing to 'h'. + h = r.instrh(handlerName, h) + } return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) { ctx, cancel := context.WithCancel(req.Context()) defer cancel() @@ -53,9 +57,6 @@ func (r *Router) handle(handlerName string, h http.HandlerFunc) httprouter.Handl for _, p := range params { ctx = context.WithValue(ctx, param(p.Key), p.Value) } - if r.instrh != nil { - h = r.instrh(handlerName, h) - } h(w, req.WithContext(ctx)) } }