Home > Backend Development > Golang > How to Reliably Check for Request Cancellation in Go?

How to Reliably Check for Request Cancellation in Go?

Susan Sarandon
Release: 2024-11-08 17:29:01
Original
789 people have browsed it

How to Reliably Check for Request Cancellation in Go?

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template