Answer the question
In order to leave comments, you need to log in
Why doesn't context work?
Always outputs nil
func test(r *http.Request) error {
ctx := (*r).Context()
ctx = context.WithValue(ctx, "test", 111)
r = (*r).WithContext(ctx)
return nil
}
func (c Controller) Index(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Context().Value("test"))
_ = test(r)
fmt.Println(r.Context().Value("test"))
_ = test(r)
}
Answer the question
In order to leave comments, you need to log in
r = (*r).WithContext(ctx)
This returns a copy of the Request, which is not propagated any further. It contains your context with the key "test".
Why are you denaming links (*r)
. The methods in the net/http and context packages are defined on pointers, which is how they should be used. Just try
func test(r *http.Request) error {
ctx := r.Context() //здесь
ctx = context.WithValue(ctx, "test", 111)
r = r.WithContext(ctx) //и здесь
return nil
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question