go - negroni 中间件中设置的请求上下文在嵌套的 gorilla 子路由器中丢失

标签 go gorilla negroni

我的基础 main设置:

muxRouter := mux.NewRouter()

v1Router.Router(muxRouter.PathPrefix("/v1").Subrouter())

http.Handle("/", muxRouter)


n := negroni.Classic()
n.Use(negroni.HandlerFunc(apiRouter.Middleware))
n.UseHandler(muxRouter)

s := &http.Server{
    Addr:           ":6060",
    Handler:        n,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
}
log.Fatal(s.ListenAndServe())

apiRouter.Middleware里面我设置了以下上下文:

context.Set(req, helperKeys.DomainName, "some-value")

但是,在v1Router.Router内的一些handlerFunc中当试图 Get上下文的值,结果为 nil:

domain := context.Get(req, helperKeys.DomainName)
fmt.Println("DomainName", domain)

打印:DomainName <nil>

我知道 Set方法是正确的,因为在 apiRouter.Middleware 中设置值后立即获取值将返回正确的字符串值。

最佳答案

我最终使用了 Go 1.7 的内置 Context:

context.Set(req, helperKeys.DomainName, "some-value")

// Replaced with:

ctx := req.Context()
ctx = context.WithValue(ctx, helperKeys.DomainName, "some-value")
req = req.WithContext(ctx)

domain := context.Get(req, helperKeys.DomainName)

// Replaced with:

domain := req.Context().Value(helperKeys.DomainName).(string)

关于go - negroni 中间件中设置的请求上下文在嵌套的 gorilla 子路由器中丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42229594/

相关文章:

json - 我的结构没有编码为 json

mongodb - 我应该保留什么 setLimit(int64) 方法来显示 Collections 中的所有记录

go - 我可以将我的功能用作 `negroni` 中间件吗

go - 为什么我有一个死锁,即使它包含一个无限循环?

go - 如何在 Go 中抽象出相同类型的循环细节?

go - 如何从 gorilla mux.Router过滤一些路径

Golang http mux 更改处理函数

go - 如何为wosagger服务websocket?

go - Negroni 在请求完成后继续调用其他处理程序