"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Pass Data from Middleware to Handlers in Golang?

How Can I Pass Data from Middleware to Handlers in Golang?

Published on 2024-11-15
Browse:857

How Can I Pass Data from Middleware to Handlers in Golang?

Passing Data from Middleware to Handlers

In your design, you have middleware that processes an incoming request and handlers that return an http.Handler. You want to pass data from the middleware to the handlers, specifically a JSON web token parsed from the request body.

To achieve this, you can utilize Gorilla's context package:

import (
    "github.com/gorilla/context"
)

func Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Middleware operations
        // Parse body/get token.
        context.Set(r, "token", token)

        next.ServeHTTP(w, r)
    })
}

func Handler() http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := context.Get(r, "token")
    })
}

In the middleware, you parse the request body and store the JWT in the request context. Then, in the handler, you can retrieve the JWT from the context:

token := context.Get(r, "token")

This allows you to avoid parsing the JWT again in your handlers, which is more efficient.

Update:

The Gorilla context package is currently in maintenance mode.

func Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Middleware operations
        // Parse body/get token.
        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")
    })
}
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3