duanlumei5941 2018-06-13 11:22
浏览 427
已采纳

如何一起使用context.WithCancel和context.WithTimeout API,是否有必要?

Now I did something like this:

func contextHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx, cancel := context.WithCancel(r.Context())
        ctx, cancel = context.WithTimeout(ctx, config.EnvConfig.RequestTimeout)

        defer cancel()

        if cn, ok := w.(http.CloseNotifier); ok {
            go func(done <-chan struct{}, closed <-chan bool) {
                select {
                case <-done:
                case <-closed:
                    logger.Debug("message", "client connection has gone away, request will be cancelled")
                    cancel()
                }
            }(ctx.Done(), cn.CloseNotify())
        }

        h.ServeHTTP(w, r.WithContext(ctx))
    })
}

Pls pay attention to these two lines:

ctx, cancel := context.WithCancel(r.Context())
ctx, cancel = context.WithTimeout(ctx, config.EnvConfig.RequestTimeout)

According to my tests: deliberately kill the client request and deliberately make the request exceed the deadline, both are working fine(i mean can receive the cancellation signal and timeout signal as expected), just my concern is: the latter cancel function will override the previous one returned by the context.WithCancel(r.Context()), so:

  1. Is it a proper way to use these two APIs together like this?
  2. Is it even necessary to use these two APIs together?

Please help to explain.

  • 写回答

2条回答 默认 最新

  • douxia2053 2018-06-13 11:38
    关注

    Because the CancelFunc returned from your WithCancel call is being immediately overwritten, this causes a resource (i.e. memory) leak in your program. From the context documentation:

    The WithCancel, WithDeadline, and WithTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the parent's reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child and its children until the parent is canceled or the timer fires.

    Removing the WithCancel context from your code will fix this problem.

    Additionally, cancellation of the HTTP request is managed by the HTTP server, as described in the http.Request.Context method documentation:

    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.

    When the server cancels the request context, all child contexts will be cancelled.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装