The code in the question overwrites the request object. This can lead to code creation on the stack using the wrong context value. Request.WithContext creates a shallow copy of the request to avoid this. Return the pointer to this small copy.
func setValue(r *http.Request, val string) *http.Requesst {
return r.WithContext(context.WithValue(r.Context(), myContext, val))
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r = setValue(r, "foobar")
})
If then the handler calls some other handler, then pass the new request to the new handler:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r = setValue(r, "foobar")
someOtherHandler.ServeHTTP(w, r)
})
source
share