Home  >  Article  >  Backend Development  >  How to Check if an HTTP Request Was Cancelled in Go?

How to Check if an HTTP Request Was Cancelled in Go?

DDD
DDDOriginal
2024-11-07 14:54:03334browse

How to Check if an HTTP Request Was Cancelled in Go?

How to Check if a Request Was Cancelled

Context and Cancellation

In Go, contexts provide a mechanism for controlling and cancelling operations. They allow for propagating cancellation signals through goroutines and HTTP requests.

The Problem

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.

Solution

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!

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