How to Set Context Value in an http.HandleFunc without Overwriting Request Object
In the provided code, the approach followed in func setValue to set a context value inside *http.Request raises concerns about overwriting the request object. Here's a corrected approach:
func setValue(r *http.Request, val string) *http.Request { ctx := context.WithValue(r.Context(), myContext, val) return r.WithContext(ctx) // return shallow copy to avoid overwriting request object }
When setting the context value within http.HandleFunc, return a pointer to the newly created request with the updated context. By doing this, we avoid modifying the original request object and ensure that subsequent handlers receive the correct context value:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { r = setValue(r, "foobar") })
If the handler invokes another handler, pass along the updated request with the context value to ensure continuity:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { r = setValue(r, "foobar") someOtherHandler.ServeHTTP(w, r) // pass updated request to subsequent handler })
By utilizing this approach, we can effectively set context values within http.HandleFunc without compromising the original request object.
The above is the detailed content of How to Set Context Value in an http.HandleFunc without Overwriting the Request Object?. For more information, please follow other related articles on the PHP Chinese website!