如何在http.HandleFunc中设置上下文值? [英] How to set context value inside http.HandleFunc?
问题描述
我想在http.HandleFunc中设置一个上下文值。以下方法似乎起作用。
I want to set a context value inside an http.HandleFunc. The following approach seems to work.
虽然我有点担心 * 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")
})
在http.HandleFunc中设置上下文变量的最佳方法是什么?
What's the best approach to set a context variable inside an http.HandleFunc?
推荐答案
问题中的代码覆盖请求对象。这可能导致使用错误的上下文值对代码进行编码。 Request.WithContext创建请求的浅表副本以避免这种情况。
$ b
The code in the question overwrites the request object. This can result in code up the stack using the wrong context value. Request.WithContext creates a shallow copy of the request to avoid this. Return a pointer to that shallow copy.
func setValue(r *http.Request, val string) *http.Requesst {
return r.WithContext(context.WithValue(r.Context(), myContext, val))
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r = setValue(r, "foobar")
})
如果处理程序调用其他处理程序,则将新请求传递给新处理程序:
If then handler invokes some other handler, then pass the new request along to the new handler:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r = setValue(r, "foobar")
someOtherHandler.ServeHTTP(w, r)
})
这篇关于如何在http.HandleFunc中设置上下文值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!