How to Properly Pass Context in Middleware and Handlers in Go?

Patricia Arquette
Release: 2024-11-09 06:52:02
Original
699 people have browsed it

How to Properly Pass Context in Middleware and Handlers in Go?

Passing Context in Middleware and Handlers in Go

Introduction

Understanding context in Go can be confusing. Let's explore how to effectively pass context to middleware and handlers.

Passing Context in Middleware

To pass context to middleware, follow these steps:

  1. Derive a new context from the request context using context.WithTimeout() or context.WithValue().
  2. Call ServeHTTP with the updated request, which now contains the new context.
  3. In the authorization checker, add the user's information to the context before calling ServeHTTP.

For example, to add a timeout to the request:

ctx, cancel := context.WithTimeout(r.Context(), time.Duration(60*time.Second))
defer cancel()
r = r.WithContext(ctx)
Copy after login

Passing Context in Handlers

To pass context to handlers:

  1. Use context.WithValue() to add values to the request's context.
  2. In the handler, use request.Context().Value() to access the values.

For example, to add the user ID to the context:

ctx := context.WithValue(r.Context(), ContextUserKey, "theuser")
h.ServeHTTP(w, r.WithContext(ctx))
Copy after login

Example Code

Here's an example implementation of middleware and a handler using context:

func checkAuth(authToken string) util.Middleware {
    return func(h http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            if r.Header.Get("Auth") != authToken {
                util.SendError(w, "...", http.StatusForbidden, false)
                return
            }
            // Add authentication-specific context here
            h.ServeHTTP(w, r)
        })
    }
}

type Handler struct {
    ...
    ...
}

func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // Get context values here
    decoder := json.NewDecoder(r.Body)

    // ...
}

func main() {
    router := mux.NewRouter()
    authToken, ok := getAuthToken()
    if !ok {
        panic("...")
    }
    authCheck := checkAuth(authToken)
    h := Handler{
       ...
   } 
   router.Handle("/hello", util.UseMiddleware(authCheck, Handler, ...))
}
Copy after login

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