Home >Backend Development >Golang >How Can I Pass Data from Middleware to Handlers in Golang?

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

DDD
DDDOriginal
2024-11-10 09:50:02655browse

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")
    })
}

The above is the detailed content of How Can I Pass Data from Middleware to Handlers in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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