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

DDD
Release: 2024-11-10 09:50:02
Original
580 people have browsed it

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template