Reputation: 11251
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?
Upvotes: 8
Views: 2857
Reputation: 417462
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
Upvotes: 12