How Can I Share Data Between Middleware and Handlers in Go?

Barbara Streisand
Release: 2024-11-17 09:03:03
Original
899 people have browsed it

How Can I Share Data Between Middleware and Handlers in Go?

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
    })
}
Copy after login

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!

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