doulianglou0898 2018-11-13 17:34
浏览 36
已采纳

如何获得入站请求结束后可以使用的上下文?

From the documentation of func (r *Request) Context() context.Context in the net/http package:

For incoming server requests, the context is canceled when the client's connection closes, the request is canceled (with HTTP/2), or when the ServeHTTP method returns.

What is the correct thing to do if I want to complete work related to the request after the ServeHTTP method has returned, for example emitting notifications? I'd like to preserve the context chain in terms of values but simply passing the context originally returned by the above method to the message queue submission API doesn't work as the context may be cancelled before it completes.

Is there an easy way to derive just the values in a context chain without deadline or cancellation? I can manually copy values I have the keys for, but other things that rely on context continuity, like trace, will be absent.

Thanks in advance for any answers.

  • 写回答

1条回答 默认 最新

  • dongya3627 2018-11-13 17:48
    关注

    Is there an easy way to derive just the values?

    Out of the box, no. There are two possibilities I can imagine:

    1. You could make a custom context, that swallows/ignores cancellations. Such a type would need a custom implementation of Done() and Err(), which detected a timeout/cancellation, and ignored it.

      This approach has a possible drawback, that you may be referencing values which are expected to go out of scope at the end of a request. This could lead to race conditions or other data integrity issues.

      I would advise against this method, although it's probably the closest to what you're asking for. Contexts should be used primarily for cancellation, so heavy use of values in context is an anti-pattern.

    2. Probably the safer and easier solution, to which you eluded in your question, would be to explicitly copy any values you still care about to a new context created with context.Background().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)