如何将数据从中间件传递给处理程序? [英] How can I pass data from middleware to handlers?

查看:58
本文介绍了如何将数据从中间件传递给处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计我的处理程序以返回http.Handler.这是我的处理程序的设计:

I am designing my handlers to return a http.Handler. Here's the design of my handlers:

 func Handler() http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  })
}

我的中间件被设计为接受http.Handler,然后在中间件完成其操作后调用该处理程序.这是我的中间件的设计:

My middleware is designed to accept an http.Handler and then call the handler once the middleware has finished performing its operations. Here's the design of my middleware:

 func Middleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // Middleware operations

    next.ServeHTTP(w, r)
  })
}

考虑到我的中间件和处理程序的设计,将信息从中间件传递到处理程序的正确方法是什么?我试图从中间件传递给处理程序的信息是从请求正文中解析的JSON Web令牌.如果我没有将解析的JWT传递给处理程序,那么我将需要在处理程序中再次解析JWT.在中间件和处理程序中解析JWT的请求正文似乎很浪费.以防万一这些信息是相关的,我将标准的net/http库与大猩猩mux一起使用.

Considering the design of my middleware and handlers, what is the proper way of passing information from the middleware to the handler? The information that I am trying to pass from my middleware to the handlers is a JSON web token parsed from the request body. If I do not pass the parsed JWT to the handler, then I will need to parse the JWT again in my handlers. Parsing the request body for a JWT in both the middleware and handler seems wasteful. Just in case this information is relevant, I am using the standard net/http library with gorilla mux.

推荐答案

由于您已经在使用 Gorilla 查看上下文包.

Since you're already using Gorilla take a look at the 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")
    })
}

这篇关于如何将数据从中间件传递给处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆