N
N
NubasLol2019-11-19 16:20:53
go
NubasLol, 2019-11-19 16:20:53

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

2 answer(s)
B
Bynov, 2019-11-19
@NubasLol

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".

U
uvelichitel, 2019-11-19
@uvelichitel

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 question

Ask a Question

731 491 924 answers to any question