author | Ian Lance Taylor
<iant@golang.org> 2016-07-15 22:37:43 UTC |
committer | Brad Fitzpatrick
<bradfitz@golang.org> 2016-07-16 21:44:27 UTC |
parent | e90d6d0afc4c315a0d87a568ae68577cc15149a0 |
context/ctxhttp/ctxhttp.go | +11 | -1 |
context/ctxhttp/ctxhttp_test.go | +2 | -3 |
diff --git a/context/ctxhttp/ctxhttp.go b/context/ctxhttp/ctxhttp.go index aa288de..606cf1f 100644 --- a/context/ctxhttp/ctxhttp.go +++ b/context/ctxhttp/ctxhttp.go @@ -27,7 +27,17 @@ func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Resp if client == nil { client = http.DefaultClient } - return client.Do(req.WithContext(ctx)) + resp, err := client.Do(req.WithContext(ctx)) + // If we got an error, and the context has been canceled, + // the context's error is probably more useful. + if err != nil { + select { + case <-ctx.Done(): + err = ctx.Err() + default: + } + } + return resp, err } // Get issues a GET request via the Do function. diff --git a/context/ctxhttp/ctxhttp_test.go b/context/ctxhttp/ctxhttp_test.go index 5cd7550..1e41551 100644 --- a/context/ctxhttp/ctxhttp_test.go +++ b/context/ctxhttp/ctxhttp_test.go @@ -11,7 +11,6 @@ import ( "io/ioutil" "net/http" "net/http/httptest" - "strings" "testing" "time" @@ -64,8 +63,8 @@ func TestCancelBeforeHeaders(t *testing.T) { res.Body.Close() t.Fatal("Get returned unexpected nil error") } - if !strings.Contains(err.Error(), "canceled") { - t.Errorf("err = %v; want something with \"canceled\"", err) + if err != context.Canceled { + t.Errorf("err = %v; want %v", err, context.Canceled) } }