Setting Context Values within HTTP Handlers
Context values provide a convenient way to pass data between handlers in a HTTP application. This Q&A demonstrates the best practice for setting context values within an http.HandleFunc.
Question:
How to effectively set a context value inside an http.HandleFunc?
Answer:
The approach presented in the question, which involves overwriting the request object, is not optimal. Instead, use the Request.WithContext method to create a shallow copy of the request and set the context value in the new copy. Return a pointer to this shallow copy.
Code:
func setValue(r *http.Request, val string) *http.Request { return r.WithContext(context.WithValue(r.Context(), myContext, val)) }
Handler Invocation:
When invoking another handler, pass the modified request along:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { r = setValue(r, "foobar") anotherHandler.ServeHTTP(w, r) })
This approach ensures that:
The above is the detailed content of How to Properly Set Context Values Within an `http.HandleFunc`?. For more information, please follow other related articles on the PHP Chinese website!