我想在 http.HandleFunc 中设置一个上下文值。以下方法似乎有效。
不过我有点担心*r = *r.WithContext(ctx)
。
type contextKey string
var myContext = contextKey("myContext")
func setValue(r *http.Request, val string) {
ctx := context.WithValue(r.Context(), myContext, val)
*r = *r.WithContext(ctx)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
setValue(r, "foobar")
})
Run Code Online (Sandbox Code Playgroud)
在 http.HandleFunc 中设置上下文变量的最佳方法是什么?
go ×1