Home > Article > Backend Development > How to Pass Data from Middleware to Handlers in Go?
In this scenario, you're using a middleware that parses a JWT from the request body and want to pass it to your handlers to avoid redundant parsing. Since your middleware returns an http.Handler and your handlers also return an http.Handler, it's necessary to find a way to pass the JWT between them.
One recommended approach is to utilize the context package from Gorilla Mux. The context package allows you to store values associated with a request in a type-safe manner.
import ( "github.com/gorilla/context" ) // Middleware serves as a wrapper around the next handler. func Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Middleware operations // Parse body/get token. token, err := getTokenFromRequest(r) if err != nil { http.Error(w, "Error getting token", http.StatusInternalServerError) return } context.Set(r, "token", token) next.ServeHTTP(w, r) }) } // Handler retrieves the JWT from the request context. func Handler() http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := context.Get(r, "token") // Use the token in your handler logic. }) }
By utilizing the context package, you can store the parsed JWT in the request context within the middleware and easily access it within your handlers without the need for re-parsing.
Update:
It's worth noting that the Gorilla context package is now in maintenance mode. For new projects, it's recommended to use the context.Context() feature introduced in Go 1.7, which provides a more robust and efficient way of managing request context data.
The above is the detailed content of How to Pass Data from Middleware to Handlers in Go?. For more information, please follow other related articles on the PHP Chinese website!