如何将上下文键和值添加到HTTP服务器并在Golang的Request context中访问它

174 阅读1分钟

如果你想在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))

	// ....
}