How to Check for Request Cancellation
In Go, programmers may encounter scenarios where they need to determine if a request has been canceled. However, using the == context.Canceled comparison in Go 1.9 and earlier can yield unexpected results.
To accurately check for request cancellation, consider the following approaches:
1. Utilize the context.Canceled Error Object:
In Go 1.13 and later, the context.Canceled error object provides a convenient way to verify cancellation. When a context is canceled, any operation performed on it will return this error. The following code demonstrates its usage:
// Create a context that is already canceled ctx, cancel := context.WithCancel(context.Background()) cancel() // Create the request with it and perform an operation r, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil) _, err := http.DefaultClient.Do(r) // Check if the error matches context.Canceled if err == context.Canceled { // Request was canceled }
2. Use the errors.Is Function:
If you need to support Go versions before 1.13, you can use the errors.Is function to check for nested context.Canceled errors. errors.Is allows you to inspect the underlying error chain and determine if any of the errors match a specified error type.
// Create a context that is already canceled ctx, cancel := context.WithCancel(context.Background()) cancel() // Create the request with it and perform an operation r, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil) _, err := http.DefaultClient.Do(r) // Check if the error chain contains context.Canceled if errors.Is(err, context.Canceled) { // Request was canceled }
The above is the detailed content of How to Reliably Check for Request Cancellation in Go?. For more information, please follow other related articles on the PHP Chinese website!