如果你必须在单元测试中为你的HTTP处理器设置请求上下文参数,你可以使用下面的简单例子。
测试
handler := your HTTP handler
r := httptest.NewRequest(http.MethodGet, "/api/v1/some/path", nil)
w := httptest.NewRecorder()
ctx := r.Context()
ctx = context.WithValue(ctx, "uuid", "some-uuid")
r = r.WithContext(ctx)
handler.Handle(w, r)
确认
如果你在你的处理程序中使用下面的代码,你会看到some-uuid :
fmt.Println(r.Context().Value("uuid"))