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.
32 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
33 w.Header().Set("Last-Modified", "sometime")
34 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
37 // pedanticReadAll works like io.ReadAll but additionally
38 // verifies that r obeys the documented io.Reader contract.
39 func pedanticReadAll(r io.Reader) (b []byte, err error) {
44 if n == 0 && err == nil {
45 return nil, fmt.Errorf("Read: n=0 with err=nil")
47 b = append(b, buf[:n]...)
50 if n != 0 || err != io.EOF {
51 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
61 type chanWriter chan string
63 func (w chanWriter) Write(p []byte) (n int, err error) {
68 func TestClient(t *testing.T) {
71 ts := httptest.NewServer(robotsTxtHandler)
75 r, err := c.Get(ts.URL)
78 b, err = pedanticReadAll(r.Body)
83 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
84 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
88 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
89 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
91 func testClientHead(t *testing.T, h2 bool) {
93 cst := newClientServerTest(t, h2, robotsTxtHandler)
96 r, err := cst.c.Head(cst.ts.URL)
100 if _, ok := r.Header["Last-Modified"]; !ok {
101 t.Error("Last-Modified header not found.")
105 type recordingTransport struct {
109 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
111 return nil, errors.New("dummy impl")
114 func TestGetRequestFormat(t *testing.T) {
117 tr := &recordingTransport{}
118 client := &Client{Transport: tr}
119 url := "http://dummy.faketld/"
120 client.Get(url) // Note: doesn't hit network
121 if tr.req.Method != "GET" {
122 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
124 if tr.req.URL.String() != url {
125 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
127 if tr.req.Header == nil {
128 t.Errorf("expected non-nil request Header")
132 func TestPostRequestFormat(t *testing.T) {
134 tr := &recordingTransport{}
135 client := &Client{Transport: tr}
137 url := "http://dummy.faketld/"
138 json := `{"key":"value"}`
139 b := strings.NewReader(json)
140 client.Post(url, "application/json", b) // Note: doesn't hit network
142 if tr.req.Method != "POST" {
143 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
145 if tr.req.URL.String() != url {
146 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
148 if tr.req.Header == nil {
149 t.Fatalf("expected non-nil request Header")
152 t.Error("got Close true, want false")
154 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
155 t.Errorf("got ContentLength %d, want %d", g, e)
159 func TestPostFormRequestFormat(t *testing.T) {
161 tr := &recordingTransport{}
162 client := &Client{Transport: tr}
164 urlStr := "http://dummy.faketld/"
165 form := make(url.Values)
166 form.Set("foo", "bar")
167 form.Add("foo", "bar2")
168 form.Set("bar", "baz")
169 client.PostForm(urlStr, form) // Note: doesn't hit network
171 if tr.req.Method != "POST" {
172 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
174 if tr.req.URL.String() != urlStr {
175 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
177 if tr.req.Header == nil {
178 t.Fatalf("expected non-nil request Header")
180 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
181 t.Errorf("got Content-Type %q, want %q", g, e)
184 t.Error("got Close true, want false")
186 // Depending on map iteration, body can be either of these.
187 expectedBody := "foo=bar&foo=bar2&bar=baz"
188 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
189 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
190 t.Errorf("got ContentLength %d, want %d", g, e)
192 bodyb, err := io.ReadAll(tr.req.Body)
194 t.Fatalf("ReadAll on req.Body: %v", err)
196 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
197 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
201 func TestClientRedirects(t *testing.T) {
204 var ts *httptest.Server
205 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
206 n, _ := strconv.Atoi(r.FormValue("n"))
207 // Test Referer header. (7 is arbitrary position to test at)
209 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
210 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
214 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
217 fmt.Fprintf(w, "n=%d", n)
222 _, err := c.Get(ts.URL)
223 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
224 t.Errorf("with default client Get, expected error %q, got %q", e, g)
227 // HEAD request should also have the ability to follow redirects.
228 _, err = c.Head(ts.URL)
229 if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
230 t.Errorf("with default client Head, expected error %q, got %q", e, g)
233 // Do should also follow redirects.
234 greq, _ := NewRequest("GET", ts.URL, nil)
236 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
237 t.Errorf("with default client Do, expected error %q, got %q", e, g)
240 // Requests with an empty Method should also redirect (Issue 12705)
243 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
244 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
248 var lastVia []*Request
250 c.CheckRedirect = func(req *Request, via []*Request) error {
255 res, err := c.Get(ts.URL)
257 t.Fatalf("Get error: %v", err)
260 finalURL := res.Request.URL.String()
261 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
262 t.Errorf("with custom client, expected error %q, got %q", e, g)
264 if !strings.HasSuffix(finalURL, "/?n=15") {
265 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
267 if e, g := 15, len(lastVia); e != g {
268 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
271 // Test that Request.Cancel is propagated between requests (Issue 14053)
272 creq, _ := NewRequest("HEAD", ts.URL, nil)
273 cancel := make(chan struct{})
275 if _, err := c.Do(creq); err != nil {
279 t.Fatal("didn't see redirect")
281 if lastReq.Cancel != cancel {
282 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
285 checkErr = errors.New("no redirects allowed")
286 res, err = c.Get(ts.URL)
287 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
288 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
291 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
294 if res.Header.Get("Location") == "" {
295 t.Errorf("no Location header in Response")
299 // Tests that Client redirects' contexts are derived from the original request's context.
300 func TestClientRedirectContext(t *testing.T) {
303 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
304 Redirect(w, r, "/", StatusTemporaryRedirect)
308 ctx, cancel := context.WithCancel(context.Background())
310 c.CheckRedirect = func(req *Request, via []*Request) error {
313 case <-req.Context().Done():
315 case <-time.After(5 * time.Second):
316 return errors.New("redirected request's context never expired after root request canceled")
319 req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
321 ue, ok := err.(*url.Error)
323 t.Fatalf("got error %T; want *url.Error", err)
325 if ue.Err != context.Canceled {
326 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
330 type redirectTest struct {
332 want int // response code
336 func TestPostRedirects(t *testing.T) {
337 postRedirectTests := []redirectTest{
339 {"/?code=301&next=302", 200, "c301"},
340 {"/?code=302&next=302", 200, "c302"},
341 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
342 {"/?code=304", 304, "c304"},
343 {"/?code=305", 305, "c305"},
344 {"/?code=307&next=303,308,302", 200, "c307"},
345 {"/?code=308&next=302,301", 200, "c308"},
346 {"/?code=404", 404, "c404"},
349 wantSegments := []string{
351 `POST /?code=301&next=302 "c301"`,
354 `POST /?code=302&next=302 "c302"`,
357 `POST /?code=303&next=301 "c303wc301"`,
360 `POST /?code=304 "c304"`,
361 `POST /?code=305 "c305"`,
362 `POST /?code=307&next=303,308,302 "c307"`,
363 `POST /?code=303&next=308,302 "c307"`,
364 `GET /?code=308&next=302 ""`,
365 `GET /?code=302 "c307"`,
367 `POST /?code=308&next=302,301 "c308"`,
368 `POST /?code=302&next=301 "c308"`,
371 `POST /?code=404 "c404"`,
373 want := strings.Join(wantSegments, "\n")
374 testRedirectsByMethod(t, "POST", postRedirectTests, want)
377 func TestDeleteRedirects(t *testing.T) {
378 deleteRedirectTests := []redirectTest{
380 {"/?code=301&next=302,308", 200, "c301"},
381 {"/?code=302&next=302", 200, "c302"},
382 {"/?code=303", 200, "c303"},
383 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
384 {"/?code=308&next=307", 200, "c308"},
385 {"/?code=404", 404, "c404"},
388 wantSegments := []string{
390 `DELETE /?code=301&next=302,308 "c301"`,
391 `GET /?code=302&next=308 ""`,
394 `DELETE /?code=302&next=302 "c302"`,
397 `DELETE /?code=303 "c303"`,
399 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
400 `DELETE /?code=301&next=308,303,302,304 "c307"`,
401 `GET /?code=308&next=303,302,304 ""`,
402 `GET /?code=303&next=302,304 "c307"`,
403 `GET /?code=302&next=304 ""`,
405 `DELETE /?code=308&next=307 "c308"`,
406 `DELETE /?code=307 "c308"`,
408 `DELETE /?code=404 "c404"`,
410 want := strings.Join(wantSegments, "\n")
411 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
414 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
420 var ts *httptest.Server
421 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
423 slurp, _ := io.ReadAll(r.Body)
424 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
425 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
426 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
430 urlQuery := r.URL.Query()
431 if v := urlQuery.Get("code"); v != "" {
433 if final := urlQuery.Get("next"); final != "" {
434 first, rest, _ := strings.Cut(final, ",")
435 location = fmt.Sprintf("%s?code=%s", location, first)
437 location = fmt.Sprintf("%s&next=%s", location, rest)
440 code, _ := strconv.Atoi(v)
442 w.Header().Set("Location", location)
450 for _, tt := range table {
451 content := tt.redirectBody
452 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
453 req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
454 res, err := c.Do(req)
459 if res.StatusCode != tt.want {
460 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
467 got = strings.TrimSpace(got)
468 want = strings.TrimSpace(want)
471 got, want, lines := removeCommonLines(got, want)
472 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
476 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
478 nl := strings.IndexByte(a, '\n')
480 return a, b, commonLines
483 if !strings.HasPrefix(b, line) {
484 return a, b, commonLines
492 func TestClientRedirectUseResponse(t *testing.T) {
495 const body = "Hello, world."
496 var ts *httptest.Server
497 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
498 if strings.Contains(r.URL.Path, "/other") {
499 io.WriteString(w, "wrong body")
501 w.Header().Set("Location", ts.URL+"/other")
502 w.WriteHeader(StatusFound)
503 io.WriteString(w, body)
509 c.CheckRedirect = func(req *Request, via []*Request) error {
510 if req.Response == nil {
511 t.Error("expected non-nil Request.Response")
513 return ErrUseLastResponse
515 res, err := c.Get(ts.URL)
519 if res.StatusCode != StatusFound {
520 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
522 defer res.Body.Close()
523 slurp, err := io.ReadAll(res.Body)
527 if string(slurp) != body {
528 t.Errorf("body = %q; want %q", slurp, body)
532 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
533 // have a Location header.
534 func TestClientRedirect308NoLocation(t *testing.T) {
537 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
538 w.Header().Set("Foo", "Bar")
543 res, err := c.Get(ts.URL)
548 if res.StatusCode != 308 {
549 t.Errorf("status = %d; want %d", res.StatusCode, 308)
551 if got := res.Header.Get("Foo"); got != "Bar" {
552 t.Errorf("Foo header = %q; want Bar", got)
556 // Don't follow a 307/308 if we can't resent the request body.
557 func TestClientRedirect308NoGetBody(t *testing.T) {
560 const fakeURL = "https://localhost:1234/" // won't be hit
561 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
562 w.Header().Set("Location", fakeURL)
566 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
571 req.GetBody = nil // so it can't rewind.
572 res, err := c.Do(req)
577 if res.StatusCode != 308 {
578 t.Errorf("status = %d; want %d", res.StatusCode, 308)
580 if got := res.Header.Get("Location"); got != fakeURL {
581 t.Errorf("Location header = %q; want %q", got, fakeURL)
585 var expectedCookies = []*Cookie{
586 {Name: "ChocolateChip", Value: "tasty"},
587 {Name: "First", Value: "Hit"},
588 {Name: "Second", Value: "Hit"},
591 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
592 for _, cookie := range r.Cookies() {
595 if r.URL.Path == "/" {
596 SetCookie(w, expectedCookies[1])
597 Redirect(w, r, "/second", StatusMovedPermanently)
599 SetCookie(w, expectedCookies[2])
600 w.Write([]byte("hello"))
604 func TestClientSendsCookieFromJar(t *testing.T) {
606 tr := &recordingTransport{}
607 client := &Client{Transport: tr}
608 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
609 us := "http://dummy.faketld/"
610 u, _ := url.Parse(us)
611 client.Jar.SetCookies(u, expectedCookies)
613 client.Get(us) // Note: doesn't hit network
614 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
616 client.Head(us) // Note: doesn't hit network
617 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
619 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
620 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
622 client.PostForm(us, url.Values{}) // Note: doesn't hit network
623 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
625 req, _ := NewRequest("GET", us, nil)
626 client.Do(req) // Note: doesn't hit network
627 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
629 req, _ = NewRequest("POST", us, nil)
630 client.Do(req) // Note: doesn't hit network
631 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
634 // Just enough correctness for our redirect tests. Uses the URL.Host as the
635 // scope of all cookies.
636 type TestJar struct {
638 perURL map[string][]*Cookie
641 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
645 j.perURL = make(map[string][]*Cookie)
647 j.perURL[u.Host] = cookies
650 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
653 return j.perURL[u.Host]
656 func TestRedirectCookiesJar(t *testing.T) {
659 var ts *httptest.Server
660 ts = httptest.NewServer(echoCookiesRedirectHandler)
664 u, _ := url.Parse(ts.URL)
665 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
666 resp, err := c.Get(ts.URL)
668 t.Fatalf("Get: %v", err)
671 matchReturnedCookies(t, expectedCookies, resp.Cookies())
674 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
675 if len(given) != len(expected) {
676 t.Logf("Received cookies: %v", given)
677 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
679 for _, ec := range expected {
681 for _, c := range given {
682 if ec.Name == c.Name && ec.Value == c.Value {
688 t.Errorf("Missing cookie %v", ec)
693 func TestJarCalls(t *testing.T) {
695 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
696 pathSuffix := r.RequestURI[1:]
697 if r.RequestURI == "/nosetcookie" {
698 return // don't set cookies for this path
700 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
701 if r.RequestURI == "/" {
702 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
706 jar := new(RecordingJar)
709 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
710 return net.Dial("tcp", ts.Listener.Addr().String())
712 _, err := c.Get("http://firsthost.fake/")
716 _, err = c.Get("http://firsthost.fake/nosetcookie")
720 got := jar.log.String()
721 want := `Cookies("http://firsthost.fake/")
722 SetCookie("http://firsthost.fake/", [name=val])
723 Cookies("http://secondhost.fake/secondpath")
724 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
725 Cookies("http://firsthost.fake/nosetcookie")
728 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
732 // RecordingJar keeps a log of calls made to it, without
733 // tracking any cookies.
734 type RecordingJar struct {
739 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
740 j.logf("SetCookie(%q, %v)\n", u, cookies)
743 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
744 j.logf("Cookies(%q)\n", u)
748 func (j *RecordingJar) logf(format string, args ...any) {
751 fmt.Fprintf(&j.log, format, args...)
754 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
755 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
757 func testStreamingGet(t *testing.T, h2 bool) {
759 say := make(chan string)
760 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
762 for str := range say {
770 res, err := c.Get(cst.ts.URL)
775 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
777 n, err := io.ReadFull(res.Body, buf[0:len(str)])
779 t.Fatalf("ReadFull on %q: %v", str, err)
782 t.Fatalf("Receiving %q, only read %d bytes", str, n)
784 got := string(buf[0:n])
786 t.Fatalf("Expected %q, got %q", str, got)
790 _, err = io.ReadFull(res.Body, buf[0:1])
792 t.Fatalf("at end expected EOF, got %v", err)
796 type writeCountingConn struct {
801 func (c *writeCountingConn) Write(p []byte) (int, error) {
803 return c.Conn.Write(p)
806 // TestClientWrites verifies that client requests are buffered and we
807 // don't send a TCP packet per line of the http request + body.
808 func TestClientWrites(t *testing.T) {
810 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
815 dialer := func(netz string, addr string) (net.Conn, error) {
816 c, err := net.Dial(netz, addr)
818 c = &writeCountingConn{c, &writes}
823 c.Transport.(*Transport).Dial = dialer
825 _, err := c.Get(ts.URL)
830 t.Errorf("Get request did %d Write calls, want 1", writes)
834 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
839 t.Errorf("Post request did %d Write calls, want 1", writes)
843 func TestClientInsecureTransport(t *testing.T) {
846 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
847 w.Write([]byte("Hello"))
849 errc := make(chanWriter, 10) // but only expecting 1
850 ts.Config.ErrorLog = log.New(errc, "", 0)
853 // TODO(bradfitz): add tests for skipping hostname checks too?
854 // would require a new cert for testing, and probably
855 // redundant with these tests.
857 for _, insecure := range []bool{true, false} {
858 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
859 InsecureSkipVerify: insecure,
861 res, err := c.Get(ts.URL)
862 if (err == nil) != insecure {
863 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
872 if !strings.Contains(v, "TLS handshake error") {
873 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
875 case <-time.After(5 * time.Second):
876 t.Errorf("timeout waiting for logged error")
881 func TestClientErrorWithRequestURI(t *testing.T) {
883 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
884 req.RequestURI = "/this/field/is/illegal/and/should/error/"
885 _, err := DefaultClient.Do(req)
887 t.Fatalf("expected an error")
889 if !strings.Contains(err.Error(), "RequestURI") {
890 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
894 func TestClientWithCorrectTLSServerName(t *testing.T) {
897 const serverName = "example.com"
898 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
899 if r.TLS.ServerName != serverName {
900 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
906 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
907 if _, err := c.Get(ts.URL); err != nil {
908 t.Fatalf("expected successful TLS connection, got error: %v", err)
912 func TestClientWithIncorrectTLSServerName(t *testing.T) {
914 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
916 errc := make(chanWriter, 10) // but only expecting 1
917 ts.Config.ErrorLog = log.New(errc, "", 0)
920 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
921 _, err := c.Get(ts.URL)
923 t.Fatalf("expected an error")
925 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
926 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
930 if !strings.Contains(v, "TLS handshake error") {
931 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
933 case <-time.After(5 * time.Second):
934 t.Errorf("timeout waiting for logged error")
938 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
941 // tls.Config.ServerName (non-empty, set to "example.com") takes
942 // precedence over "some-other-host.tld" which previously incorrectly
943 // took precedence. We don't actually connect to (or even resolve)
944 // "some-other-host.tld", though, because of the Transport.Dial hook.
946 // The httptest.Server has a cert with "example.com" as its name.
947 func TestTransportUsesTLSConfigServerName(t *testing.T) {
949 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
950 w.Write([]byte("Hello"))
955 tr := c.Transport.(*Transport)
956 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
957 tr.Dial = func(netw, addr string) (net.Conn, error) {
958 return net.Dial(netw, ts.Listener.Addr().String())
960 res, err := c.Get("https://some-other-host.tld/")
967 func TestResponseSetsTLSConnectionState(t *testing.T) {
969 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
970 w.Write([]byte("Hello"))
975 tr := c.Transport.(*Transport)
976 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
977 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
978 tr.Dial = func(netw, addr string) (net.Conn, error) {
979 return net.Dial(netw, ts.Listener.Addr().String())
981 res, err := c.Get("https://example.com/")
985 defer res.Body.Close()
987 t.Fatal("Response didn't set TLS Connection State.")
989 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
990 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
994 // Check that an HTTPS client can interpret a particular TLS error
995 // to determine that the server is speaking HTTP.
996 // See golang.org/issue/11111.
997 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
999 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1000 ts.Config.ErrorLog = quietLog
1003 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1004 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1005 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1009 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1010 func TestClientHeadContentLength_h1(t *testing.T) {
1011 testClientHeadContentLength(t, h1Mode)
1014 func TestClientHeadContentLength_h2(t *testing.T) {
1015 testClientHeadContentLength(t, h2Mode)
1018 func testClientHeadContentLength(t *testing.T, h2 bool) {
1020 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1021 if v := r.FormValue("cl"); v != "" {
1022 w.Header().Set("Content-Length", v)
1030 {"/?cl=1234", 1234},
1034 for _, tt := range tests {
1035 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1036 res, err := cst.c.Do(req)
1040 if res.ContentLength != tt.want {
1041 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1043 bs, err := io.ReadAll(res.Body)
1048 t.Errorf("Unexpected content: %q", bs)
1053 func TestEmptyPasswordAuth(t *testing.T) {
1057 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1058 auth := r.Header.Get("Authorization")
1059 if strings.HasPrefix(auth, "Basic ") {
1061 decoded, err := base64.StdEncoding.DecodeString(encoded)
1065 expected := gopher + ":"
1066 s := string(decoded)
1068 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1071 t.Errorf("Invalid auth %q", auth)
1075 req, err := NewRequest("GET", ts.URL, nil)
1079 req.URL.User = url.User(gopher)
1081 resp, err := c.Do(req)
1085 defer resp.Body.Close()
1088 func TestBasicAuth(t *testing.T) {
1090 tr := &recordingTransport{}
1091 client := &Client{Transport: tr}
1093 url := "http://My%20User:My%20Pass@dummy.faketld/"
1094 expected := "My User:My Pass"
1097 if tr.req.Method != "GET" {
1098 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1100 if tr.req.URL.String() != url {
1101 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1103 if tr.req.Header == nil {
1104 t.Fatalf("expected non-nil request Header")
1106 auth := tr.req.Header.Get("Authorization")
1107 if strings.HasPrefix(auth, "Basic ") {
1109 decoded, err := base64.StdEncoding.DecodeString(encoded)
1113 s := string(decoded)
1115 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1118 t.Errorf("Invalid auth %q", auth)
1122 func TestBasicAuthHeadersPreserved(t *testing.T) {
1124 tr := &recordingTransport{}
1125 client := &Client{Transport: tr}
1127 // If Authorization header is provided, username in URL should not override it
1128 url := "http://My%20User@dummy.faketld/"
1129 req, err := NewRequest("GET", url, nil)
1133 req.SetBasicAuth("My User", "My Pass")
1134 expected := "My User:My Pass"
1137 if tr.req.Method != "GET" {
1138 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1140 if tr.req.URL.String() != url {
1141 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1143 if tr.req.Header == nil {
1144 t.Fatalf("expected non-nil request Header")
1146 auth := tr.req.Header.Get("Authorization")
1147 if strings.HasPrefix(auth, "Basic ") {
1149 decoded, err := base64.StdEncoding.DecodeString(encoded)
1153 s := string(decoded)
1155 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1158 t.Errorf("Invalid auth %q", auth)
1163 func TestStripPasswordFromError(t *testing.T) {
1164 client := &Client{Transport: &recordingTransport{}}
1165 testCases := []struct {
1171 desc: "Strip password from error message",
1172 in: "http://user:password@dummy.faketld/",
1173 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1176 desc: "Don't Strip password from domain name",
1177 in: "http://user:password@password.faketld/",
1178 out: `Get "http://user:***@password.faketld/": dummy impl`,
1181 desc: "Don't Strip password from path",
1182 in: "http://user:password@dummy.faketld/password",
1183 out: `Get "http://user:***@dummy.faketld/password": dummy impl`,
1186 desc: "Strip escaped password",
1187 in: "http://user:pa%2Fssword@dummy.faketld/",
1188 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1191 for _, tC := range testCases {
1192 t.Run(tC.desc, func(t *testing.T) {
1193 _, err := client.Get(tC.in)
1194 if err.Error() != tC.out {
1195 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1196 tC.in, tC.out, err.Error())
1202 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1203 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1205 func testClientTimeout(t *testing.T, h2 bool) {
1211 nonce string // a unique per-request string
1212 sawSlowNonce bool // true if the handler saw /slow?nonce=<nonce>
1214 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1216 if r.URL.Path == "/" {
1217 Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
1220 if r.URL.Path == "/slow" {
1222 if r.Form.Get("nonce") == nonce {
1225 t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
1229 w.Write([]byte("Hello"))
1231 <-r.Context().Done()
1237 // Try to trigger a timeout after reading part of the response body.
1238 // The initial timeout is emprically usually long enough on a decently fast
1239 // machine, but if we undershoot we'll retry with exponentially longer
1240 // timeouts until the test either passes or times out completely.
1241 // This keeps the test reasonably fast in the typical case but allows it to
1242 // also eventually succeed on arbitrarily slow machines.
1243 timeout := 10 * time.Millisecond
1245 for ; ; timeout *= 2 {
1247 // The only way we can feasibly hit this while the test is running is if
1248 // the request fails without actually waiting for the timeout to occur.
1249 t.Fatalf("timeout overflow")
1251 if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
1252 t.Fatalf("failed to produce expected timeout before test deadline")
1254 t.Logf("attempting test with timeout %v", timeout)
1255 cst.c.Timeout = timeout
1258 nonce = fmt.Sprint(nextNonce)
1260 sawSlowNonce = false
1262 res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
1264 if strings.Contains(err.Error(), "Client.Timeout") {
1265 // Timed out before handler could respond.
1266 t.Logf("timeout before response received")
1276 t.Fatal("handler never got /slow request, but client returned response")
1279 _, err = io.ReadAll(res.Body)
1283 t.Fatal("expected error from ReadAll")
1285 ne, ok := err.(net.Error)
1287 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1288 } else if !ne.Timeout() {
1289 t.Errorf("net.Error.Timeout = false; want true")
1291 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1292 t.Errorf("error string = %q; missing timeout substring", got)
1299 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1300 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1302 // Client.Timeout firing before getting to the body
1303 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1306 donec := make(chan bool, 1)
1307 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1311 // Note that we use a channel send here and not a close.
1312 // The race detector doesn't know that we're waiting for a timeout
1313 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1314 // with us closing it. If we timed out immediately, we could close the testserver
1315 // before we entered the handler. We're not timing out immediately and there's
1316 // no way we would be done before we entered the handler, but the race detector
1317 // doesn't know this, so synchronize explicitly.
1318 defer func() { donec <- true }()
1320 cst.c.Timeout = 5 * time.Millisecond
1321 res, err := cst.c.Get(cst.ts.URL)
1324 t.Fatal("got response from Get; expected error")
1326 if _, ok := err.(*url.Error); !ok {
1327 t.Fatalf("Got error of type %T; want *url.Error", err)
1329 ne, ok := err.(net.Error)
1331 t.Fatalf("Got error of type %T; want some net.Error", err)
1334 t.Error("net.Error.Timeout = false; want true")
1336 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1337 t.Errorf("error string = %q; missing timeout substring", got)
1341 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1343 func TestClientTimeoutCancel(t *testing.T) {
1347 testDone := make(chan struct{})
1348 ctx, cancel := context.WithCancel(context.Background())
1350 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1355 defer close(testDone)
1357 cst.c.Timeout = 1 * time.Hour
1358 req, _ := NewRequest("GET", cst.ts.URL, nil)
1359 req.Cancel = ctx.Done()
1360 res, err := cst.c.Do(req)
1365 _, err = io.Copy(io.Discard, res.Body)
1366 if err != ExportErrRequestCanceled {
1367 t.Fatalf("error = %v; want errRequestCanceled", err)
1371 func TestClientTimeoutDoesNotExpire_h1(t *testing.T) { testClientTimeoutDoesNotExpire(t, h1Mode) }
1372 func TestClientTimeoutDoesNotExpire_h2(t *testing.T) { testClientTimeoutDoesNotExpire(t, h2Mode) }
1374 // Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1375 func testClientTimeoutDoesNotExpire(t *testing.T, h2 bool) {
1379 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1380 w.Write([]byte("body"))
1384 cst.c.Timeout = 1 * time.Hour
1385 req, _ := NewRequest("GET", cst.ts.URL, nil)
1386 res, err := cst.c.Do(req)
1390 if _, err = io.Copy(io.Discard, res.Body); err != nil {
1391 t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1393 if err = res.Body.Close(); err != nil {
1394 t.Fatalf("res.Body.Close() = %v, want nil", err)
1398 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1399 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1400 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1403 saw := make(chan string, 2)
1404 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1406 if r.URL.Path == "/" {
1407 Redirect(w, r, "/foo", StatusFound) // which includes a body
1412 res, err := cst.c.Get(cst.ts.URL)
1416 _, err = io.ReadAll(res.Body)
1426 t.Fatal("server didn't see a request")
1431 case second = <-saw:
1433 t.Fatal("server didn't see a second request")
1436 if first != second {
1437 t.Fatal("server saw different client ports before & after the redirect")
1441 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1442 type eofReaderFunc func()
1444 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1449 func TestReferer(t *testing.T) {
1451 lastReq, newReq string // from -> to URLs
1455 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1456 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1458 // don't send a user and password:
1459 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1460 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1463 {"http://test.com", "http://link.com", "http://test.com"},
1464 {"https://test.com", "https://link.com", "https://test.com"},
1466 // https to http doesn't send a referer:
1467 {"https://test.com", "http://link.com", ""},
1468 {"https://gopher:go@test.com", "http://link.com", ""},
1470 for _, tt := range tests {
1471 l, err := url.Parse(tt.lastReq)
1475 n, err := url.Parse(tt.newReq)
1479 r := ExportRefererForURL(l, n)
1481 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1486 // issue15577Tripper returns a Response with a redirect response
1487 // header and doesn't populate its Response.Request field.
1488 type issue15577Tripper struct{}
1490 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1493 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1494 Body: io.NopCloser(strings.NewReader("")),
1499 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1500 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1502 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1503 Transport: issue15577Tripper{},
1505 // Check that this doesn't crash:
1506 c.Get("http://dummy.tld")
1509 // Issue 4800: copy (some) headers when Client follows a redirect.
1510 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1512 ua = "some-agent/1.2"
1516 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1518 "User-Agent": []string{ua},
1519 "X-Foo": []string{xfoo},
1520 "Referer": []string{ts2URL},
1521 "Accept-Encoding": []string{"gzip"},
1523 if !reflect.DeepEqual(r.Header, want) {
1524 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1527 w.Header().Set("Result", "got errors")
1529 w.Header().Set("Result", "ok")
1533 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1534 Redirect(w, r, ts1.URL, StatusFound)
1540 c.CheckRedirect = func(r *Request, via []*Request) error {
1542 "User-Agent": []string{ua},
1543 "X-Foo": []string{xfoo},
1544 "Referer": []string{ts2URL},
1546 if !reflect.DeepEqual(r.Header, want) {
1547 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1552 req, _ := NewRequest("GET", ts2.URL, nil)
1553 req.Header.Add("User-Agent", ua)
1554 req.Header.Add("X-Foo", xfoo)
1555 req.Header.Add("Cookie", "foo=bar")
1556 req.Header.Add("Authorization", "secretpassword")
1557 res, err := c.Do(req)
1561 defer res.Body.Close()
1562 if res.StatusCode != 200 {
1565 if got := res.Header.Get("Result"); got != "ok" {
1566 t.Errorf("result = %q; want ok", got)
1570 // Issue 22233: copy host when Client follows a relative redirect.
1571 func TestClientCopyHostOnRedirect(t *testing.T) {
1572 // Virtual hostname: should not receive any request.
1573 virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1574 t.Errorf("Virtual host received request %v", r.URL)
1576 io.WriteString(w, "should not see this response")
1578 defer virtual.Close()
1579 virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1580 t.Logf("Virtual host is %v", virtualHost)
1582 // Actual hostname: should not receive any request.
1583 const wantBody = "response body"
1586 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1589 // Relative redirect.
1590 if r.Host != virtualHost {
1591 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1595 w.Header().Set("Location", "/hop")
1598 // Absolute redirect.
1599 if r.Host != virtualHost {
1600 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1604 w.Header().Set("Location", tsURL+"/final")
1607 if r.Host != tsHost {
1608 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1613 io.WriteString(w, wantBody)
1615 t.Errorf("Serving unexpected path %q", r.URL.Path)
1621 tsHost = strings.TrimPrefix(ts.URL, "http://")
1622 t.Logf("Server host is %v", tsHost)
1625 req, _ := NewRequest("GET", ts.URL, nil)
1626 req.Host = virtualHost
1627 resp, err := c.Do(req)
1631 defer resp.Body.Close()
1632 if resp.StatusCode != 200 {
1633 t.Fatal(resp.Status)
1635 if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1636 t.Errorf("body = %q; want %q", got, wantBody)
1640 // Issue 17494: cookies should be altered when Client follows redirects.
1641 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1642 cookieMap := func(cs []*Cookie) map[string][]string {
1643 m := make(map[string][]string)
1644 for _, c := range cs {
1645 m[c.Name] = append(m[c.Name], c.Value)
1650 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1651 var want map[string][]string
1652 got := cookieMap(r.Cookies())
1654 c, _ := r.Cookie("Cycle")
1657 want = map[string][]string{
1658 "Cookie1": {"OldValue1a", "OldValue1b"},
1659 "Cookie2": {"OldValue2"},
1660 "Cookie3": {"OldValue3a", "OldValue3b"},
1661 "Cookie4": {"OldValue4"},
1664 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1665 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1666 Redirect(w, r, "/", StatusFound)
1668 want = map[string][]string{
1669 "Cookie1": {"OldValue1a", "OldValue1b"},
1670 "Cookie3": {"OldValue3a", "OldValue3b"},
1671 "Cookie4": {"OldValue4"},
1674 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1675 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1676 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1677 Redirect(w, r, "/", StatusFound)
1679 want = map[string][]string{
1680 "Cookie1": {"OldValue1a", "OldValue1b"},
1681 "Cookie3": {"NewValue3"},
1682 "Cookie4": {"NewValue4"},
1685 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1686 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1687 Redirect(w, r, "/", StatusFound)
1689 want = map[string][]string{
1690 "Cookie1": {"OldValue1a", "OldValue1b"},
1691 "Cookie3": {"NewValue3"},
1692 "Cookie4": {"NewValue4"},
1693 "Cookie5": {"NewValue5"},
1696 // Don't redirect to ensure the loop ends.
1698 t.Errorf("unexpected redirect cycle")
1702 if !reflect.DeepEqual(got, want) {
1703 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1708 jar, _ := cookiejar.New(nil)
1712 u, _ := url.Parse(ts.URL)
1713 req, _ := NewRequest("GET", ts.URL, nil)
1714 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1715 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1716 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1717 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1718 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1719 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1720 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1721 res, err := c.Do(req)
1725 defer res.Body.Close()
1726 if res.StatusCode != 200 {
1731 // Part of Issue 4800
1732 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1739 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1740 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1742 // Sensitive headers:
1743 {"cookie", "http://foo.com/", "http://bar.com/", false},
1744 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1745 {"authorization", "http://foo.com/", "http://bar.com/", false},
1746 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1748 // But subdomains should work:
1749 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1750 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1751 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1752 {"www-authenticate", "http://foo.com/", "https://foo.com/", false},
1753 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1754 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1755 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1756 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1757 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false},
1759 for i, tt := range tests {
1760 u0, err := url.Parse(tt.initialURL)
1762 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1765 u1, err := url.Parse(tt.destURL)
1767 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1770 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1772 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1773 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1778 func TestClientRedirectTypes(t *testing.T) {
1782 tests := [...]struct {
1785 wantMethod string // desired subsequent client method
1787 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1788 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1789 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1790 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1791 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1793 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1794 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1795 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1796 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1797 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1799 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1800 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1801 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1802 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1803 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1805 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1806 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1807 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1808 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1809 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1811 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1812 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1813 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1814 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1815 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1817 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1818 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1819 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1820 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1821 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1824 handlerc := make(chan HandlerFunc, 1)
1826 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1833 for i, tt := range tests {
1834 handlerc <- func(w ResponseWriter, r *Request) {
1835 w.Header().Set("Location", ts.URL)
1836 w.WriteHeader(tt.serverStatus)
1839 req, err := NewRequest(tt.method, ts.URL, nil)
1841 t.Errorf("#%d: NewRequest: %v", i, err)
1845 c.CheckRedirect = func(req *Request, via []*Request) error {
1846 if got, want := req.Method, tt.wantMethod; got != want {
1847 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1849 handlerc <- func(rw ResponseWriter, req *Request) {
1850 // TODO: Check that the body is valid when we do 307 and 308 support
1855 res, err := c.Do(req)
1857 t.Errorf("#%d: Response: %v", i, err)
1865 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1866 // Its Read returns readErr and increments *readCalls atomically.
1867 // Its Close returns nil and increments *closeCalls atomically.
1868 type issue18239Body struct {
1874 func (b issue18239Body) Read([]byte) (int, error) {
1875 atomic.AddInt32(b.readCalls, 1)
1879 func (b issue18239Body) Close() error {
1880 atomic.AddInt32(b.closeCalls, 1)
1884 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1885 // if Request.GetBody is not defined.
1886 func TestTransportBodyReadError(t *testing.T) {
1889 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1890 if r.URL.Path == "/ping" {
1893 buf := make([]byte, 1)
1894 n, err := r.Body.Read(buf)
1895 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1899 tr := c.Transport.(*Transport)
1901 // Do one initial successful request to create an idle TCP connection
1902 // for the subsequent request to reuse. (The Transport only retries
1903 // requests on reused connections.)
1904 res, err := c.Get(ts.URL + "/ping")
1910 var readCallsAtomic int32
1911 var closeCallsAtomic int32 // atomic
1912 someErr := errors.New("some body read error")
1913 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1915 req, err := NewRequest("POST", ts.URL, body)
1920 _, err = tr.RoundTrip(req)
1922 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1925 // And verify that our Body wasn't used multiple times, which
1926 // would indicate retries. (as it buggily was during part of
1927 // Go 1.8's dev cycle)
1928 readCalls := atomic.LoadInt32(&readCallsAtomic)
1929 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1931 t.Errorf("read calls = %d; want 1", readCalls)
1933 if closeCalls != 1 {
1934 t.Errorf("close calls = %d; want 1", closeCalls)
1938 type roundTripperWithoutCloseIdle struct{}
1940 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1942 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1944 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1945 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
1947 func TestClientCloseIdleConnections(t *testing.T) {
1948 c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1949 c.CloseIdleConnections() // verify we don't crash at least
1952 var tr RoundTripper = roundTripperWithCloseIdle(func() {
1955 c = &Client{Transport: tr}
1956 c.CloseIdleConnections()
1958 t.Error("not closed")
1962 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1963 errDial := errors.New("not actually dialing")
1965 Timeout: 5 * time.Second,
1966 Transport: &Transport{
1967 DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1968 deadline, ok := ctx.Deadline()
1970 t.Error("no deadline")
1972 t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1978 c.Get("https://example.tld/")
1981 func TestClientDoCanceledVsTimeout_h1(t *testing.T) {
1982 testClientDoCanceledVsTimeout(t, h1Mode)
1985 func TestClientDoCanceledVsTimeout_h2(t *testing.T) {
1986 testClientDoCanceledVsTimeout(t, h2Mode)
1989 // Issue 33545: lock-in the behavior promised by Client.Do's
1990 // docs about request cancellation vs timing out.
1991 func testClientDoCanceledVsTimeout(t *testing.T, h2 bool) {
1993 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1994 w.Write([]byte("Hello, World!"))
1998 cases := []string{"timeout", "canceled"}
2000 for _, name := range cases {
2001 t.Run(name, func(t *testing.T) {
2002 var ctx context.Context
2004 if name == "timeout" {
2005 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
2007 ctx, cancel = context.WithCancel(context.Background())
2012 req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
2013 _, err := cst.c.Do(req)
2015 t.Fatal("Unexpectedly got a nil error")
2018 ue := err.(*url.Error)
2020 var wantIsTimeout bool
2021 var wantErr error = context.Canceled
2022 if name == "timeout" {
2023 wantErr = context.DeadlineExceeded
2024 wantIsTimeout = true
2026 if g, w := ue.Timeout(), wantIsTimeout; g != w {
2027 t.Fatalf("url.Timeout() = %t, want %t", g, w)
2029 if g, w := ue.Err, wantErr; g != w {
2030 t.Errorf("url.Error.Err = %v; want %v", g, w)
2036 type nilBodyRoundTripper struct{}
2038 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
2040 StatusCode: StatusOK,
2041 Status: StatusText(StatusOK),
2047 func TestClientPopulatesNilResponseBody(t *testing.T) {
2048 c := &Client{Transport: nilBodyRoundTripper{}}
2050 resp, err := c.Get("http://localhost/anything")
2052 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2055 if resp.Body == nil {
2056 t.Fatalf("Client failed to provide a non-nil Body as documented")
2059 if err := resp.Body.Close(); err != nil {
2060 t.Fatalf("error from Close on substitute Response.Body: %v", err)
2064 if b, err := io.ReadAll(resp.Body); err != nil {
2065 t.Errorf("read error from substitute Response.Body: %v", err)
2066 } else if len(b) != 0 {
2067 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2071 // Issue 40382: Client calls Close multiple times on Request.Body.
2072 func TestClientCallsCloseOnlyOnce(t *testing.T) {
2075 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2076 w.WriteHeader(StatusNoContent)
2080 // Issue occurred non-deterministically: needed to occur after a successful
2081 // write (into TCP buffer) but before end of body.
2082 for i := 0; i < 50 && !t.Failed(); i++ {
2083 body := &issue40382Body{t: t, n: 300000}
2084 req, err := NewRequest(MethodPost, cst.ts.URL, body)
2088 resp, err := cst.tr.RoundTrip(req)
2096 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2097 // Its Read reads n bytes before returning io.EOF.
2098 // Its Close returns nil but fails the test if called more than once.
2099 type issue40382Body struct {
2102 closeCallsAtomic int32
2105 func (b *issue40382Body) Read(p []byte) (int, error) {
2121 func (b *issue40382Body) Close() error {
2122 if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2123 b.t.Error("Body closed more than once")
2128 func TestProbeZeroLengthBody(t *testing.T) {
2131 reqc := make(chan struct{})
2132 cst := newClientServerTest(t, false, HandlerFunc(func(w ResponseWriter, r *Request) {
2134 if _, err := io.Copy(w, r.Body); err != nil {
2135 t.Errorf("error copying request body: %v", err)
2140 bodyr, bodyw := io.Pipe()
2142 var wg sync.WaitGroup
2146 req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2147 res, err := cst.c.Do(req)
2148 b, err := io.ReadAll(res.Body)
2157 // Request should be sent after trying to probe the request body for 200ms.
2158 case <-time.After(60 * time.Second):
2159 t.Errorf("request not sent after 60s")
2162 // Write the request body and wait for the request to complete.
2163 const content = "body"
2164 bodyw.Write([]byte(content))
2167 if gotBody != content {
2168 t.Fatalf("server got body %q, want %q", gotBody, content)