Home > Article > Backend Development > How to Check if an HTTP Request Was Cancelled in Go?
In Go, contexts provide a mechanism for controlling and cancelling operations. They allow for propagating cancellation signals through goroutines and HTTP requests.
When using HTTP requests with a context, it's crucial to handle cancellation correctly. In Go 1.9, attempting to check if a request was cancelled using err == context.Canceled may result in incorrect results.
In Go 1.13 :
The preferred way to check for cancellation is to use the new errors.Is function:
ctx, cancel := context.WithCancel(context.Background()) cancel() r, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil) _, err := http.DefaultClient.Do(r) log.Println(errors.Is(err, context.Canceled)) // Prints true
errors.Is checks the error chain and returns true if any error in the chain matches the provided context.Canceled error.
In Go 1.9-1.12:
For earlier versions of Go, you can use the following workaround:
type canceledErr struct { error } func (e *canceledErr) Cancelled() bool { return e.Error() == "context canceled" } 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) ch <- &canceledErr{err} }() cancel() log.Println((<-ch).Cancelled()) // Prints true }
This workaround creates a custom error type canceledErr that embeds the wrapped error and provides a Cancelled() method to check for context cancellation.
The above is the detailed content of How to Check if an HTTP Request Was Cancelled in Go?. For more information, please follow other related articles on the PHP Chinese website!