doudang4857 2018-08-07 10:15
浏览 110
已采纳

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?

  • 写回答

1条回答 默认 最新

  • drgwsx8405 2018-08-07 10:19
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料