Przeglądaj źródła

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 <iant@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Ian Lance Taylor 9 lat temu
rodzic
commit
45b61eaf18
2 zmienionych plików z 13 dodań i 4 usunięć
  1. 11 1
      context/ctxhttp/ctxhttp.go
  2. 2 3
      context/ctxhttp/ctxhttp_test.go

+ 11 - 1
context/ctxhttp/ctxhttp.go

@@ -27,7 +27,17 @@ func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Resp
 	if client == nil {
 	if client == nil {
 		client = http.DefaultClient
 		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.
 // Get issues a GET request via the Do function.

+ 2 - 3
context/ctxhttp/ctxhttp_test.go

@@ -11,7 +11,6 @@ import (
 	"io/ioutil"
 	"io/ioutil"
 	"net/http"
 	"net/http"
 	"net/http/httptest"
 	"net/http/httptest"
-	"strings"
 	"testing"
 	"testing"
 	"time"
 	"time"
 
 
@@ -64,8 +63,8 @@ func TestCancelBeforeHeaders(t *testing.T) {
 		res.Body.Close()
 		res.Body.Close()
 		t.Fatal("Get returned unexpected nil error")
 		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)
 	}
 	}
 }
 }