我的基础 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/