Home >Backend Development >Golang >How to Detect Request Cancellation in Go?

How to Detect Request Cancellation in Go?

DDD
DDDOriginal
2024-11-07 18:23:02524browse

How to Detect Request Cancellation in Go?

Detecting Request Cancellation in Go

In Go, verifying whether an HTTP request has been cancelled can be done in several ways. The code snippet provided attempts to check cancellation by inspecting the error returned from http.DefaultClient.Do(), but it unexpectedly logs false.

Solution for Go 1.13

For Go versions 1.13 and above, the recommended approach is to leverage the errors.Is function. This function enables you to check if an error matches a specific type, including errors from the context package.

// Create a canceled context
ctx, cancel := context.WithCancel(context.Background())
cancel()

// Create a request with the canceled context
r, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)

// Attempt the request, which will fail immediately due to the canceled context
_, err := http.DefaultClient.Do(r)

// Validate the error's origin using errors.Is
if errors.Is(err, context.Canceled) {
    fmt.Println("Request canceled!")
}

In this case, errors.Is will accurately determine that err originates from the canceled context, thus confirming that the request was indeed cancelled.

Alternative Approach

Prior to Go 1.13, you can utilize a combination of grpc.ErrorDesc and context.Err() to verify cancellation:

// Create a canceled context
ctx, cancel := context.WithCancel(context.Background())
cancel()

// Create a request with the canceled context
r, _ := http.NewRequestWithContext(ctx, "GET", "http://example.com", nil)

// Attempt the request, which will fail immediately due to the canceled context
_, err := http.DefaultClient.Do(r)

// Check for a canceled context error
if grpc.ErrorDesc(err) == context.Canceled {
    fmt.Println("Request canceled!")
}

The above is the detailed content of How to Detect Request Cancellation in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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