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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用