1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
33 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
34 w.Header().Set("Last-Modified", "sometime")
35 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
38 // pedanticReadAll works like ioutil.ReadAll but additionally
39 // verifies that r obeys the documented io.Reader contract.
40 func pedanticReadAll(r io.Reader) (b []byte, err error) {
45 if n == 0 && err == nil {
46 return nil, fmt.Errorf("Read: n=0 with err=nil")
48 b = append(b, buf[:n]...)
51 if n != 0 || err != io.EOF {
52 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
62 type chanWriter chan string
64 func (w chanWriter) Write(p []byte) (n int, err error) {
69 func TestClient(t *testing.T) {
72 ts := httptest.NewServer(robotsTxtHandler)
76 r, err := c.Get(ts.URL)
79 b, err = pedanticReadAll(r.Body)
84 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
85 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
89 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
90 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
92 func testClientHead(t *testing.T, h2 bool) {
94 cst := newClientServerTest(t, h2, robotsTxtHandler)
97 r, err := cst.c.Head(cst.ts.URL)
101 if _, ok := r.Header["Last-Modified"]; !ok {
102 t.Error("Last-Modified header not found.")
106 type recordingTransport struct {
110 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
112 return nil, errors.New("dummy impl")
115 func TestGetRequestFormat(t *testing.T) {
118 tr := &recordingTransport{}
119 client := &Client{Transport: tr}
120 url := "http://dummy.faketld/"
121 client.Get(url) // Note: doesn't hit network
122 if tr.req.Method != "GET" {
123 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
125 if tr.req.URL.String() != url {
126 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
128 if tr.req.Header == nil {
129 t.Errorf("expected non-nil request Header")
133 func TestPostRequestFormat(t *testing.T) {
135 tr := &recordingTransport{}
136 client := &Client{Transport: tr}
138 url := "http://dummy.faketld/"
139 json := `{"key":"value"}`
140 b := strings.NewReader(json)
141 client.Post(url, "application/json", b) // Note: doesn't hit network
143 if tr.req.Method != "POST" {
144 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
146 if tr.req.URL.String() != url {
147 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
149 if tr.req.Header == nil {
150 t.Fatalf("expected non-nil request Header")
153 t.Error("got Close true, want false")
155 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
156 t.Errorf("got ContentLength %d, want %d", g, e)
160 func TestPostFormRequestFormat(t *testing.T) {
162 tr := &recordingTransport{}
163 client := &Client{Transport: tr}
165 urlStr := "http://dummy.faketld/"
166 form := make(url.Values)
167 form.Set("foo", "bar")
168 form.Add("foo", "bar2")
169 form.Set("bar", "baz")
170 client.PostForm(urlStr, form) // Note: doesn't hit network
172 if tr.req.Method != "POST" {
173 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
175 if tr.req.URL.String() != urlStr {
176 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
178 if tr.req.Header == nil {
179 t.Fatalf("expected non-nil request Header")
181 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
182 t.Errorf("got Content-Type %q, want %q", g, e)
185 t.Error("got Close true, want false")
187 // Depending on map iteration, body can be either of these.
188 expectedBody := "foo=bar&foo=bar2&bar=baz"
189 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
190 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
191 t.Errorf("got ContentLength %d, want %d", g, e)
193 bodyb, err := ioutil.ReadAll(tr.req.Body)
195 t.Fatalf("ReadAll on req.Body: %v", err)
197 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
198 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
202 func TestClientRedirects(t *testing.T) {
205 var ts *httptest.Server
206 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
207 n, _ := strconv.Atoi(r.FormValue("n"))
208 // Test Referer header. (7 is arbitrary position to test at)
210 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
211 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
215 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
218 fmt.Fprintf(w, "n=%d", n)
223 _, err := c.Get(ts.URL)
224 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
225 t.Errorf("with default client Get, expected error %q, got %q", e, g)
228 // HEAD request should also have the ability to follow redirects.
229 _, err = c.Head(ts.URL)
230 if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
231 t.Errorf("with default client Head, expected error %q, got %q", e, g)
234 // Do should also follow redirects.
235 greq, _ := NewRequest("GET", ts.URL, nil)
237 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
238 t.Errorf("with default client Do, expected error %q, got %q", e, g)
241 // Requests with an empty Method should also redirect (Issue 12705)
244 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
245 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
249 var lastVia []*Request
251 c.CheckRedirect = func(req *Request, via []*Request) error {
256 res, err := c.Get(ts.URL)
258 t.Fatalf("Get error: %v", err)
261 finalUrl := res.Request.URL.String()
262 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
263 t.Errorf("with custom client, expected error %q, got %q", e, g)
265 if !strings.HasSuffix(finalUrl, "/?n=15") {
266 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
268 if e, g := 15, len(lastVia); e != g {
269 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
272 // Test that Request.Cancel is propagated between requests (Issue 14053)
273 creq, _ := NewRequest("HEAD", ts.URL, nil)
274 cancel := make(chan struct{})
276 if _, err := c.Do(creq); err != nil {
280 t.Fatal("didn't see redirect")
282 if lastReq.Cancel != cancel {
283 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
286 checkErr = errors.New("no redirects allowed")
287 res, err = c.Get(ts.URL)
288 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
289 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
292 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
295 if res.Header.Get("Location") == "" {
296 t.Errorf("no Location header in Response")
300 // Tests that Client redirects' contexts are derived from the original request's context.
301 func TestClientRedirectContext(t *testing.T) {
304 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
305 Redirect(w, r, "/", StatusTemporaryRedirect)
309 ctx, cancel := context.WithCancel(context.Background())
311 c.CheckRedirect = func(req *Request, via []*Request) error {
314 case <-req.Context().Done():
316 case <-time.After(5 * time.Second):
317 return errors.New("redirected request's context never expired after root request canceled")
320 req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
322 ue, ok := err.(*url.Error)
324 t.Fatalf("got error %T; want *url.Error", err)
326 if ue.Err != context.Canceled {
327 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
331 type redirectTest struct {
333 want int // response code
337 func TestPostRedirects(t *testing.T) {
338 postRedirectTests := []redirectTest{
340 {"/?code=301&next=302", 200, "c301"},
341 {"/?code=302&next=302", 200, "c302"},
342 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
343 {"/?code=304", 304, "c304"},
344 {"/?code=305", 305, "c305"},
345 {"/?code=307&next=303,308,302", 200, "c307"},
346 {"/?code=308&next=302,301", 200, "c308"},
347 {"/?code=404", 404, "c404"},
350 wantSegments := []string{
352 `POST /?code=301&next=302 "c301"`,
355 `POST /?code=302&next=302 "c302"`,
358 `POST /?code=303&next=301 "c303wc301"`,
361 `POST /?code=304 "c304"`,
362 `POST /?code=305 "c305"`,
363 `POST /?code=307&next=303,308,302 "c307"`,
364 `POST /?code=303&next=308,302 "c307"`,
365 `GET /?code=308&next=302 ""`,
366 `GET /?code=302 "c307"`,
368 `POST /?code=308&next=302,301 "c308"`,
369 `POST /?code=302&next=301 "c308"`,
372 `POST /?code=404 "c404"`,
374 want := strings.Join(wantSegments, "\n")
375 testRedirectsByMethod(t, "POST", postRedirectTests, want)
378 func TestDeleteRedirects(t *testing.T) {
379 deleteRedirectTests := []redirectTest{
381 {"/?code=301&next=302,308", 200, "c301"},
382 {"/?code=302&next=302", 200, "c302"},
383 {"/?code=303", 200, "c303"},
384 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
385 {"/?code=308&next=307", 200, "c308"},
386 {"/?code=404", 404, "c404"},
389 wantSegments := []string{
391 `DELETE /?code=301&next=302,308 "c301"`,
392 `GET /?code=302&next=308 ""`,
395 `DELETE /?code=302&next=302 "c302"`,
398 `DELETE /?code=303 "c303"`,
400 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
401 `DELETE /?code=301&next=308,303,302,304 "c307"`,
402 `GET /?code=308&next=303,302,304 ""`,
403 `GET /?code=303&next=302,304 "c307"`,
404 `GET /?code=302&next=304 ""`,
406 `DELETE /?code=308&next=307 "c308"`,
407 `DELETE /?code=307 "c308"`,
409 `DELETE /?code=404 "c404"`,
411 want := strings.Join(wantSegments, "\n")
412 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
415 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
421 var ts *httptest.Server
422 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
424 slurp, _ := ioutil.ReadAll(r.Body)
425 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
426 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
427 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
431 urlQuery := r.URL.Query()
432 if v := urlQuery.Get("code"); v != "" {
434 if final := urlQuery.Get("next"); final != "" {
435 splits := strings.Split(final, ",")
436 first, rest := splits[0], splits[1:]
437 location = fmt.Sprintf("%s?code=%s", location, first)
439 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
442 code, _ := strconv.Atoi(v)
444 w.Header().Set("Location", location)
452 for _, tt := range table {
453 content := tt.redirectBody
454 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
455 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
456 res, err := c.Do(req)
461 if res.StatusCode != tt.want {
462 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
469 got = strings.TrimSpace(got)
470 want = strings.TrimSpace(want)
473 got, want, lines := removeCommonLines(got, want)
474 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
478 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
480 nl := strings.IndexByte(a, '\n')
482 return a, b, commonLines
485 if !strings.HasPrefix(b, line) {
486 return a, b, commonLines
494 func TestClientRedirectUseResponse(t *testing.T) {
497 const body = "Hello, world."
498 var ts *httptest.Server
499 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
500 if strings.Contains(r.URL.Path, "/other") {
501 io.WriteString(w, "wrong body")
503 w.Header().Set("Location", ts.URL+"/other")
504 w.WriteHeader(StatusFound)
505 io.WriteString(w, body)
511 c.CheckRedirect = func(req *Request, via []*Request) error {
512 if req.Response == nil {
513 t.Error("expected non-nil Request.Response")
515 return ErrUseLastResponse
517 res, err := c.Get(ts.URL)
521 if res.StatusCode != StatusFound {
522 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
524 defer res.Body.Close()
525 slurp, err := ioutil.ReadAll(res.Body)
529 if string(slurp) != body {
530 t.Errorf("body = %q; want %q", slurp, body)
534 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
535 // have a Location header.
536 func TestClientRedirect308NoLocation(t *testing.T) {
539 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
540 w.Header().Set("Foo", "Bar")
545 res, err := c.Get(ts.URL)
550 if res.StatusCode != 308 {
551 t.Errorf("status = %d; want %d", res.StatusCode, 308)
553 if got := res.Header.Get("Foo"); got != "Bar" {
554 t.Errorf("Foo header = %q; want Bar", got)
558 // Don't follow a 307/308 if we can't resent the request body.
559 func TestClientRedirect308NoGetBody(t *testing.T) {
562 const fakeURL = "https://localhost:1234/" // won't be hit
563 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
564 w.Header().Set("Location", fakeURL)
568 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
573 req.GetBody = nil // so it can't rewind.
574 res, err := c.Do(req)
579 if res.StatusCode != 308 {
580 t.Errorf("status = %d; want %d", res.StatusCode, 308)
582 if got := res.Header.Get("Location"); got != fakeURL {
583 t.Errorf("Location header = %q; want %q", got, fakeURL)
587 var expectedCookies = []*Cookie{
588 {Name: "ChocolateChip", Value: "tasty"},
589 {Name: "First", Value: "Hit"},
590 {Name: "Second", Value: "Hit"},
593 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
594 for _, cookie := range r.Cookies() {
597 if r.URL.Path == "/" {
598 SetCookie(w, expectedCookies[1])
599 Redirect(w, r, "/second", StatusMovedPermanently)
601 SetCookie(w, expectedCookies[2])
602 w.Write([]byte("hello"))
606 func TestClientSendsCookieFromJar(t *testing.T) {
608 tr := &recordingTransport{}
609 client := &Client{Transport: tr}
610 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
611 us := "http://dummy.faketld/"
612 u, _ := url.Parse(us)
613 client.Jar.SetCookies(u, expectedCookies)
615 client.Get(us) // Note: doesn't hit network
616 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
618 client.Head(us) // Note: doesn't hit network
619 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
621 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
622 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
624 client.PostForm(us, url.Values{}) // Note: doesn't hit network
625 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
627 req, _ := NewRequest("GET", us, nil)
628 client.Do(req) // Note: doesn't hit network
629 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
631 req, _ = NewRequest("POST", us, nil)
632 client.Do(req) // Note: doesn't hit network
633 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
636 // Just enough correctness for our redirect tests. Uses the URL.Host as the
637 // scope of all cookies.
638 type TestJar struct {
640 perURL map[string][]*Cookie
643 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
647 j.perURL = make(map[string][]*Cookie)
649 j.perURL[u.Host] = cookies
652 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
655 return j.perURL[u.Host]
658 func TestRedirectCookiesJar(t *testing.T) {
661 var ts *httptest.Server
662 ts = httptest.NewServer(echoCookiesRedirectHandler)
666 u, _ := url.Parse(ts.URL)
667 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
668 resp, err := c.Get(ts.URL)
670 t.Fatalf("Get: %v", err)
673 matchReturnedCookies(t, expectedCookies, resp.Cookies())
676 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
677 if len(given) != len(expected) {
678 t.Logf("Received cookies: %v", given)
679 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
681 for _, ec := range expected {
683 for _, c := range given {
684 if ec.Name == c.Name && ec.Value == c.Value {
690 t.Errorf("Missing cookie %v", ec)
695 func TestJarCalls(t *testing.T) {
697 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
698 pathSuffix := r.RequestURI[1:]
699 if r.RequestURI == "/nosetcookie" {
700 return // don't set cookies for this path
702 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
703 if r.RequestURI == "/" {
704 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
708 jar := new(RecordingJar)
711 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
712 return net.Dial("tcp", ts.Listener.Addr().String())
714 _, err := c.Get("http://firsthost.fake/")
718 _, err = c.Get("http://firsthost.fake/nosetcookie")
722 got := jar.log.String()
723 want := `Cookies("http://firsthost.fake/")
724 SetCookie("http://firsthost.fake/", [name=val])
725 Cookies("http://secondhost.fake/secondpath")
726 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
727 Cookies("http://firsthost.fake/nosetcookie")
730 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
734 // RecordingJar keeps a log of calls made to it, without
735 // tracking any cookies.
736 type RecordingJar struct {
741 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
742 j.logf("SetCookie(%q, %v)\n", u, cookies)
745 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
746 j.logf("Cookies(%q)\n", u)
750 func (j *RecordingJar) logf(format string, args ...interface{}) {
753 fmt.Fprintf(&j.log, format, args...)
756 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
757 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
759 func testStreamingGet(t *testing.T, h2 bool) {
761 say := make(chan string)
762 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
764 for str := range say {
772 res, err := c.Get(cst.ts.URL)
777 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
779 n, err := io.ReadFull(res.Body, buf[0:len(str)])
781 t.Fatalf("ReadFull on %q: %v", str, err)
784 t.Fatalf("Receiving %q, only read %d bytes", str, n)
786 got := string(buf[0:n])
788 t.Fatalf("Expected %q, got %q", str, got)
792 _, err = io.ReadFull(res.Body, buf[0:1])
794 t.Fatalf("at end expected EOF, got %v", err)
798 type writeCountingConn struct {
803 func (c *writeCountingConn) Write(p []byte) (int, error) {
805 return c.Conn.Write(p)
808 // TestClientWrites verifies that client requests are buffered and we
809 // don't send a TCP packet per line of the http request + body.
810 func TestClientWrites(t *testing.T) {
812 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
817 dialer := func(netz string, addr string) (net.Conn, error) {
818 c, err := net.Dial(netz, addr)
820 c = &writeCountingConn{c, &writes}
825 c.Transport.(*Transport).Dial = dialer
827 _, err := c.Get(ts.URL)
832 t.Errorf("Get request did %d Write calls, want 1", writes)
836 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
841 t.Errorf("Post request did %d Write calls, want 1", writes)
845 func TestClientInsecureTransport(t *testing.T) {
848 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
849 w.Write([]byte("Hello"))
851 errc := make(chanWriter, 10) // but only expecting 1
852 ts.Config.ErrorLog = log.New(errc, "", 0)
855 // TODO(bradfitz): add tests for skipping hostname checks too?
856 // would require a new cert for testing, and probably
857 // redundant with these tests.
859 for _, insecure := range []bool{true, false} {
860 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
861 InsecureSkipVerify: insecure,
863 res, err := c.Get(ts.URL)
864 if (err == nil) != insecure {
865 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
874 if !strings.Contains(v, "TLS handshake error") {
875 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
877 case <-time.After(5 * time.Second):
878 t.Errorf("timeout waiting for logged error")
883 func TestClientErrorWithRequestURI(t *testing.T) {
885 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
886 req.RequestURI = "/this/field/is/illegal/and/should/error/"
887 _, err := DefaultClient.Do(req)
889 t.Fatalf("expected an error")
891 if !strings.Contains(err.Error(), "RequestURI") {
892 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
896 func TestClientWithCorrectTLSServerName(t *testing.T) {
899 const serverName = "example.com"
900 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
901 if r.TLS.ServerName != serverName {
902 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
908 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
909 if _, err := c.Get(ts.URL); err != nil {
910 t.Fatalf("expected successful TLS connection, got error: %v", err)
914 func TestClientWithIncorrectTLSServerName(t *testing.T) {
916 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
918 errc := make(chanWriter, 10) // but only expecting 1
919 ts.Config.ErrorLog = log.New(errc, "", 0)
922 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
923 _, err := c.Get(ts.URL)
925 t.Fatalf("expected an error")
927 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
928 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
932 if !strings.Contains(v, "TLS handshake error") {
933 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
935 case <-time.After(5 * time.Second):
936 t.Errorf("timeout waiting for logged error")
940 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
943 // tls.Config.ServerName (non-empty, set to "example.com") takes
944 // precedence over "some-other-host.tld" which previously incorrectly
945 // took precedence. We don't actually connect to (or even resolve)
946 // "some-other-host.tld", though, because of the Transport.Dial hook.
948 // The httptest.Server has a cert with "example.com" as its name.
949 func TestTransportUsesTLSConfigServerName(t *testing.T) {
951 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
952 w.Write([]byte("Hello"))
957 tr := c.Transport.(*Transport)
958 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
959 tr.Dial = func(netw, addr string) (net.Conn, error) {
960 return net.Dial(netw, ts.Listener.Addr().String())
962 res, err := c.Get("https://some-other-host.tld/")
969 func TestResponseSetsTLSConnectionState(t *testing.T) {
971 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
972 w.Write([]byte("Hello"))
977 tr := c.Transport.(*Transport)
978 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
979 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
980 tr.Dial = func(netw, addr string) (net.Conn, error) {
981 return net.Dial(netw, ts.Listener.Addr().String())
983 res, err := c.Get("https://example.com/")
987 defer res.Body.Close()
989 t.Fatal("Response didn't set TLS Connection State.")
991 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
992 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
996 // Check that an HTTPS client can interpret a particular TLS error
997 // to determine that the server is speaking HTTP.
998 // See golang.org/issue/11111.
999 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1001 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1002 ts.Config.ErrorLog = quietLog
1005 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1006 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1007 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1011 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1012 func TestClientHeadContentLength_h1(t *testing.T) {
1013 testClientHeadContentLength(t, h1Mode)
1016 func TestClientHeadContentLength_h2(t *testing.T) {
1017 testClientHeadContentLength(t, h2Mode)
1020 func testClientHeadContentLength(t *testing.T, h2 bool) {
1022 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1023 if v := r.FormValue("cl"); v != "" {
1024 w.Header().Set("Content-Length", v)
1032 {"/?cl=1234", 1234},
1036 for _, tt := range tests {
1037 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1038 res, err := cst.c.Do(req)
1042 if res.ContentLength != tt.want {
1043 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1045 bs, err := ioutil.ReadAll(res.Body)
1050 t.Errorf("Unexpected content: %q", bs)
1055 func TestEmptyPasswordAuth(t *testing.T) {
1059 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1060 auth := r.Header.Get("Authorization")
1061 if strings.HasPrefix(auth, "Basic ") {
1063 decoded, err := base64.StdEncoding.DecodeString(encoded)
1067 expected := gopher + ":"
1068 s := string(decoded)
1070 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1073 t.Errorf("Invalid auth %q", auth)
1077 req, err := NewRequest("GET", ts.URL, nil)
1081 req.URL.User = url.User(gopher)
1083 resp, err := c.Do(req)
1087 defer resp.Body.Close()
1090 func TestBasicAuth(t *testing.T) {
1092 tr := &recordingTransport{}
1093 client := &Client{Transport: tr}
1095 url := "http://My%20User:My%20Pass@dummy.faketld/"
1096 expected := "My User:My Pass"
1099 if tr.req.Method != "GET" {
1100 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1102 if tr.req.URL.String() != url {
1103 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1105 if tr.req.Header == nil {
1106 t.Fatalf("expected non-nil request Header")
1108 auth := tr.req.Header.Get("Authorization")
1109 if strings.HasPrefix(auth, "Basic ") {
1111 decoded, err := base64.StdEncoding.DecodeString(encoded)
1115 s := string(decoded)
1117 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1120 t.Errorf("Invalid auth %q", auth)
1124 func TestBasicAuthHeadersPreserved(t *testing.T) {
1126 tr := &recordingTransport{}
1127 client := &Client{Transport: tr}
1129 // If Authorization header is provided, username in URL should not override it
1130 url := "http://My%20User@dummy.faketld/"
1131 req, err := NewRequest("GET", url, nil)
1135 req.SetBasicAuth("My User", "My Pass")
1136 expected := "My User:My Pass"
1139 if tr.req.Method != "GET" {
1140 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1142 if tr.req.URL.String() != url {
1143 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1145 if tr.req.Header == nil {
1146 t.Fatalf("expected non-nil request Header")
1148 auth := tr.req.Header.Get("Authorization")
1149 if strings.HasPrefix(auth, "Basic ") {
1151 decoded, err := base64.StdEncoding.DecodeString(encoded)
1155 s := string(decoded)
1157 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1160 t.Errorf("Invalid auth %q", auth)
1165 func TestStripPasswordFromError(t *testing.T) {
1166 client := &Client{Transport: &recordingTransport{}}
1167 testCases := []struct {
1173 desc: "Strip password from error message",
1174 in: "http://user:password@dummy.faketld/",
1175 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1178 desc: "Don't Strip password from domain name",
1179 in: "http://user:password@password.faketld/",
1180 out: `Get "http://user:***@password.faketld/": dummy impl`,
1183 desc: "Don't Strip password from path",
1184 in: "http://user:password@dummy.faketld/password",
1185 out: `Get "http://user:***@dummy.faketld/password": dummy impl`,
1188 desc: "Strip escaped password",
1189 in: "http://user:pa%2Fssword@dummy.faketld/",
1190 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1193 for _, tC := range testCases {
1194 t.Run(tC.desc, func(t *testing.T) {
1195 _, err := client.Get(tC.in)
1196 if err.Error() != tC.out {
1197 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1198 tC.in, tC.out, err.Error())
1204 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1205 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1207 func testClientTimeout(t *testing.T, h2 bool) {
1210 testDone := make(chan struct{}) // closed in defer below
1212 sawRoot := make(chan bool, 1)
1213 sawSlow := make(chan bool, 1)
1214 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1215 if r.URL.Path == "/" {
1217 Redirect(w, r, "/slow", StatusFound)
1220 if r.URL.Path == "/slow" {
1222 w.Write([]byte("Hello"))
1229 defer close(testDone) // before cst.close, to unblock /slow handler
1231 // 200ms should be long enough to get a normal request (the /
1232 // handler), but not so long that it makes the test slow.
1233 const timeout = 200 * time.Millisecond
1234 cst.c.Timeout = timeout
1236 res, err := cst.c.Get(cst.ts.URL)
1238 if strings.Contains(err.Error(), "Client.Timeout") {
1239 t.Skipf("host too slow to get fast resource in %v", timeout)
1248 t.Fatal("handler never got / request")
1255 t.Fatal("handler never got /slow request")
1258 errc := make(chan error, 1)
1260 _, err := ioutil.ReadAll(res.Body)
1265 const failTime = 5 * time.Second
1269 t.Fatal("expected error from ReadAll")
1271 ne, ok := err.(net.Error)
1273 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1274 } else if !ne.Timeout() {
1275 t.Errorf("net.Error.Timeout = false; want true")
1277 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1278 t.Errorf("error string = %q; missing timeout substring", got)
1280 case <-time.After(failTime):
1281 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1285 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1286 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1288 // Client.Timeout firing before getting to the body
1289 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1292 donec := make(chan bool, 1)
1293 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1297 // Note that we use a channel send here and not a close.
1298 // The race detector doesn't know that we're waiting for a timeout
1299 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1300 // with us closing it. If we timed out immediately, we could close the testserver
1301 // before we entered the handler. We're not timing out immediately and there's
1302 // no way we would be done before we entered the handler, but the race detector
1303 // doesn't know this, so synchronize explicitly.
1304 defer func() { donec <- true }()
1306 cst.c.Timeout = 5 * time.Millisecond
1307 res, err := cst.c.Get(cst.ts.URL)
1310 t.Fatal("got response from Get; expected error")
1312 if _, ok := err.(*url.Error); !ok {
1313 t.Fatalf("Got error of type %T; want *url.Error", err)
1315 ne, ok := err.(net.Error)
1317 t.Fatalf("Got error of type %T; want some net.Error", err)
1320 t.Error("net.Error.Timeout = false; want true")
1322 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1323 t.Errorf("error string = %q; missing timeout substring", got)
1327 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1329 func TestClientTimeoutCancel(t *testing.T) {
1333 testDone := make(chan struct{})
1334 ctx, cancel := context.WithCancel(context.Background())
1336 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1341 defer close(testDone)
1343 cst.c.Timeout = 1 * time.Hour
1344 req, _ := NewRequest("GET", cst.ts.URL, nil)
1345 req.Cancel = ctx.Done()
1346 res, err := cst.c.Do(req)
1351 _, err = io.Copy(ioutil.Discard, res.Body)
1352 if err != ExportErrRequestCanceled {
1353 t.Fatalf("error = %v; want errRequestCanceled", err)
1357 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1358 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1359 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1362 saw := make(chan string, 2)
1363 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1365 if r.URL.Path == "/" {
1366 Redirect(w, r, "/foo", StatusFound) // which includes a body
1371 res, err := cst.c.Get(cst.ts.URL)
1375 _, err = ioutil.ReadAll(res.Body)
1385 t.Fatal("server didn't see a request")
1390 case second = <-saw:
1392 t.Fatal("server didn't see a second request")
1395 if first != second {
1396 t.Fatal("server saw different client ports before & after the redirect")
1400 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1401 type eofReaderFunc func()
1403 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1408 func TestReferer(t *testing.T) {
1410 lastReq, newReq string // from -> to URLs
1414 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1415 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1417 // don't send a user and password:
1418 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1419 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1422 {"http://test.com", "http://link.com", "http://test.com"},
1423 {"https://test.com", "https://link.com", "https://test.com"},
1425 // https to http doesn't send a referer:
1426 {"https://test.com", "http://link.com", ""},
1427 {"https://gopher:go@test.com", "http://link.com", ""},
1429 for _, tt := range tests {
1430 l, err := url.Parse(tt.lastReq)
1434 n, err := url.Parse(tt.newReq)
1438 r := ExportRefererForURL(l, n)
1440 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1445 // issue15577Tripper returns a Response with a redirect response
1446 // header and doesn't populate its Response.Request field.
1447 type issue15577Tripper struct{}
1449 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1452 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1453 Body: ioutil.NopCloser(strings.NewReader("")),
1458 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1459 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1461 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1462 Transport: issue15577Tripper{},
1464 // Check that this doesn't crash:
1465 c.Get("http://dummy.tld")
1468 // Issue 4800: copy (some) headers when Client follows a redirect.
1469 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1471 ua = "some-agent/1.2"
1475 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1477 "User-Agent": []string{ua},
1478 "X-Foo": []string{xfoo},
1479 "Referer": []string{ts2URL},
1480 "Accept-Encoding": []string{"gzip"},
1482 if !reflect.DeepEqual(r.Header, want) {
1483 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1486 w.Header().Set("Result", "got errors")
1488 w.Header().Set("Result", "ok")
1492 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1493 Redirect(w, r, ts1.URL, StatusFound)
1499 c.CheckRedirect = func(r *Request, via []*Request) error {
1501 "User-Agent": []string{ua},
1502 "X-Foo": []string{xfoo},
1503 "Referer": []string{ts2URL},
1505 if !reflect.DeepEqual(r.Header, want) {
1506 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1511 req, _ := NewRequest("GET", ts2.URL, nil)
1512 req.Header.Add("User-Agent", ua)
1513 req.Header.Add("X-Foo", xfoo)
1514 req.Header.Add("Cookie", "foo=bar")
1515 req.Header.Add("Authorization", "secretpassword")
1516 res, err := c.Do(req)
1520 defer res.Body.Close()
1521 if res.StatusCode != 200 {
1524 if got := res.Header.Get("Result"); got != "ok" {
1525 t.Errorf("result = %q; want ok", got)
1529 // Issue 22233: copy host when Client follows a relative redirect.
1530 func TestClientCopyHostOnRedirect(t *testing.T) {
1531 // Virtual hostname: should not receive any request.
1532 virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1533 t.Errorf("Virtual host received request %v", r.URL)
1535 io.WriteString(w, "should not see this response")
1537 defer virtual.Close()
1538 virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1539 t.Logf("Virtual host is %v", virtualHost)
1541 // Actual hostname: should not receive any request.
1542 const wantBody = "response body"
1545 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1548 // Relative redirect.
1549 if r.Host != virtualHost {
1550 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1554 w.Header().Set("Location", "/hop")
1557 // Absolute redirect.
1558 if r.Host != virtualHost {
1559 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1563 w.Header().Set("Location", tsURL+"/final")
1566 if r.Host != tsHost {
1567 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1572 io.WriteString(w, wantBody)
1574 t.Errorf("Serving unexpected path %q", r.URL.Path)
1580 tsHost = strings.TrimPrefix(ts.URL, "http://")
1581 t.Logf("Server host is %v", tsHost)
1584 req, _ := NewRequest("GET", ts.URL, nil)
1585 req.Host = virtualHost
1586 resp, err := c.Do(req)
1590 defer resp.Body.Close()
1591 if resp.StatusCode != 200 {
1592 t.Fatal(resp.Status)
1594 if got, err := ioutil.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1595 t.Errorf("body = %q; want %q", got, wantBody)
1599 // Issue 17494: cookies should be altered when Client follows redirects.
1600 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1601 cookieMap := func(cs []*Cookie) map[string][]string {
1602 m := make(map[string][]string)
1603 for _, c := range cs {
1604 m[c.Name] = append(m[c.Name], c.Value)
1609 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1610 var want map[string][]string
1611 got := cookieMap(r.Cookies())
1613 c, _ := r.Cookie("Cycle")
1616 want = map[string][]string{
1617 "Cookie1": {"OldValue1a", "OldValue1b"},
1618 "Cookie2": {"OldValue2"},
1619 "Cookie3": {"OldValue3a", "OldValue3b"},
1620 "Cookie4": {"OldValue4"},
1623 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1624 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1625 Redirect(w, r, "/", StatusFound)
1627 want = map[string][]string{
1628 "Cookie1": {"OldValue1a", "OldValue1b"},
1629 "Cookie3": {"OldValue3a", "OldValue3b"},
1630 "Cookie4": {"OldValue4"},
1633 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1634 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1635 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1636 Redirect(w, r, "/", StatusFound)
1638 want = map[string][]string{
1639 "Cookie1": {"OldValue1a", "OldValue1b"},
1640 "Cookie3": {"NewValue3"},
1641 "Cookie4": {"NewValue4"},
1644 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1645 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1646 Redirect(w, r, "/", StatusFound)
1648 want = map[string][]string{
1649 "Cookie1": {"OldValue1a", "OldValue1b"},
1650 "Cookie3": {"NewValue3"},
1651 "Cookie4": {"NewValue4"},
1652 "Cookie5": {"NewValue5"},
1655 // Don't redirect to ensure the loop ends.
1657 t.Errorf("unexpected redirect cycle")
1661 if !reflect.DeepEqual(got, want) {
1662 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1667 jar, _ := cookiejar.New(nil)
1671 u, _ := url.Parse(ts.URL)
1672 req, _ := NewRequest("GET", ts.URL, nil)
1673 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1674 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1675 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1676 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1677 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1678 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1679 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1680 res, err := c.Do(req)
1684 defer res.Body.Close()
1685 if res.StatusCode != 200 {
1690 // Part of Issue 4800
1691 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1698 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1699 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1701 // Sensitive headers:
1702 {"cookie", "http://foo.com/", "http://bar.com/", false},
1703 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1704 {"authorization", "http://foo.com/", "http://bar.com/", false},
1705 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1707 // But subdomains should work:
1708 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1709 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1710 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1711 {"www-authenticate", "http://foo.com/", "https://foo.com/", false},
1712 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1713 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1714 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1715 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1716 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false},
1718 for i, tt := range tests {
1719 u0, err := url.Parse(tt.initialURL)
1721 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1724 u1, err := url.Parse(tt.destURL)
1726 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1729 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1731 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1732 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1737 func TestClientRedirectTypes(t *testing.T) {
1741 tests := [...]struct {
1744 wantMethod string // desired subsequent client method
1746 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1747 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1748 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1749 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1750 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1752 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1753 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1754 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1755 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1756 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1758 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1759 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1760 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1761 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1762 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1764 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1765 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1766 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1767 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1768 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1770 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1771 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1772 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1773 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1774 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1776 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1777 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1778 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1779 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1780 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1783 handlerc := make(chan HandlerFunc, 1)
1785 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1792 for i, tt := range tests {
1793 handlerc <- func(w ResponseWriter, r *Request) {
1794 w.Header().Set("Location", ts.URL)
1795 w.WriteHeader(tt.serverStatus)
1798 req, err := NewRequest(tt.method, ts.URL, nil)
1800 t.Errorf("#%d: NewRequest: %v", i, err)
1804 c.CheckRedirect = func(req *Request, via []*Request) error {
1805 if got, want := req.Method, tt.wantMethod; got != want {
1806 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1808 handlerc <- func(rw ResponseWriter, req *Request) {
1809 // TODO: Check that the body is valid when we do 307 and 308 support
1814 res, err := c.Do(req)
1816 t.Errorf("#%d: Response: %v", i, err)
1824 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1825 // Its Read returns readErr and increments *readCalls atomically.
1826 // Its Close returns nil and increments *closeCalls atomically.
1827 type issue18239Body struct {
1833 func (b issue18239Body) Read([]byte) (int, error) {
1834 atomic.AddInt32(b.readCalls, 1)
1838 func (b issue18239Body) Close() error {
1839 atomic.AddInt32(b.closeCalls, 1)
1843 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1844 // if Request.GetBody is not defined.
1845 func TestTransportBodyReadError(t *testing.T) {
1848 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1849 if r.URL.Path == "/ping" {
1852 buf := make([]byte, 1)
1853 n, err := r.Body.Read(buf)
1854 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1858 tr := c.Transport.(*Transport)
1860 // Do one initial successful request to create an idle TCP connection
1861 // for the subsequent request to reuse. (The Transport only retries
1862 // requests on reused connections.)
1863 res, err := c.Get(ts.URL + "/ping")
1869 var readCallsAtomic int32
1870 var closeCallsAtomic int32 // atomic
1871 someErr := errors.New("some body read error")
1872 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1874 req, err := NewRequest("POST", ts.URL, body)
1879 _, err = tr.RoundTrip(req)
1881 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1884 // And verify that our Body wasn't used multiple times, which
1885 // would indicate retries. (as it buggily was during part of
1886 // Go 1.8's dev cycle)
1887 readCalls := atomic.LoadInt32(&readCallsAtomic)
1888 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1890 t.Errorf("read calls = %d; want 1", readCalls)
1892 if closeCalls != 1 {
1893 t.Errorf("close calls = %d; want 1", closeCalls)
1897 type roundTripperWithoutCloseIdle struct{}
1899 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1901 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1903 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1904 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
1906 func TestClientCloseIdleConnections(t *testing.T) {
1907 c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1908 c.CloseIdleConnections() // verify we don't crash at least
1911 var tr RoundTripper = roundTripperWithCloseIdle(func() {
1914 c = &Client{Transport: tr}
1915 c.CloseIdleConnections()
1917 t.Error("not closed")
1921 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1922 errDial := errors.New("not actually dialing")
1924 Timeout: 5 * time.Second,
1925 Transport: &Transport{
1926 DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1927 deadline, ok := ctx.Deadline()
1929 t.Error("no deadline")
1931 t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1937 c.Get("https://example.tld/")
1940 func TestClientDoCanceledVsTimeout_h1(t *testing.T) {
1941 testClientDoCanceledVsTimeout(t, h1Mode)
1944 func TestClientDoCanceledVsTimeout_h2(t *testing.T) {
1945 testClientDoCanceledVsTimeout(t, h2Mode)
1948 // Issue 33545: lock-in the behavior promised by Client.Do's
1949 // docs about request cancelation vs timing out.
1950 func testClientDoCanceledVsTimeout(t *testing.T, h2 bool) {
1952 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1953 w.Write([]byte("Hello, World!"))
1957 cases := []string{"timeout", "canceled"}
1959 for _, name := range cases {
1960 t.Run(name, func(t *testing.T) {
1961 var ctx context.Context
1963 if name == "timeout" {
1964 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
1966 ctx, cancel = context.WithCancel(context.Background())
1971 req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
1972 _, err := cst.c.Do(req)
1974 t.Fatal("Unexpectedly got a nil error")
1977 ue := err.(*url.Error)
1979 var wantIsTimeout bool
1980 var wantErr error = context.Canceled
1981 if name == "timeout" {
1982 wantErr = context.DeadlineExceeded
1983 wantIsTimeout = true
1985 if g, w := ue.Timeout(), wantIsTimeout; g != w {
1986 t.Fatalf("url.Timeout() = %t, want %t", g, w)
1988 if g, w := ue.Err, wantErr; g != w {
1989 t.Errorf("url.Error.Err = %v; want %v", g, w)
1995 type nilBodyRoundTripper struct{}
1997 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
1999 StatusCode: StatusOK,
2000 Status: StatusText(StatusOK),
2006 func TestClientPopulatesNilResponseBody(t *testing.T) {
2007 c := &Client{Transport: nilBodyRoundTripper{}}
2009 resp, err := c.Get("http://localhost/anything")
2011 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2014 if resp.Body == nil {
2015 t.Fatalf("Client failed to provide a non-nil Body as documented")
2018 if err := resp.Body.Close(); err != nil {
2019 t.Fatalf("error from Close on substitute Response.Body: %v", err)
2023 if b, err := ioutil.ReadAll(resp.Body); err != nil {
2024 t.Errorf("read error from substitute Response.Body: %v", err)
2025 } else if len(b) != 0 {
2026 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)