In http.HandlerFunc
I got this. But my question is: does it make sense to put defer cancel()
after applying the timeout context?
Because the bottom selection will continue to listen until the context is completed. And the delay will be executed after the context is completed. But is that done? :)
// Apply timeout context var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, time.Duration(time.Duration(match_route.timeout) * time.Second)) defer cancel() // <--- does this make sense go func(){ match_route.handler(w, r.WithContext(ctx)) cancel() }() select { case <-ctx.Done(): if ctx.Err() == context.DeadlineExceeded { http.Error(w, "Timeout", http.StatusRequestTimeout) } }
Yes, I think this does make sense, in fact the purpose of using defer cancel()
is to ensure that the cancel function is called to release the context associated with it resource, no matter how the function exits, in your example the cancel()
function is deferred until http.HandlerFunc
completes or when the context completes, so go func ()
is responsible for executing the match_route.handler
function using the provided context, and then calling cancel()
to explicitly cancel the context, and the select
statement is used to wait for the context Complete, if the context is completed because the deadline is exceeded, an error response is returned!
The above is the detailed content of Does this make sense with defer cancel() ?. For more information, please follow other related articles on the PHP Chinese website!