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

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

报告相同问题?