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:
Please help to explain.
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.
You can just use WithTimeout()
, instead of using both APIs, because WithTimeout()
returns you a context.CancelFunc
just as WithCancel()
does, which could be called at any time to cancel the target process/routine. Of course, the cancellation should before hitting the deadline set by WithTimeout()
.
So,
Is it a proper way to use these two APIs together like this?
Is it even necessary to use these two APIs together?
No, no need to use both, use returned context.CancelFunc
by any API in package context.