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

如何一起使用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条)

报告相同问题?

悬赏问题

  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥15 第一个已完成,求第二个做法
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?
  • ¥15 Bioage计算生物学年龄
  • ¥20 如何将FPGA Alveo U50恢复原来出厂设置哇?