How to Properly Set Context Values Within an `http.HandleFunc`?

Barbara Streisand
Release: 2024-11-15 19:39:03
Original
884 people have browsed it

How to Properly Set Context Values Within an `http.HandleFunc`?

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))
}
Copy after login

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)
})
Copy after login

This approach ensures that:

  • The original request is not overwritten, avoiding potential issues with downstream code.
  • The context value is correctly propagated to handlers that are called later.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template