我正在设计我的处理程序以返回 http.Handler。这是我的处理程序的设计:
func Handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
})
}
我的中间件设计为接受一个 http.Handler,然后在中间件完成其操作后调用该处理程序。这是我的中间件的设计:
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 token 。如果我没有将解析的 JWT 传递给处理程序,那么我将需要在我的处理程序中再次解析 JWT。在中间件和处理程序中解析 JWT 的请求正文似乎很浪费。以防万一这些信息是相关的,我将标准的 net/http 库与 gorilla mux 一起使用。
最佳答案
(如果您不想更改方法签名,这很好。)
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")
})
}
更新
Gorilla context
包现在处于维护模式
每个 repo :
Note gorilla/context, having been born well before context.Context existed, does not play well with the shallow copying of the request that http.Request.WithContext (added to net/http Go 1.7 onwards) performs.
Using gorilla/context may lead to memory leaks under those conditions, as the pointers to each http.Request become "islanded" and will not be cleaned up when the response is sent.
You should use the http.Request.Context() feature in Go 1.7.
关于go - 如何将数据从中间件传递到处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31504456/