gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:44:51 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com