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.
34 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
35 w.Header().Set("Last-Modified", "sometime")
36 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
39 // pedanticReadAll works like io.ReadAll but additionally
40 // verifies that r obeys the documented io.Reader contract.
41 func pedanticReadAll(r io.Reader) (b []byte, err error) {
46 if n == 0 && err == nil {
47 return nil, fmt.Errorf("Read: n=0 with err=nil")
49 b = append(b, buf[:n]...)
52 if n != 0 || err != io.EOF {
53 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
63 type chanWriter chan string
65 func (w chanWriter) Write(p []byte) (n int, err error) {
70 func TestClient(t *testing.T) {
73 ts := httptest.NewServer(robotsTxtHandler)
77 r, err := c.Get(ts.URL)
80 b, err = pedanticReadAll(r.Body)
85 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
86 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
90 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
91 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
93 func testClientHead(t *testing.T, h2 bool) {
95 cst := newClientServerTest(t, h2, robotsTxtHandler)
98 r, err := cst.c.Head(cst.ts.URL)
102 if _, ok := r.Header["Last-Modified"]; !ok {
103 t.Error("Last-Modified header not found.")
107 type recordingTransport struct {
111 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
113 return nil, errors.New("dummy impl")
116 func TestGetRequestFormat(t *testing.T) {
119 tr := &recordingTransport{}
120 client := &Client{Transport: tr}
121 url := "http://dummy.faketld/"
122 client.Get(url) // Note: doesn't hit network
123 if tr.req.Method != "GET" {
124 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
126 if tr.req.URL.String() != url {
127 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
129 if tr.req.Header == nil {
130 t.Errorf("expected non-nil request Header")
134 func TestPostRequestFormat(t *testing.T) {
136 tr := &recordingTransport{}
137 client := &Client{Transport: tr}
139 url := "http://dummy.faketld/"
140 json := `{"key":"value"}`
141 b := strings.NewReader(json)
142 client.Post(url, "application/json", b) // Note: doesn't hit network
144 if tr.req.Method != "POST" {
145 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
147 if tr.req.URL.String() != url {
148 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
150 if tr.req.Header == nil {
151 t.Fatalf("expected non-nil request Header")
154 t.Error("got Close true, want false")
156 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
157 t.Errorf("got ContentLength %d, want %d", g, e)
161 func TestPostFormRequestFormat(t *testing.T) {
163 tr := &recordingTransport{}
164 client := &Client{Transport: tr}
166 urlStr := "http://dummy.faketld/"
167 form := make(url.Values)
168 form.Set("foo", "bar")
169 form.Add("foo", "bar2")
170 form.Set("bar", "baz")
171 client.PostForm(urlStr, form) // Note: doesn't hit network
173 if tr.req.Method != "POST" {
174 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
176 if tr.req.URL.String() != urlStr {
177 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
179 if tr.req.Header == nil {
180 t.Fatalf("expected non-nil request Header")
182 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
183 t.Errorf("got Content-Type %q, want %q", g, e)
186 t.Error("got Close true, want false")
188 // Depending on map iteration, body can be either of these.
189 expectedBody := "foo=bar&foo=bar2&bar=baz"
190 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
191 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
192 t.Errorf("got ContentLength %d, want %d", g, e)
194 bodyb, err := io.ReadAll(tr.req.Body)
196 t.Fatalf("ReadAll on req.Body: %v", err)
198 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
199 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
203 func TestClientRedirects(t *testing.T) {
206 var ts *httptest.Server
207 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
208 n, _ := strconv.Atoi(r.FormValue("n"))
209 // Test Referer header. (7 is arbitrary position to test at)
211 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
212 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
216 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
219 fmt.Fprintf(w, "n=%d", n)
224 _, err := c.Get(ts.URL)
225 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
226 t.Errorf("with default client Get, expected error %q, got %q", e, g)
229 // HEAD request should also have the ability to follow redirects.
230 _, err = c.Head(ts.URL)
231 if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
232 t.Errorf("with default client Head, expected error %q, got %q", e, g)
235 // Do should also follow redirects.
236 greq, _ := NewRequest("GET", ts.URL, nil)
238 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
239 t.Errorf("with default client Do, expected error %q, got %q", e, g)
242 // Requests with an empty Method should also redirect (Issue 12705)
245 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
246 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
250 var lastVia []*Request
252 c.CheckRedirect = func(req *Request, via []*Request) error {
257 res, err := c.Get(ts.URL)
259 t.Fatalf("Get error: %v", err)
262 finalURL := res.Request.URL.String()
263 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
264 t.Errorf("with custom client, expected error %q, got %q", e, g)
266 if !strings.HasSuffix(finalURL, "/?n=15") {
267 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
269 if e, g := 15, len(lastVia); e != g {
270 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
273 // Test that Request.Cancel is propagated between requests (Issue 14053)
274 creq, _ := NewRequest("HEAD", ts.URL, nil)
275 cancel := make(chan struct{})
277 if _, err := c.Do(creq); err != nil {
281 t.Fatal("didn't see redirect")
283 if lastReq.Cancel != cancel {
284 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
287 checkErr = errors.New("no redirects allowed")
288 res, err = c.Get(ts.URL)
289 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
290 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
293 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
296 if res.Header.Get("Location") == "" {
297 t.Errorf("no Location header in Response")
301 // Tests that Client redirects' contexts are derived from the original request's context.
302 func TestClientRedirectContext(t *testing.T) {
305 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
306 Redirect(w, r, "/", StatusTemporaryRedirect)
310 ctx, cancel := context.WithCancel(context.Background())
312 c.CheckRedirect = func(req *Request, via []*Request) error {
315 case <-req.Context().Done():
317 case <-time.After(5 * time.Second):
318 return errors.New("redirected request's context never expired after root request canceled")
321 req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
323 ue, ok := err.(*url.Error)
325 t.Fatalf("got error %T; want *url.Error", err)
327 if ue.Err != context.Canceled {
328 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
332 type redirectTest struct {
334 want int // response code
338 func TestPostRedirects(t *testing.T) {
339 postRedirectTests := []redirectTest{
341 {"/?code=301&next=302", 200, "c301"},
342 {"/?code=302&next=302", 200, "c302"},
343 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
344 {"/?code=304", 304, "c304"},
345 {"/?code=305", 305, "c305"},
346 {"/?code=307&next=303,308,302", 200, "c307"},
347 {"/?code=308&next=302,301", 200, "c308"},
348 {"/?code=404", 404, "c404"},
351 wantSegments := []string{
353 `POST /?code=301&next=302 "c301"`,
356 `POST /?code=302&next=302 "c302"`,
359 `POST /?code=303&next=301 "c303wc301"`,
362 `POST /?code=304 "c304"`,
363 `POST /?code=305 "c305"`,
364 `POST /?code=307&next=303,308,302 "c307"`,
365 `POST /?code=303&next=308,302 "c307"`,
366 `GET /?code=308&next=302 ""`,
367 `GET /?code=302 "c307"`,
369 `POST /?code=308&next=302,301 "c308"`,
370 `POST /?code=302&next=301 "c308"`,
373 `POST /?code=404 "c404"`,
375 want := strings.Join(wantSegments, "\n")
376 testRedirectsByMethod(t, "POST", postRedirectTests, want)
379 func TestDeleteRedirects(t *testing.T) {
380 deleteRedirectTests := []redirectTest{
382 {"/?code=301&next=302,308", 200, "c301"},
383 {"/?code=302&next=302", 200, "c302"},
384 {"/?code=303", 200, "c303"},
385 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
386 {"/?code=308&next=307", 200, "c308"},
387 {"/?code=404", 404, "c404"},
390 wantSegments := []string{
392 `DELETE /?code=301&next=302,308 "c301"`,
393 `GET /?code=302&next=308 ""`,
396 `DELETE /?code=302&next=302 "c302"`,
399 `DELETE /?code=303 "c303"`,
401 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
402 `DELETE /?code=301&next=308,303,302,304 "c307"`,
403 `GET /?code=308&next=303,302,304 ""`,
404 `GET /?code=303&next=302,304 "c307"`,
405 `GET /?code=302&next=304 ""`,
407 `DELETE /?code=308&next=307 "c308"`,
408 `DELETE /?code=307 "c308"`,
410 `DELETE /?code=404 "c404"`,
412 want := strings.Join(wantSegments, "\n")
413 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
416 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
422 var ts *httptest.Server
423 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
425 slurp, _ := io.ReadAll(r.Body)
426 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
427 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
428 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
432 urlQuery := r.URL.Query()
433 if v := urlQuery.Get("code"); v != "" {
435 if final := urlQuery.Get("next"); final != "" {
436 first, rest, _ := strings.Cut(final, ",")
437 location = fmt.Sprintf("%s?code=%s", location, first)
439 location = fmt.Sprintf("%s&next=%s", location, 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 io.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 := io.ReadAll(res.Body)
529 if string(slurp) != body {
530 t.Errorf("body = %q; want %q", slurp, body)
534 // Issues 17773 and 49281: don't follow a 3xx if the response doesn't
535 // have a Location header.
536 func TestClientRedirectNoLocation(t *testing.T) {
537 for _, code := range []int{301, 308} {
538 t.Run(fmt.Sprint(code), func(t *testing.T) {
541 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
542 w.Header().Set("Foo", "Bar")
547 res, err := c.Get(ts.URL)
552 if res.StatusCode != code {
553 t.Errorf("status = %d; want %d", res.StatusCode, code)
555 if got := res.Header.Get("Foo"); got != "Bar" {
556 t.Errorf("Foo header = %q; want Bar", got)
562 // Don't follow a 307/308 if we can't resent the request body.
563 func TestClientRedirect308NoGetBody(t *testing.T) {
566 const fakeURL = "https://localhost:1234/" // won't be hit
567 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
568 w.Header().Set("Location", fakeURL)
572 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
577 req.GetBody = nil // so it can't rewind.
578 res, err := c.Do(req)
583 if res.StatusCode != 308 {
584 t.Errorf("status = %d; want %d", res.StatusCode, 308)
586 if got := res.Header.Get("Location"); got != fakeURL {
587 t.Errorf("Location header = %q; want %q", got, fakeURL)
591 var expectedCookies = []*Cookie{
592 {Name: "ChocolateChip", Value: "tasty"},
593 {Name: "First", Value: "Hit"},
594 {Name: "Second", Value: "Hit"},
597 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
598 for _, cookie := range r.Cookies() {
601 if r.URL.Path == "/" {
602 SetCookie(w, expectedCookies[1])
603 Redirect(w, r, "/second", StatusMovedPermanently)
605 SetCookie(w, expectedCookies[2])
606 w.Write([]byte("hello"))
610 func TestClientSendsCookieFromJar(t *testing.T) {
612 tr := &recordingTransport{}
613 client := &Client{Transport: tr}
614 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
615 us := "http://dummy.faketld/"
616 u, _ := url.Parse(us)
617 client.Jar.SetCookies(u, expectedCookies)
619 client.Get(us) // Note: doesn't hit network
620 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
622 client.Head(us) // Note: doesn't hit network
623 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
625 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
626 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
628 client.PostForm(us, url.Values{}) // Note: doesn't hit network
629 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
631 req, _ := NewRequest("GET", us, nil)
632 client.Do(req) // Note: doesn't hit network
633 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
635 req, _ = NewRequest("POST", us, nil)
636 client.Do(req) // Note: doesn't hit network
637 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
640 // Just enough correctness for our redirect tests. Uses the URL.Host as the
641 // scope of all cookies.
642 type TestJar struct {
644 perURL map[string][]*Cookie
647 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
651 j.perURL = make(map[string][]*Cookie)
653 j.perURL[u.Host] = cookies
656 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
659 return j.perURL[u.Host]
662 func TestRedirectCookiesJar(t *testing.T) {
665 var ts *httptest.Server
666 ts = httptest.NewServer(echoCookiesRedirectHandler)
670 u, _ := url.Parse(ts.URL)
671 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
672 resp, err := c.Get(ts.URL)
674 t.Fatalf("Get: %v", err)
677 matchReturnedCookies(t, expectedCookies, resp.Cookies())
680 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
681 if len(given) != len(expected) {
682 t.Logf("Received cookies: %v", given)
683 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
685 for _, ec := range expected {
687 for _, c := range given {
688 if ec.Name == c.Name && ec.Value == c.Value {
694 t.Errorf("Missing cookie %v", ec)
699 func TestJarCalls(t *testing.T) {
701 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
702 pathSuffix := r.RequestURI[1:]
703 if r.RequestURI == "/nosetcookie" {
704 return // don't set cookies for this path
706 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
707 if r.RequestURI == "/" {
708 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
712 jar := new(RecordingJar)
715 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
716 return net.Dial("tcp", ts.Listener.Addr().String())
718 _, err := c.Get("http://firsthost.fake/")
722 _, err = c.Get("http://firsthost.fake/nosetcookie")
726 got := jar.log.String()
727 want := `Cookies("http://firsthost.fake/")
728 SetCookie("http://firsthost.fake/", [name=val])
729 Cookies("http://secondhost.fake/secondpath")
730 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
731 Cookies("http://firsthost.fake/nosetcookie")
734 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
738 // RecordingJar keeps a log of calls made to it, without
739 // tracking any cookies.
740 type RecordingJar struct {
745 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
746 j.logf("SetCookie(%q, %v)\n", u, cookies)
749 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
750 j.logf("Cookies(%q)\n", u)
754 func (j *RecordingJar) logf(format string, args ...any) {
757 fmt.Fprintf(&j.log, format, args...)
760 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
761 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
763 func testStreamingGet(t *testing.T, h2 bool) {
765 say := make(chan string)
766 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
768 for str := range say {
776 res, err := c.Get(cst.ts.URL)
781 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
783 n, err := io.ReadFull(res.Body, buf[0:len(str)])
785 t.Fatalf("ReadFull on %q: %v", str, err)
788 t.Fatalf("Receiving %q, only read %d bytes", str, n)
790 got := string(buf[0:n])
792 t.Fatalf("Expected %q, got %q", str, got)
796 _, err = io.ReadFull(res.Body, buf[0:1])
798 t.Fatalf("at end expected EOF, got %v", err)
802 type writeCountingConn struct {
807 func (c *writeCountingConn) Write(p []byte) (int, error) {
809 return c.Conn.Write(p)
812 // TestClientWrites verifies that client requests are buffered and we
813 // don't send a TCP packet per line of the http request + body.
814 func TestClientWrites(t *testing.T) {
816 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
821 dialer := func(netz string, addr string) (net.Conn, error) {
822 c, err := net.Dial(netz, addr)
824 c = &writeCountingConn{c, &writes}
829 c.Transport.(*Transport).Dial = dialer
831 _, err := c.Get(ts.URL)
836 t.Errorf("Get request did %d Write calls, want 1", writes)
840 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
845 t.Errorf("Post request did %d Write calls, want 1", writes)
849 func TestClientInsecureTransport(t *testing.T) {
852 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
853 w.Write([]byte("Hello"))
855 errc := make(chanWriter, 10) // but only expecting 1
856 ts.Config.ErrorLog = log.New(errc, "", 0)
859 // TODO(bradfitz): add tests for skipping hostname checks too?
860 // would require a new cert for testing, and probably
861 // redundant with these tests.
863 for _, insecure := range []bool{true, false} {
864 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
865 InsecureSkipVerify: insecure,
867 res, err := c.Get(ts.URL)
868 if (err == nil) != insecure {
869 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
878 if !strings.Contains(v, "TLS handshake error") {
879 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
881 case <-time.After(5 * time.Second):
882 t.Errorf("timeout waiting for logged error")
887 func TestClientErrorWithRequestURI(t *testing.T) {
889 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
890 req.RequestURI = "/this/field/is/illegal/and/should/error/"
891 _, err := DefaultClient.Do(req)
893 t.Fatalf("expected an error")
895 if !strings.Contains(err.Error(), "RequestURI") {
896 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
900 func TestClientWithCorrectTLSServerName(t *testing.T) {
903 const serverName = "example.com"
904 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
905 if r.TLS.ServerName != serverName {
906 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
912 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
913 if _, err := c.Get(ts.URL); err != nil {
914 t.Fatalf("expected successful TLS connection, got error: %v", err)
918 func TestClientWithIncorrectTLSServerName(t *testing.T) {
920 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
922 errc := make(chanWriter, 10) // but only expecting 1
923 ts.Config.ErrorLog = log.New(errc, "", 0)
926 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
927 _, err := c.Get(ts.URL)
929 t.Fatalf("expected an error")
931 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
932 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
936 if !strings.Contains(v, "TLS handshake error") {
937 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
939 case <-time.After(5 * time.Second):
940 t.Errorf("timeout waiting for logged error")
944 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
947 // tls.Config.ServerName (non-empty, set to "example.com") takes
948 // precedence over "some-other-host.tld" which previously incorrectly
949 // took precedence. We don't actually connect to (or even resolve)
950 // "some-other-host.tld", though, because of the Transport.Dial hook.
952 // The httptest.Server has a cert with "example.com" as its name.
953 func TestTransportUsesTLSConfigServerName(t *testing.T) {
955 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
956 w.Write([]byte("Hello"))
961 tr := c.Transport.(*Transport)
962 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
963 tr.Dial = func(netw, addr string) (net.Conn, error) {
964 return net.Dial(netw, ts.Listener.Addr().String())
966 res, err := c.Get("https://some-other-host.tld/")
973 func TestResponseSetsTLSConnectionState(t *testing.T) {
975 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
976 w.Write([]byte("Hello"))
981 tr := c.Transport.(*Transport)
982 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
983 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
984 tr.Dial = func(netw, addr string) (net.Conn, error) {
985 return net.Dial(netw, ts.Listener.Addr().String())
987 res, err := c.Get("https://example.com/")
991 defer res.Body.Close()
993 t.Fatal("Response didn't set TLS Connection State.")
995 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
996 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
1000 // Check that an HTTPS client can interpret a particular TLS error
1001 // to determine that the server is speaking HTTP.
1002 // See golang.org/issue/11111.
1003 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1005 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1006 ts.Config.ErrorLog = quietLog
1009 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1010 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1011 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1015 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1016 func TestClientHeadContentLength_h1(t *testing.T) {
1017 testClientHeadContentLength(t, h1Mode)
1020 func TestClientHeadContentLength_h2(t *testing.T) {
1021 testClientHeadContentLength(t, h2Mode)
1024 func testClientHeadContentLength(t *testing.T, h2 bool) {
1026 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1027 if v := r.FormValue("cl"); v != "" {
1028 w.Header().Set("Content-Length", v)
1036 {"/?cl=1234", 1234},
1040 for _, tt := range tests {
1041 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1042 res, err := cst.c.Do(req)
1046 if res.ContentLength != tt.want {
1047 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1049 bs, err := io.ReadAll(res.Body)
1054 t.Errorf("Unexpected content: %q", bs)
1059 func TestEmptyPasswordAuth(t *testing.T) {
1063 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1064 auth := r.Header.Get("Authorization")
1065 if strings.HasPrefix(auth, "Basic ") {
1067 decoded, err := base64.StdEncoding.DecodeString(encoded)
1071 expected := gopher + ":"
1072 s := string(decoded)
1074 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1077 t.Errorf("Invalid auth %q", auth)
1081 req, err := NewRequest("GET", ts.URL, nil)
1085 req.URL.User = url.User(gopher)
1087 resp, err := c.Do(req)
1091 defer resp.Body.Close()
1094 func TestBasicAuth(t *testing.T) {
1096 tr := &recordingTransport{}
1097 client := &Client{Transport: tr}
1099 url := "http://My%20User:My%20Pass@dummy.faketld/"
1100 expected := "My User:My Pass"
1103 if tr.req.Method != "GET" {
1104 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1106 if tr.req.URL.String() != url {
1107 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1109 if tr.req.Header == nil {
1110 t.Fatalf("expected non-nil request Header")
1112 auth := tr.req.Header.Get("Authorization")
1113 if strings.HasPrefix(auth, "Basic ") {
1115 decoded, err := base64.StdEncoding.DecodeString(encoded)
1119 s := string(decoded)
1121 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1124 t.Errorf("Invalid auth %q", auth)
1128 func TestBasicAuthHeadersPreserved(t *testing.T) {
1130 tr := &recordingTransport{}
1131 client := &Client{Transport: tr}
1133 // If Authorization header is provided, username in URL should not override it
1134 url := "http://My%20User@dummy.faketld/"
1135 req, err := NewRequest("GET", url, nil)
1139 req.SetBasicAuth("My User", "My Pass")
1140 expected := "My User:My Pass"
1143 if tr.req.Method != "GET" {
1144 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1146 if tr.req.URL.String() != url {
1147 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1149 if tr.req.Header == nil {
1150 t.Fatalf("expected non-nil request Header")
1152 auth := tr.req.Header.Get("Authorization")
1153 if strings.HasPrefix(auth, "Basic ") {
1155 decoded, err := base64.StdEncoding.DecodeString(encoded)
1159 s := string(decoded)
1161 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1164 t.Errorf("Invalid auth %q", auth)
1169 func TestStripPasswordFromError(t *testing.T) {
1170 client := &Client{Transport: &recordingTransport{}}
1171 testCases := []struct {
1177 desc: "Strip password from error message",
1178 in: "http://user:password@dummy.faketld/",
1179 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1182 desc: "Don't Strip password from domain name",
1183 in: "http://user:password@password.faketld/",
1184 out: `Get "http://user:***@password.faketld/": dummy impl`,
1187 desc: "Don't Strip password from path",
1188 in: "http://user:password@dummy.faketld/password",
1189 out: `Get "http://user:***@dummy.faketld/password": dummy impl`,
1192 desc: "Strip escaped password",
1193 in: "http://user:pa%2Fssword@dummy.faketld/",
1194 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1197 for _, tC := range testCases {
1198 t.Run(tC.desc, func(t *testing.T) {
1199 _, err := client.Get(tC.in)
1200 if err.Error() != tC.out {
1201 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1202 tC.in, tC.out, err.Error())
1208 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1209 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1211 func testClientTimeout(t *testing.T, h2 bool) {
1217 nonce string // a unique per-request string
1218 sawSlowNonce bool // true if the handler saw /slow?nonce=<nonce>
1220 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1222 if r.URL.Path == "/" {
1223 Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
1226 if r.URL.Path == "/slow" {
1228 if r.Form.Get("nonce") == nonce {
1231 t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
1235 w.Write([]byte("Hello"))
1237 <-r.Context().Done()
1243 // Try to trigger a timeout after reading part of the response body.
1244 // The initial timeout is emprically usually long enough on a decently fast
1245 // machine, but if we undershoot we'll retry with exponentially longer
1246 // timeouts until the test either passes or times out completely.
1247 // This keeps the test reasonably fast in the typical case but allows it to
1248 // also eventually succeed on arbitrarily slow machines.
1249 timeout := 10 * time.Millisecond
1251 for ; ; timeout *= 2 {
1253 // The only way we can feasibly hit this while the test is running is if
1254 // the request fails without actually waiting for the timeout to occur.
1255 t.Fatalf("timeout overflow")
1257 if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
1258 t.Fatalf("failed to produce expected timeout before test deadline")
1260 t.Logf("attempting test with timeout %v", timeout)
1261 cst.c.Timeout = timeout
1264 nonce = fmt.Sprint(nextNonce)
1266 sawSlowNonce = false
1268 res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
1270 if strings.Contains(err.Error(), "Client.Timeout") {
1271 // Timed out before handler could respond.
1272 t.Logf("timeout before response received")
1275 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1276 testenv.SkipFlaky(t, 43120)
1285 t.Fatal("handler never got /slow request, but client returned response")
1288 _, err = io.ReadAll(res.Body)
1292 t.Fatal("expected error from ReadAll")
1294 ne, ok := err.(net.Error)
1296 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1297 } else if !ne.Timeout() {
1298 t.Errorf("net.Error.Timeout = false; want true")
1300 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1301 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1302 testenv.SkipFlaky(t, 43120)
1304 t.Errorf("error string = %q; missing timeout substring", got)
1311 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1312 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1314 // Client.Timeout firing before getting to the body
1315 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1318 donec := make(chan bool, 1)
1319 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1323 // Note that we use a channel send here and not a close.
1324 // The race detector doesn't know that we're waiting for a timeout
1325 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1326 // with us closing it. If we timed out immediately, we could close the testserver
1327 // before we entered the handler. We're not timing out immediately and there's
1328 // no way we would be done before we entered the handler, but the race detector
1329 // doesn't know this, so synchronize explicitly.
1330 defer func() { donec <- true }()
1332 cst.c.Timeout = 5 * time.Millisecond
1333 res, err := cst.c.Get(cst.ts.URL)
1336 t.Fatal("got response from Get; expected error")
1338 if _, ok := err.(*url.Error); !ok {
1339 t.Fatalf("Got error of type %T; want *url.Error", err)
1341 ne, ok := err.(net.Error)
1343 t.Fatalf("Got error of type %T; want some net.Error", err)
1346 t.Error("net.Error.Timeout = false; want true")
1348 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1349 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1350 testenv.SkipFlaky(t, 43120)
1352 t.Errorf("error string = %q; missing timeout substring", got)
1356 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1358 func TestClientTimeoutCancel(t *testing.T) {
1362 testDone := make(chan struct{})
1363 ctx, cancel := context.WithCancel(context.Background())
1365 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1370 defer close(testDone)
1372 cst.c.Timeout = 1 * time.Hour
1373 req, _ := NewRequest("GET", cst.ts.URL, nil)
1374 req.Cancel = ctx.Done()
1375 res, err := cst.c.Do(req)
1380 _, err = io.Copy(io.Discard, res.Body)
1381 if err != ExportErrRequestCanceled {
1382 t.Fatalf("error = %v; want errRequestCanceled", err)
1386 func TestClientTimeoutDoesNotExpire_h1(t *testing.T) { testClientTimeoutDoesNotExpire(t, h1Mode) }
1387 func TestClientTimeoutDoesNotExpire_h2(t *testing.T) { testClientTimeoutDoesNotExpire(t, h2Mode) }
1389 // Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1390 func testClientTimeoutDoesNotExpire(t *testing.T, h2 bool) {
1394 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1395 w.Write([]byte("body"))
1399 cst.c.Timeout = 1 * time.Hour
1400 req, _ := NewRequest("GET", cst.ts.URL, nil)
1401 res, err := cst.c.Do(req)
1405 if _, err = io.Copy(io.Discard, res.Body); err != nil {
1406 t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1408 if err = res.Body.Close(); err != nil {
1409 t.Fatalf("res.Body.Close() = %v, want nil", err)
1413 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1414 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1415 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1418 saw := make(chan string, 2)
1419 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1421 if r.URL.Path == "/" {
1422 Redirect(w, r, "/foo", StatusFound) // which includes a body
1427 res, err := cst.c.Get(cst.ts.URL)
1431 _, err = io.ReadAll(res.Body)
1441 t.Fatal("server didn't see a request")
1446 case second = <-saw:
1448 t.Fatal("server didn't see a second request")
1451 if first != second {
1452 t.Fatal("server saw different client ports before & after the redirect")
1456 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1457 type eofReaderFunc func()
1459 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1464 func TestReferer(t *testing.T) {
1466 lastReq, newReq string // from -> to URLs
1470 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1471 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1473 // don't send a user and password:
1474 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1475 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1478 {"http://test.com", "http://link.com", "http://test.com"},
1479 {"https://test.com", "https://link.com", "https://test.com"},
1481 // https to http doesn't send a referer:
1482 {"https://test.com", "http://link.com", ""},
1483 {"https://gopher:go@test.com", "http://link.com", ""},
1485 for _, tt := range tests {
1486 l, err := url.Parse(tt.lastReq)
1490 n, err := url.Parse(tt.newReq)
1494 r := ExportRefererForURL(l, n)
1496 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1501 // issue15577Tripper returns a Response with a redirect response
1502 // header and doesn't populate its Response.Request field.
1503 type issue15577Tripper struct{}
1505 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1508 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1509 Body: io.NopCloser(strings.NewReader("")),
1514 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1515 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1517 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1518 Transport: issue15577Tripper{},
1520 // Check that this doesn't crash:
1521 c.Get("http://dummy.tld")
1524 // Issue 4800: copy (some) headers when Client follows a redirect.
1525 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1527 ua = "some-agent/1.2"
1531 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1533 "User-Agent": []string{ua},
1534 "X-Foo": []string{xfoo},
1535 "Referer": []string{ts2URL},
1536 "Accept-Encoding": []string{"gzip"},
1538 if !reflect.DeepEqual(r.Header, want) {
1539 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1542 w.Header().Set("Result", "got errors")
1544 w.Header().Set("Result", "ok")
1548 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1549 Redirect(w, r, ts1.URL, StatusFound)
1555 c.CheckRedirect = func(r *Request, via []*Request) error {
1557 "User-Agent": []string{ua},
1558 "X-Foo": []string{xfoo},
1559 "Referer": []string{ts2URL},
1561 if !reflect.DeepEqual(r.Header, want) {
1562 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1567 req, _ := NewRequest("GET", ts2.URL, nil)
1568 req.Header.Add("User-Agent", ua)
1569 req.Header.Add("X-Foo", xfoo)
1570 req.Header.Add("Cookie", "foo=bar")
1571 req.Header.Add("Authorization", "secretpassword")
1572 res, err := c.Do(req)
1576 defer res.Body.Close()
1577 if res.StatusCode != 200 {
1580 if got := res.Header.Get("Result"); got != "ok" {
1581 t.Errorf("result = %q; want ok", got)
1585 // Issue 22233: copy host when Client follows a relative redirect.
1586 func TestClientCopyHostOnRedirect(t *testing.T) {
1587 // Virtual hostname: should not receive any request.
1588 virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1589 t.Errorf("Virtual host received request %v", r.URL)
1591 io.WriteString(w, "should not see this response")
1593 defer virtual.Close()
1594 virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1595 t.Logf("Virtual host is %v", virtualHost)
1597 // Actual hostname: should not receive any request.
1598 const wantBody = "response body"
1601 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1604 // Relative redirect.
1605 if r.Host != virtualHost {
1606 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1610 w.Header().Set("Location", "/hop")
1613 // Absolute redirect.
1614 if r.Host != virtualHost {
1615 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1619 w.Header().Set("Location", tsURL+"/final")
1622 if r.Host != tsHost {
1623 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1628 io.WriteString(w, wantBody)
1630 t.Errorf("Serving unexpected path %q", r.URL.Path)
1636 tsHost = strings.TrimPrefix(ts.URL, "http://")
1637 t.Logf("Server host is %v", tsHost)
1640 req, _ := NewRequest("GET", ts.URL, nil)
1641 req.Host = virtualHost
1642 resp, err := c.Do(req)
1646 defer resp.Body.Close()
1647 if resp.StatusCode != 200 {
1648 t.Fatal(resp.Status)
1650 if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1651 t.Errorf("body = %q; want %q", got, wantBody)
1655 // Issue 17494: cookies should be altered when Client follows redirects.
1656 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1657 cookieMap := func(cs []*Cookie) map[string][]string {
1658 m := make(map[string][]string)
1659 for _, c := range cs {
1660 m[c.Name] = append(m[c.Name], c.Value)
1665 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1666 var want map[string][]string
1667 got := cookieMap(r.Cookies())
1669 c, _ := r.Cookie("Cycle")
1672 want = map[string][]string{
1673 "Cookie1": {"OldValue1a", "OldValue1b"},
1674 "Cookie2": {"OldValue2"},
1675 "Cookie3": {"OldValue3a", "OldValue3b"},
1676 "Cookie4": {"OldValue4"},
1679 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1680 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1681 Redirect(w, r, "/", StatusFound)
1683 want = map[string][]string{
1684 "Cookie1": {"OldValue1a", "OldValue1b"},
1685 "Cookie3": {"OldValue3a", "OldValue3b"},
1686 "Cookie4": {"OldValue4"},
1689 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1690 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1691 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1692 Redirect(w, r, "/", StatusFound)
1694 want = map[string][]string{
1695 "Cookie1": {"OldValue1a", "OldValue1b"},
1696 "Cookie3": {"NewValue3"},
1697 "Cookie4": {"NewValue4"},
1700 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1701 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1702 Redirect(w, r, "/", StatusFound)
1704 want = map[string][]string{
1705 "Cookie1": {"OldValue1a", "OldValue1b"},
1706 "Cookie3": {"NewValue3"},
1707 "Cookie4": {"NewValue4"},
1708 "Cookie5": {"NewValue5"},
1711 // Don't redirect to ensure the loop ends.
1713 t.Errorf("unexpected redirect cycle")
1717 if !reflect.DeepEqual(got, want) {
1718 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1723 jar, _ := cookiejar.New(nil)
1727 u, _ := url.Parse(ts.URL)
1728 req, _ := NewRequest("GET", ts.URL, nil)
1729 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1730 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1731 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1732 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1733 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1734 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1735 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1736 res, err := c.Do(req)
1740 defer res.Body.Close()
1741 if res.StatusCode != 200 {
1746 // Part of Issue 4800
1747 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1754 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1755 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1757 // Sensitive headers:
1758 {"cookie", "http://foo.com/", "http://bar.com/", false},
1759 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1760 {"authorization", "http://foo.com/", "http://bar.com/", false},
1761 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1763 // But subdomains should work:
1764 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1765 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1766 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1767 {"www-authenticate", "http://foo.com/", "https://foo.com/", false},
1768 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1769 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1770 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1771 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1772 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false},
1774 for i, tt := range tests {
1775 u0, err := url.Parse(tt.initialURL)
1777 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1780 u1, err := url.Parse(tt.destURL)
1782 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1785 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1787 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1788 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1793 func TestClientRedirectTypes(t *testing.T) {
1797 tests := [...]struct {
1800 wantMethod string // desired subsequent client method
1802 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1803 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1804 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1805 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1806 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1808 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1809 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1810 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1811 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1812 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1814 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1815 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1816 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1817 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1818 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1820 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1821 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1822 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1823 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1824 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1826 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1827 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1828 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1829 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1830 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1832 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1833 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1834 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1835 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1836 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1839 handlerc := make(chan HandlerFunc, 1)
1841 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1848 for i, tt := range tests {
1849 handlerc <- func(w ResponseWriter, r *Request) {
1850 w.Header().Set("Location", ts.URL)
1851 w.WriteHeader(tt.serverStatus)
1854 req, err := NewRequest(tt.method, ts.URL, nil)
1856 t.Errorf("#%d: NewRequest: %v", i, err)
1860 c.CheckRedirect = func(req *Request, via []*Request) error {
1861 if got, want := req.Method, tt.wantMethod; got != want {
1862 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1864 handlerc <- func(rw ResponseWriter, req *Request) {
1865 // TODO: Check that the body is valid when we do 307 and 308 support
1870 res, err := c.Do(req)
1872 t.Errorf("#%d: Response: %v", i, err)
1880 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1881 // Its Read returns readErr and increments *readCalls atomically.
1882 // Its Close returns nil and increments *closeCalls atomically.
1883 type issue18239Body struct {
1889 func (b issue18239Body) Read([]byte) (int, error) {
1890 atomic.AddInt32(b.readCalls, 1)
1894 func (b issue18239Body) Close() error {
1895 atomic.AddInt32(b.closeCalls, 1)
1899 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1900 // if Request.GetBody is not defined.
1901 func TestTransportBodyReadError(t *testing.T) {
1904 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1905 if r.URL.Path == "/ping" {
1908 buf := make([]byte, 1)
1909 n, err := r.Body.Read(buf)
1910 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1914 tr := c.Transport.(*Transport)
1916 // Do one initial successful request to create an idle TCP connection
1917 // for the subsequent request to reuse. (The Transport only retries
1918 // requests on reused connections.)
1919 res, err := c.Get(ts.URL + "/ping")
1925 var readCallsAtomic int32
1926 var closeCallsAtomic int32 // atomic
1927 someErr := errors.New("some body read error")
1928 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1930 req, err := NewRequest("POST", ts.URL, body)
1935 _, err = tr.RoundTrip(req)
1937 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1940 // And verify that our Body wasn't used multiple times, which
1941 // would indicate retries. (as it buggily was during part of
1942 // Go 1.8's dev cycle)
1943 readCalls := atomic.LoadInt32(&readCallsAtomic)
1944 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1946 t.Errorf("read calls = %d; want 1", readCalls)
1948 if closeCalls != 1 {
1949 t.Errorf("close calls = %d; want 1", closeCalls)
1953 type roundTripperWithoutCloseIdle struct{}
1955 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1957 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1959 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1960 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
1962 func TestClientCloseIdleConnections(t *testing.T) {
1963 c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1964 c.CloseIdleConnections() // verify we don't crash at least
1967 var tr RoundTripper = roundTripperWithCloseIdle(func() {
1970 c = &Client{Transport: tr}
1971 c.CloseIdleConnections()
1973 t.Error("not closed")
1977 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1978 errDial := errors.New("not actually dialing")
1980 Timeout: 5 * time.Second,
1981 Transport: &Transport{
1982 DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1983 deadline, ok := ctx.Deadline()
1985 t.Error("no deadline")
1987 t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1993 c.Get("https://example.tld/")
1996 func TestClientDoCanceledVsTimeout_h1(t *testing.T) {
1997 testClientDoCanceledVsTimeout(t, h1Mode)
2000 func TestClientDoCanceledVsTimeout_h2(t *testing.T) {
2001 testClientDoCanceledVsTimeout(t, h2Mode)
2004 // Issue 33545: lock-in the behavior promised by Client.Do's
2005 // docs about request cancellation vs timing out.
2006 func testClientDoCanceledVsTimeout(t *testing.T, h2 bool) {
2008 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
2009 w.Write([]byte("Hello, World!"))
2013 cases := []string{"timeout", "canceled"}
2015 for _, name := range cases {
2016 t.Run(name, func(t *testing.T) {
2017 var ctx context.Context
2019 if name == "timeout" {
2020 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
2022 ctx, cancel = context.WithCancel(context.Background())
2027 req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
2028 _, err := cst.c.Do(req)
2030 t.Fatal("Unexpectedly got a nil error")
2033 ue := err.(*url.Error)
2035 var wantIsTimeout bool
2036 var wantErr error = context.Canceled
2037 if name == "timeout" {
2038 wantErr = context.DeadlineExceeded
2039 wantIsTimeout = true
2041 if g, w := ue.Timeout(), wantIsTimeout; g != w {
2042 t.Fatalf("url.Timeout() = %t, want %t", g, w)
2044 if g, w := ue.Err, wantErr; g != w {
2045 t.Errorf("url.Error.Err = %v; want %v", g, w)
2051 type nilBodyRoundTripper struct{}
2053 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
2055 StatusCode: StatusOK,
2056 Status: StatusText(StatusOK),
2062 func TestClientPopulatesNilResponseBody(t *testing.T) {
2063 c := &Client{Transport: nilBodyRoundTripper{}}
2065 resp, err := c.Get("http://localhost/anything")
2067 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2070 if resp.Body == nil {
2071 t.Fatalf("Client failed to provide a non-nil Body as documented")
2074 if err := resp.Body.Close(); err != nil {
2075 t.Fatalf("error from Close on substitute Response.Body: %v", err)
2079 if b, err := io.ReadAll(resp.Body); err != nil {
2080 t.Errorf("read error from substitute Response.Body: %v", err)
2081 } else if len(b) != 0 {
2082 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2086 // Issue 40382: Client calls Close multiple times on Request.Body.
2087 func TestClientCallsCloseOnlyOnce(t *testing.T) {
2090 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2091 w.WriteHeader(StatusNoContent)
2095 // Issue occurred non-deterministically: needed to occur after a successful
2096 // write (into TCP buffer) but before end of body.
2097 for i := 0; i < 50 && !t.Failed(); i++ {
2098 body := &issue40382Body{t: t, n: 300000}
2099 req, err := NewRequest(MethodPost, cst.ts.URL, body)
2103 resp, err := cst.tr.RoundTrip(req)
2111 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2112 // Its Read reads n bytes before returning io.EOF.
2113 // Its Close returns nil but fails the test if called more than once.
2114 type issue40382Body struct {
2117 closeCallsAtomic int32
2120 func (b *issue40382Body) Read(p []byte) (int, error) {
2136 func (b *issue40382Body) Close() error {
2137 if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2138 b.t.Error("Body closed more than once")
2143 func TestProbeZeroLengthBody(t *testing.T) {
2146 reqc := make(chan struct{})
2147 cst := newClientServerTest(t, false, HandlerFunc(func(w ResponseWriter, r *Request) {
2149 if _, err := io.Copy(w, r.Body); err != nil {
2150 t.Errorf("error copying request body: %v", err)
2155 bodyr, bodyw := io.Pipe()
2157 var wg sync.WaitGroup
2161 req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2162 res, err := cst.c.Do(req)
2163 b, err := io.ReadAll(res.Body)
2172 // Request should be sent after trying to probe the request body for 200ms.
2173 case <-time.After(60 * time.Second):
2174 t.Errorf("request not sent after 60s")
2177 // Write the request body and wait for the request to complete.
2178 const content = "body"
2179 bodyw.Write([]byte(content))
2182 if gotBody != content {
2183 t.Fatalf("server got body %q, want %q", gotBody, content)