Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

httptest.NewRequest set Context stub

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?

like image 534
Rudziankoŭ Avatar asked Aug 07 '18 10:08

Rudziankoŭ


1 Answers

You have the request, you can do whatever you want to with it before you pass it along.

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
like image 69
icza Avatar answered Nov 15 '22 07:11

icza