Understanding context in Go can be confusing. Let's explore how to effectively pass context to middleware and handlers.
To pass context to middleware, follow these steps:
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)
To pass context to handlers:
For example, to add the user ID to the context:
ctx := context.WithValue(r.Context(), ContextUserKey, "theuser") h.ServeHTTP(w, r.WithContext(ctx))
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, ...)) }
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!