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

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

DDD
Release: 2024-11-07 14:54:03
Original
419 people have browsed it

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template