I have this simple code in which I try to check if the request was cancelled. But surprisingly, it prints false
instead of true
in go 1.9.
I wonder what's the correct way to check that?
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
}
You can check the context's error:
Prints
The cleanest way to do this in Go 1.13+ is using the new
errors.Is
function.