httptest.NewRequest设置上下文存根

问题描述:

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?

我正在创建一个请求存根,以便将其传递给经过测试的功能: p> \ n

  request:= httptest.NewRequest(“ GET”,“ http://example.com/foo”,nil)
  code>  pre> 
 
 

问题 strong>:我是否还可以通过向其添加 request-uuid code>值来为此请求的 Context code>对象存根? p> div>

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