如果你想在HTTP服务器的上下文中添加一组键和值对,然后通过Request上下文获取它们,你可以使用下面的例子。
服务器
type ctxSome int
const CtxSomeKey = ctxSome(iota)
ctx := context.WithValue(context.Background(), CtxSomeKey, "some-value")
srv := &http.Server{
Addr: address,
Handler: handler,
BaseContext: func(listener net.Listener) context.Context {
return ctx
},
}
处理程序
func SomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Context().Value(CtxSomeKey))
// ....
}