How to set context value inside http.HandleFunc?

I want to set the context value inside http.HandleFunc. The following approach seems to work.

I'm a little worried about *r = *r.WithContext(ctx).

type contextKey string
var myContext = contextKey("myContext")

func setValue(r *http.Request, val string)  {
  ctx := context.WithValue(r.Context(), myContext, val)
  *r = *r.WithContext(ctx)
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    setValue(r, "foobar")
})

What is the best approach to set a context variable inside http.HandleFunc?

0
source share
1 answer

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)
})
+2
source

Source: https://habr.com/ru/post/1658590/


All Articles