8

I am creating a request stub in order to pass it to function under the tested:

request := httptest.NewRequest("GET", "http://example.com/foo", nil)

Question: can I also stub Context object for this request by adding request-uuid Value to it?

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192
  • There's no reason to stub it, just use `context.WithValue` to add the value to a real context. – Adrian Aug 07 '18 at 13:16

1 Answers1

11

You have the request, you can do whatever you want to with it before you hand it over.

Use Request.Context() to access its context, use context.WithValue() to derive a new context.Context with your key-value in it, and use Request.WithContext() to acquire a new http.Request with the new context:

request := httptest.NewRequest("GET", "http://example.com/foo", nil)
ctx := request.Context()
ctx = context.WithValue(ctx, "request-uuid", "myvalue")
request = request.WithContext(ctx)

// now request's context contains the "request-uuid" key
icza
  • 389,944
  • 63
  • 907
  • 827