httptest.NewRequest 设置上下文存根

httptest.NewRequest set Context stub

我正在创建一个请求存根,以便将其传递给被测试的函数:

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

问题:我还可以通过向其添加 request-uuid 值来为该请求存根 Context 对象吗?

你有 request,你可以在传递它之前用它做任何你想做的事。

在新上下文中使用 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

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