Skip to content

Commit 45b61ea

Browse files
ianlancetaylorbradfitz
authored andcommitted
context/ctxhttp: if context is canceled, return its error
This preserves the promise that Do will return the context's error. Fixes golang/go#16381 Change-Id: I0db49b175736a695199b38819b4ff97b83d9c5ed Reviewed-on: https://go-review.googlesource.com/24977 Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent e90d6d0 commit 45b61ea

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

context/ctxhttp/ctxhttp.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,17 @@ func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Resp
2727
if client == nil {
2828
client = http.DefaultClient
2929
}
30-
return client.Do(req.WithContext(ctx))
30+
resp, err := client.Do(req.WithContext(ctx))
31+
// If we got an error, and the context has been canceled,
32+
// the context's error is probably more useful.
33+
if err != nil {
34+
select {
35+
case <-ctx.Done():
36+
err = ctx.Err()
37+
default:
38+
}
39+
}
40+
return resp, err
3141
}
3242

3343
// Get issues a GET request via the Do function.

context/ctxhttp/ctxhttp_test.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import (
1111
"io/ioutil"
1212
"net/http"
1313
"net/http/httptest"
14-
"strings"
1514
"testing"
1615
"time"
1716

@@ -64,8 +63,8 @@ func TestCancelBeforeHeaders(t *testing.T) {
6463
res.Body.Close()
6564
t.Fatal("Get returned unexpected nil error")
6665
}
67-
if !strings.Contains(err.Error(), "canceled") {
68-
t.Errorf("err = %v; want something with \"canceled\"", err)
66+
if err != context.Canceled {
67+
t.Errorf("err = %v; want %v", err, context.Canceled)
6968
}
7069
}
7170

0 commit comments

Comments
 (0)