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

How to Check for Request Cancellation in Go?

Mary-Kate Olsen
Release: 2024-11-08 08:55:02
Original
497 people have browsed it

How to Check for Request Cancellation in Go?

Checking for Request Cancellation in Go

In Go, checking if a request was cancelled is essential for handling asynchronous operations gracefully. A simple solution is to monitor the request's context, which houses cancellation signals.

Consider the following code:

package main

import (
    "context"
    "log"
    "net/http"
)

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)
        log.Println(err == context.Canceled)
        ch <- true
    }()
    cancel()
    <-ch
}
Copy after login

This code attempts to determine request cancellation by comparing the error returned by Do() with context.Canceled. However, in Go 1.9, it surprisingly prints false instead of true.

Correct Approach

For Go versions prior to 1.13, the appropriate way to check for cancellation is to use context.Err() and compare its return value with context.Canceled:

if r.Context().Err() == context.Canceled {
    // Request was cancelled
}
Copy after login

Go 1.13

In Go 1.13 and later, checking for cancellation became even more convenient with the introduction of the errors.Is() function. This function allows you to check if an error matches another error type, even if it's wrapped in multiple layers:

if errors.Is(err, context.Canceled) {
    // Request was cancelled
}
Copy after login

This method ensures accurate cancellation detection even when other errors are wrapped around context.Canceled.

The above is the detailed content of How to 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