The standard way is to use a context of type context.Context
and pass it around to all the functions that need to know when the request is cancelled.
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{}
}
Source and more on https://blog.golang.org/context
Update
As Paulo mentioned, Request.Cancel is now deprecated and the author should pass the context to the request itself(using *Request.WithContext) and use the cancellation channel of the context(to cancel the request).
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())
}
}
http.DefaultTransport
, which has sensible timeouts (andProxyFromEnvironment
) instead of an empty Transport. – Cymric