How to Share Data Between Middleware and Handlers
Your handlers return HTTP handlers, and your middleware accepts HTTP handlers and calls them after performing its operations. To pass data from the middleware to the handlers, you can leverage the context package.
import ( "context" "github.com/gorilla/mux" ) func Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Middleware operations // Parse body/get token. token := parseToken(r) ctx := context.WithValue(r.Context(), "token", token) next.ServeHTTP(w, r.WithContext(ctx)) }) } func Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := r.Context().Value("token") // Continue with handler logic }) }
This approach avoids parsing the JWT in both the middleware and handler, ensuring efficient use of resources. Note that you can pass any type of data by changing the type of the Value argument in r.Context().Value().
The above is the detailed content of How Can I Share Data Between Middleware and Handlers in Go?. For more information, please follow other related articles on the PHP Chinese website!