Skip to content

Commit

Permalink
context/ctxhttp: if context is canceled, return its error
Browse files Browse the repository at this point in the history
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 <iant@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
  • Loading branch information
ianlancetaylor authored and bradfitz committed Jul 16, 2016
1 parent e90d6d0 commit 45b61ea
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
12 changes: 11 additions & 1 deletion context/ctxhttp/ctxhttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 2 additions & 3 deletions context/ctxhttp/ctxhttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -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)
}
}

Expand Down

0 comments on commit 45b61ea

Please sign in to comment.