Passing Context in Middleware and HandlerFunc
In Go, the context package provides functionality for passing information between request handlers. This is particularly useful for middleware, which can perform actions before and after the execution of a handler function.
Creating and Passing Context
In the context of middleware, we can create a new context by calling context.WithValue on the request's context, providing a key and value pair. This new context should then be used when calling the handler's ServeHTTP method.
For instance, in the provided code snippet, the checkAuth middleware function receives the request context and auth token as input. It returns a wrapped handler function that checks the auth token.
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 } h.ServeHTTP(w, r) }) } }
To initialize the context with the auth token, we can call context.WithValue on the request's context, as shown below:
func main() { authToken, ok := getAuthToken() if !ok { panic("...") } ctx := context.WithValue(r.Context(), "auth_token", authToken) router.Handle("/hello", util.UseMiddleware(authCheck, Handler, ...)) }
This new context will then be used when the middleware handler calls the original handler's ServeHTTP method.
Accessing Context in Handlers
The handler can access the context information by calling r.Context(), which returns the current context. The value can be retrieved using the Value method, as shown in the code snippet below:
func (h *HandlerW) ServeHTTP(w http.ResponseWriter, r *http.Request) { authToken := r.Context().Value("auth_token").(string) // ... }
The above is the detailed content of How can I pass and access context information in Go HTTP Handlers and Middleware?. For more information, please follow other related articles on the PHP Chinese website!