Home >Backend Development >Golang >How to Pass Context in Golang Requests to Middleware and Handlers?

How to Pass Context in Golang Requests to Middleware and Handlers?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 01:27:03774browse

How to Pass Context in Golang Requests to Middleware and Handlers?

How to Pass Context in Golang Request to Middleware

Understanding Context

Go's context, introduced in version 1.7, is a mechanism for associating metadata with requests. It allows you to pass information between different parts of your code, including middleware and handlers.

Passing Context to Middleware

Your question raises the issue of how to pass the context to both middleware and a handler. To align with the example code you provided, the checkAuth function would represent the middleware, while Handler represents the handler.

To pass the context to the middleware, you would typically use the WithContext method on the request object. For instance:

func checkAuth(authToken string) http.HandlerFunc {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context() // Retrieve the current context from the request

    if r.Header.Get("Auth") != authToken {
      util.SendError(w, "...", http.StatusForbidden, false)
      return
    }

    h := r.Context().Value(key) // Retrieve the handler from context
    h.ServeHTTP(w, r) // Pass the request to the handler
  })
}

Passing Context to Handler

To pass the context to the handler, you would again use the WithContext method on the request object. In the ServeHTTP method of your handler, you can retrieve the context using the Value method:

func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  ctx := r.Context() // Retrieve the context from the request
  
  decoder := json.NewDecoder(r.Body)

  // Decode request / context and get params
  var p params
  err := decoder.Decode(&p)
  if err != nil {
    ...
    return
  }

  // Perform GET request and pass context
  ...

}

Example Usage

Your main function could look like the following:

func main() {
  router := mux.NewRouter()

  // Initialize middleware handlers
  h := Handler{
    ...
  }

  // Pass context to authCheck
  authToken, ok := getAuthToken()
  if !ok {
    panic("...")
  }
  authCheck := checkAuth(authToken)

  // Chain middleware handlers and pass context
  router.Handle("/hello", util.UseMiddleware(authCheck, h, ...))
}

Remember, context should only be used for passing transient information. For more persistent data, use a database or other storage mechanism.

The above is the detailed content of How to Pass Context in Golang Requests to Middleware and Handlers?. 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