From 0d989b642861efa13f082dc4d5370088e739e86a Mon Sep 17 00:00:00 2001 From: Krasi Georgiev Date: Mon, 26 Mar 2018 18:36:27 +0300 Subject: [PATCH] fix data race in Router.handle --- route/route.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) 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)) } }