标准方法是使用context.Context 类型的上下文,并将其传递给所有需要知道何时取消请求的函数。
func httpDo(ctx context.Context, req *http.Request, f func(*http.Response, error) error) error {
// Run the HTTP request in a goroutine and pass the response to f.
tr := &http.Transport{}
client := &http.Client{Transport: tr}
c := make(chan error, 1)
go func() { c <- f(client.Do(req)) }()
select {
case <-ctx.Done():
tr.CancelRequest(req)
<-c // Wait for f to return.
return ctx.Err()
case err := <-c:
return err
}
}
golang.org/x/net/context
// A Context carries a deadline, cancelation signal, and request-scoped values
// across API boundaries. Its methods are safe for simultaneous use by multiple
// goroutines.
type Context interface {
// Done returns a channel that is closed when this Context is canceled
// or times out.
Done() <-chan struct{}
// Err indicates why this context was canceled, after the Done channel
// is closed.
Err() error
// Deadline returns the time when this Context will be canceled, if any.
Deadline() (deadline time.Time, ok bool)
// Value returns the value associated with key or nil if none.
Value(key interface{}) interface{}
}
来源和更多信息https://blog.golang.org/context
更新
正如 Paulo mentioned,Request.Cancel 现在已弃用,作者应将上下文传递给请求本身(使用 *Request.WithContext)并使用上下文的取消通道(取消请求)。
package main
import (
"context"
"net/http"
"time"
)
func main() {
cx, cancel := context.WithCancel(context.Background())
req, _ := http.NewRequest("GET", "http://google.com", nil)
req = req.WithContext(cx)
ch := make(chan error)
go func() {
_, err := http.DefaultClient.Do(req)
select {
case <-cx.Done():
// Already timedout
default:
ch <- err
}
}()
// Simulating user cancel request
go func() {
time.Sleep(100 * time.Millisecond)
cancel()
}()
select {
case err := <-ch:
if err != nil {
// HTTP error
panic(err)
}
print("no error")
case <-cx.Done():
panic(cx.Err())
}
}