Home >Backend Development >Golang >How to Properly Set Context Values Within an `http.HandleFunc`?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-15 19:39:031006browse

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))
}

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 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!

Statement:
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