如何检查请求是否被取消

hgl*_*hgl 5 go

我有这个简单的代码,我尝试检查请求是否被取消.但令人惊讶的是,它打印false而不是true去1.9.

我想知道检查它的正确方法是什么?

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
}
Run Code Online (Sandbox Code Playgroud)

Dir*_*aio 16

在 Go 1.13+ 中最简洁的方法是使用新errors.Is函数。

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

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

// Do it, it will immediately fail because the context is canceled.
_, err := http.DefaultClient.Do(r)
log.Println(err) // Get http://example.com: context canceled

// This prints false, because the http client wraps the context.Canceled
// error into another one with extra information.
log.Println(err == context.Canceled)

// This prints true, because errors.Is checks all the errors in the wrap chain,
// and returns true if any of them matches.
log.Println(errors.Is(err, context.Canceled))
Run Code Online (Sandbox Code Playgroud)


Ain*_*r-G 12

您可以检查上下文的错误:

package main

import (
    "context"
    "fmt"
)

func main() {    
    ctx, cancel := context.WithCancel(context.Background())
    fmt.Println(ctx.Err())
    cancel()
    fmt.Println(ctx.Err())
}
Run Code Online (Sandbox Code Playgroud)

打印

<nil>
context canceled
Run Code Online (Sandbox Code Playgroud)