Checking for Request Cancellation in Go
In Go, checking if a request was cancelled is essential for handling asynchronous operations gracefully. A simple solution is to monitor the request's context, which houses cancellation signals.
Consider the following code:
package main import ( "context" "log" "net/http" ) func main() { r, _ := http.NewRequest("GET", "http://example.com", nil) ctx, cancel := context.WithCancel(context.Background()) r = r.WithContext(ctx) ch := make(chan bool) go func() { _, err := http.DefaultClient.Do(r) log.Println(err == context.Canceled) ch <- true }() cancel() <-ch }
This code attempts to determine request cancellation by comparing the error returned by Do() with context.Canceled. However, in Go 1.9, it surprisingly prints false instead of true.
Correct Approach
For Go versions prior to 1.13, the appropriate way to check for cancellation is to use context.Err() and compare its return value with context.Canceled:
if r.Context().Err() == context.Canceled { // Request was cancelled }
Go 1.13
In Go 1.13 and later, checking for cancellation became even more convenient with the introduction of the errors.Is() function. This function allows you to check if an error matches another error type, even if it's wrapped in multiple layers:
if errors.Is(err, context.Canceled) { // Request was cancelled }
This method ensures accurate cancellation detection even when other errors are wrapped around context.Canceled.
The above is the detailed content of How to Check for Request Cancellation in Go?. For more information, please follow other related articles on the PHP Chinese website!