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 func TestClient(t *testing.T) { run(t, testClient) }
64 func testClient(t *testing.T, mode testMode) {
65 ts := newClientServerTest(t, mode, robotsTxtHandler).ts
68 r, err := c.Get(ts.URL)
71 b, err = pedanticReadAll(r.Body)
76 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
77 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
81 func TestClientHead(t *testing.T) { run(t, testClientHead) }
82 func testClientHead(t *testing.T, mode testMode) {
83 cst := newClientServerTest(t, mode, robotsTxtHandler)
84 r, err := cst.c.Head(cst.ts.URL)
88 if _, ok := r.Header["Last-Modified"]; !ok {
89 t.Error("Last-Modified header not found.")
93 type recordingTransport struct {
97 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
99 return nil, errors.New("dummy impl")
102 func TestGetRequestFormat(t *testing.T) {
105 tr := &recordingTransport{}
106 client := &Client{Transport: tr}
107 url := "http://dummy.faketld/"
108 client.Get(url) // Note: doesn't hit network
109 if tr.req.Method != "GET" {
110 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
112 if tr.req.URL.String() != url {
113 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
115 if tr.req.Header == nil {
116 t.Errorf("expected non-nil request Header")
120 func TestPostRequestFormat(t *testing.T) {
122 tr := &recordingTransport{}
123 client := &Client{Transport: tr}
125 url := "http://dummy.faketld/"
126 json := `{"key":"value"}`
127 b := strings.NewReader(json)
128 client.Post(url, "application/json", b) // Note: doesn't hit network
130 if tr.req.Method != "POST" {
131 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
133 if tr.req.URL.String() != url {
134 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
136 if tr.req.Header == nil {
137 t.Fatalf("expected non-nil request Header")
140 t.Error("got Close true, want false")
142 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
143 t.Errorf("got ContentLength %d, want %d", g, e)
147 func TestPostFormRequestFormat(t *testing.T) {
149 tr := &recordingTransport{}
150 client := &Client{Transport: tr}
152 urlStr := "http://dummy.faketld/"
153 form := make(url.Values)
154 form.Set("foo", "bar")
155 form.Add("foo", "bar2")
156 form.Set("bar", "baz")
157 client.PostForm(urlStr, form) // Note: doesn't hit network
159 if tr.req.Method != "POST" {
160 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
162 if tr.req.URL.String() != urlStr {
163 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
165 if tr.req.Header == nil {
166 t.Fatalf("expected non-nil request Header")
168 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
169 t.Errorf("got Content-Type %q, want %q", g, e)
172 t.Error("got Close true, want false")
174 // Depending on map iteration, body can be either of these.
175 expectedBody := "foo=bar&foo=bar2&bar=baz"
176 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
177 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
178 t.Errorf("got ContentLength %d, want %d", g, e)
180 bodyb, err := io.ReadAll(tr.req.Body)
182 t.Fatalf("ReadAll on req.Body: %v", err)
184 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
185 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
189 func TestClientRedirects(t *testing.T) { run(t, testClientRedirects) }
190 func testClientRedirects(t *testing.T, mode testMode) {
191 var ts *httptest.Server
192 ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
193 n, _ := strconv.Atoi(r.FormValue("n"))
194 // Test Referer header. (7 is arbitrary position to test at)
196 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
197 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
201 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
204 fmt.Fprintf(w, "n=%d", n)
208 _, err := c.Get(ts.URL)
209 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
210 t.Errorf("with default client Get, expected error %q, got %q", e, g)
213 // HEAD request should also have the ability to follow redirects.
214 _, err = c.Head(ts.URL)
215 if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
216 t.Errorf("with default client Head, expected error %q, got %q", e, g)
219 // Do should also follow redirects.
220 greq, _ := NewRequest("GET", ts.URL, nil)
222 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
223 t.Errorf("with default client Do, expected error %q, got %q", e, g)
226 // Requests with an empty Method should also redirect (Issue 12705)
229 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
230 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
234 var lastVia []*Request
236 c.CheckRedirect = func(req *Request, via []*Request) error {
241 res, err := c.Get(ts.URL)
243 t.Fatalf("Get error: %v", err)
246 finalURL := res.Request.URL.String()
247 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
248 t.Errorf("with custom client, expected error %q, got %q", e, g)
250 if !strings.HasSuffix(finalURL, "/?n=15") {
251 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
253 if e, g := 15, len(lastVia); e != g {
254 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
257 // Test that Request.Cancel is propagated between requests (Issue 14053)
258 creq, _ := NewRequest("HEAD", ts.URL, nil)
259 cancel := make(chan struct{})
261 if _, err := c.Do(creq); err != nil {
265 t.Fatal("didn't see redirect")
267 if lastReq.Cancel != cancel {
268 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
271 checkErr = errors.New("no redirects allowed")
272 res, err = c.Get(ts.URL)
273 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
274 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
277 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
280 if res.Header.Get("Location") == "" {
281 t.Errorf("no Location header in Response")
285 // Tests that Client redirects' contexts are derived from the original request's context.
286 func TestClientRedirectsContext(t *testing.T) { run(t, testClientRedirectsContext) }
287 func testClientRedirectsContext(t *testing.T, mode testMode) {
288 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
289 Redirect(w, r, "/", StatusTemporaryRedirect)
292 ctx, cancel := context.WithCancel(context.Background())
294 c.CheckRedirect = func(req *Request, via []*Request) error {
297 case <-req.Context().Done():
299 case <-time.After(5 * time.Second):
300 return errors.New("redirected request's context never expired after root request canceled")
303 req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
305 ue, ok := err.(*url.Error)
307 t.Fatalf("got error %T; want *url.Error", err)
309 if ue.Err != context.Canceled {
310 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
314 type redirectTest struct {
316 want int // response code
320 func TestPostRedirects(t *testing.T) {
321 postRedirectTests := []redirectTest{
323 {"/?code=301&next=302", 200, "c301"},
324 {"/?code=302&next=302", 200, "c302"},
325 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
326 {"/?code=304", 304, "c304"},
327 {"/?code=305", 305, "c305"},
328 {"/?code=307&next=303,308,302", 200, "c307"},
329 {"/?code=308&next=302,301", 200, "c308"},
330 {"/?code=404", 404, "c404"},
333 wantSegments := []string{
335 `POST /?code=301&next=302 "c301"`,
338 `POST /?code=302&next=302 "c302"`,
341 `POST /?code=303&next=301 "c303wc301"`,
344 `POST /?code=304 "c304"`,
345 `POST /?code=305 "c305"`,
346 `POST /?code=307&next=303,308,302 "c307"`,
347 `POST /?code=303&next=308,302 "c307"`,
348 `GET /?code=308&next=302 ""`,
349 `GET /?code=302 "c307"`,
351 `POST /?code=308&next=302,301 "c308"`,
352 `POST /?code=302&next=301 "c308"`,
355 `POST /?code=404 "c404"`,
357 want := strings.Join(wantSegments, "\n")
358 run(t, func(t *testing.T, mode testMode) {
359 testRedirectsByMethod(t, mode, "POST", postRedirectTests, want)
363 func TestDeleteRedirects(t *testing.T) {
364 deleteRedirectTests := []redirectTest{
366 {"/?code=301&next=302,308", 200, "c301"},
367 {"/?code=302&next=302", 200, "c302"},
368 {"/?code=303", 200, "c303"},
369 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
370 {"/?code=308&next=307", 200, "c308"},
371 {"/?code=404", 404, "c404"},
374 wantSegments := []string{
376 `DELETE /?code=301&next=302,308 "c301"`,
377 `GET /?code=302&next=308 ""`,
380 `DELETE /?code=302&next=302 "c302"`,
383 `DELETE /?code=303 "c303"`,
385 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
386 `DELETE /?code=301&next=308,303,302,304 "c307"`,
387 `GET /?code=308&next=303,302,304 ""`,
388 `GET /?code=303&next=302,304 "c307"`,
389 `GET /?code=302&next=304 ""`,
391 `DELETE /?code=308&next=307 "c308"`,
392 `DELETE /?code=307 "c308"`,
394 `DELETE /?code=404 "c404"`,
396 want := strings.Join(wantSegments, "\n")
397 run(t, func(t *testing.T, mode testMode) {
398 testRedirectsByMethod(t, mode, "DELETE", deleteRedirectTests, want)
402 func testRedirectsByMethod(t *testing.T, mode testMode, method string, table []redirectTest, want string) {
407 var ts *httptest.Server
408 ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
410 slurp, _ := io.ReadAll(r.Body)
411 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
412 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
413 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
417 urlQuery := r.URL.Query()
418 if v := urlQuery.Get("code"); v != "" {
420 if final := urlQuery.Get("next"); final != "" {
421 first, rest, _ := strings.Cut(final, ",")
422 location = fmt.Sprintf("%s?code=%s", location, first)
424 location = fmt.Sprintf("%s&next=%s", location, rest)
427 code, _ := strconv.Atoi(v)
429 w.Header().Set("Location", location)
436 for _, tt := range table {
437 content := tt.redirectBody
438 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
439 req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
440 res, err := c.Do(req)
445 if res.StatusCode != tt.want {
446 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
453 got = strings.TrimSpace(got)
454 want = strings.TrimSpace(want)
457 got, want, lines := removeCommonLines(got, want)
458 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
462 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
464 nl := strings.IndexByte(a, '\n')
466 return a, b, commonLines
469 if !strings.HasPrefix(b, line) {
470 return a, b, commonLines
478 func TestClientRedirectUseResponse(t *testing.T) { run(t, testClientRedirectUseResponse) }
479 func testClientRedirectUseResponse(t *testing.T, mode testMode) {
480 const body = "Hello, world."
481 var ts *httptest.Server
482 ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
483 if strings.Contains(r.URL.Path, "/other") {
484 io.WriteString(w, "wrong body")
486 w.Header().Set("Location", ts.URL+"/other")
487 w.WriteHeader(StatusFound)
488 io.WriteString(w, body)
493 c.CheckRedirect = func(req *Request, via []*Request) error {
494 if req.Response == nil {
495 t.Error("expected non-nil Request.Response")
497 return ErrUseLastResponse
499 res, err := c.Get(ts.URL)
503 if res.StatusCode != StatusFound {
504 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
506 defer res.Body.Close()
507 slurp, err := io.ReadAll(res.Body)
511 if string(slurp) != body {
512 t.Errorf("body = %q; want %q", slurp, body)
516 // Issues 17773 and 49281: don't follow a 3xx if the response doesn't
517 // have a Location header.
518 func TestClientRedirectNoLocation(t *testing.T) { run(t, testClientRedirectNoLocation) }
519 func testClientRedirectNoLocation(t *testing.T, mode testMode) {
520 for _, code := range []int{301, 308} {
521 t.Run(fmt.Sprint(code), func(t *testing.T) {
523 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
524 w.Header().Set("Foo", "Bar")
527 res, err := cst.c.Get(cst.ts.URL)
532 if res.StatusCode != code {
533 t.Errorf("status = %d; want %d", res.StatusCode, code)
535 if got := res.Header.Get("Foo"); got != "Bar" {
536 t.Errorf("Foo header = %q; want Bar", got)
542 // Don't follow a 307/308 if we can't resent the request body.
543 func TestClientRedirect308NoGetBody(t *testing.T) { run(t, testClientRedirect308NoGetBody) }
544 func testClientRedirect308NoGetBody(t *testing.T, mode testMode) {
545 const fakeURL = "https://localhost:1234/" // won't be hit
546 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
547 w.Header().Set("Location", fakeURL)
550 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
555 req.GetBody = nil // so it can't rewind.
556 res, err := c.Do(req)
561 if res.StatusCode != 308 {
562 t.Errorf("status = %d; want %d", res.StatusCode, 308)
564 if got := res.Header.Get("Location"); got != fakeURL {
565 t.Errorf("Location header = %q; want %q", got, fakeURL)
569 var expectedCookies = []*Cookie{
570 {Name: "ChocolateChip", Value: "tasty"},
571 {Name: "First", Value: "Hit"},
572 {Name: "Second", Value: "Hit"},
575 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
576 for _, cookie := range r.Cookies() {
579 if r.URL.Path == "/" {
580 SetCookie(w, expectedCookies[1])
581 Redirect(w, r, "/second", StatusMovedPermanently)
583 SetCookie(w, expectedCookies[2])
584 w.Write([]byte("hello"))
588 func TestClientSendsCookieFromJar(t *testing.T) {
590 tr := &recordingTransport{}
591 client := &Client{Transport: tr}
592 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
593 us := "http://dummy.faketld/"
594 u, _ := url.Parse(us)
595 client.Jar.SetCookies(u, expectedCookies)
597 client.Get(us) // Note: doesn't hit network
598 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
600 client.Head(us) // Note: doesn't hit network
601 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
603 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
604 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
606 client.PostForm(us, url.Values{}) // Note: doesn't hit network
607 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
609 req, _ := NewRequest("GET", us, nil)
610 client.Do(req) // Note: doesn't hit network
611 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
613 req, _ = NewRequest("POST", us, nil)
614 client.Do(req) // Note: doesn't hit network
615 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
618 // Just enough correctness for our redirect tests. Uses the URL.Host as the
619 // scope of all cookies.
620 type TestJar struct {
622 perURL map[string][]*Cookie
625 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
629 j.perURL = make(map[string][]*Cookie)
631 j.perURL[u.Host] = cookies
634 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
637 return j.perURL[u.Host]
640 func TestRedirectCookiesJar(t *testing.T) { run(t, testRedirectCookiesJar) }
641 func testRedirectCookiesJar(t *testing.T, mode testMode) {
642 var ts *httptest.Server
643 ts = newClientServerTest(t, mode, echoCookiesRedirectHandler).ts
646 u, _ := url.Parse(ts.URL)
647 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
648 resp, err := c.Get(ts.URL)
650 t.Fatalf("Get: %v", err)
653 matchReturnedCookies(t, expectedCookies, resp.Cookies())
656 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
657 if len(given) != len(expected) {
658 t.Logf("Received cookies: %v", given)
659 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
661 for _, ec := range expected {
663 for _, c := range given {
664 if ec.Name == c.Name && ec.Value == c.Value {
670 t.Errorf("Missing cookie %v", ec)
675 func TestJarCalls(t *testing.T) { run(t, testJarCalls, []testMode{http1Mode}) }
676 func testJarCalls(t *testing.T, mode testMode) {
677 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
678 pathSuffix := r.RequestURI[1:]
679 if r.RequestURI == "/nosetcookie" {
680 return // don't set cookies for this path
682 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
683 if r.RequestURI == "/" {
684 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
687 jar := new(RecordingJar)
690 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
691 return net.Dial("tcp", ts.Listener.Addr().String())
693 _, err := c.Get("http://firsthost.fake/")
697 _, err = c.Get("http://firsthost.fake/nosetcookie")
701 got := jar.log.String()
702 want := `Cookies("http://firsthost.fake/")
703 SetCookie("http://firsthost.fake/", [name=val])
704 Cookies("http://secondhost.fake/secondpath")
705 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
706 Cookies("http://firsthost.fake/nosetcookie")
709 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
713 // RecordingJar keeps a log of calls made to it, without
714 // tracking any cookies.
715 type RecordingJar struct {
720 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
721 j.logf("SetCookie(%q, %v)\n", u, cookies)
724 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
725 j.logf("Cookies(%q)\n", u)
729 func (j *RecordingJar) logf(format string, args ...any) {
732 fmt.Fprintf(&j.log, format, args...)
735 func TestStreamingGet(t *testing.T) { run(t, testStreamingGet) }
736 func testStreamingGet(t *testing.T, mode testMode) {
737 say := make(chan string)
738 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
740 for str := range say {
747 res, err := c.Get(cst.ts.URL)
752 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
754 n, err := io.ReadFull(res.Body, buf[0:len(str)])
756 t.Fatalf("ReadFull on %q: %v", str, err)
759 t.Fatalf("Receiving %q, only read %d bytes", str, n)
761 got := string(buf[0:n])
763 t.Fatalf("Expected %q, got %q", str, got)
767 _, err = io.ReadFull(res.Body, buf[0:1])
769 t.Fatalf("at end expected EOF, got %v", err)
773 type writeCountingConn struct {
778 func (c *writeCountingConn) Write(p []byte) (int, error) {
780 return c.Conn.Write(p)
783 // TestClientWrites verifies that client requests are buffered and we
784 // don't send a TCP packet per line of the http request + body.
785 func TestClientWrites(t *testing.T) { run(t, testClientWrites, []testMode{http1Mode}) }
786 func testClientWrites(t *testing.T, mode testMode) {
787 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
791 dialer := func(netz string, addr string) (net.Conn, error) {
792 c, err := net.Dial(netz, addr)
794 c = &writeCountingConn{c, &writes}
799 c.Transport.(*Transport).Dial = dialer
801 _, err := c.Get(ts.URL)
806 t.Errorf("Get request did %d Write calls, want 1", writes)
810 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
815 t.Errorf("Post request did %d Write calls, want 1", writes)
819 func TestClientInsecureTransport(t *testing.T) {
820 run(t, testClientInsecureTransport, []testMode{https1Mode, http2Mode})
822 func testClientInsecureTransport(t *testing.T, mode testMode) {
823 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
824 w.Write([]byte("Hello"))
827 errLog := new(strings.Builder)
828 ts.Config.ErrorLog = log.New(errLog, "", 0)
830 // TODO(bradfitz): add tests for skipping hostname checks too?
831 // would require a new cert for testing, and probably
832 // redundant with these tests.
834 for _, insecure := range []bool{true, false} {
835 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
836 InsecureSkipVerify: insecure,
838 res, err := c.Get(ts.URL)
839 if (err == nil) != insecure {
840 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
848 if !strings.Contains(errLog.String(), "TLS handshake error") {
849 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", errLog)
853 func TestClientErrorWithRequestURI(t *testing.T) {
855 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
856 req.RequestURI = "/this/field/is/illegal/and/should/error/"
857 _, err := DefaultClient.Do(req)
859 t.Fatalf("expected an error")
861 if !strings.Contains(err.Error(), "RequestURI") {
862 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
866 func TestClientWithCorrectTLSServerName(t *testing.T) {
867 run(t, testClientWithCorrectTLSServerName, []testMode{https1Mode, http2Mode})
869 func testClientWithCorrectTLSServerName(t *testing.T, mode testMode) {
870 const serverName = "example.com"
871 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
872 if r.TLS.ServerName != serverName {
873 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
878 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
879 if _, err := c.Get(ts.URL); err != nil {
880 t.Fatalf("expected successful TLS connection, got error: %v", err)
884 func TestClientWithIncorrectTLSServerName(t *testing.T) {
885 run(t, testClientWithIncorrectTLSServerName, []testMode{https1Mode, http2Mode})
887 func testClientWithIncorrectTLSServerName(t *testing.T, mode testMode) {
888 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {}))
890 errLog := new(strings.Builder)
891 ts.Config.ErrorLog = log.New(errLog, "", 0)
894 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
895 _, err := c.Get(ts.URL)
897 t.Fatalf("expected an error")
899 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
900 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
904 if !strings.Contains(errLog.String(), "TLS handshake error") {
905 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", errLog)
909 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
912 // tls.Config.ServerName (non-empty, set to "example.com") takes
913 // precedence over "some-other-host.tld" which previously incorrectly
914 // took precedence. We don't actually connect to (or even resolve)
915 // "some-other-host.tld", though, because of the Transport.Dial hook.
917 // The httptest.Server has a cert with "example.com" as its name.
918 func TestTransportUsesTLSConfigServerName(t *testing.T) {
919 run(t, testTransportUsesTLSConfigServerName, []testMode{https1Mode, http2Mode})
921 func testTransportUsesTLSConfigServerName(t *testing.T, mode testMode) {
922 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
923 w.Write([]byte("Hello"))
927 tr := c.Transport.(*Transport)
928 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
929 tr.Dial = func(netw, addr string) (net.Conn, error) {
930 return net.Dial(netw, ts.Listener.Addr().String())
932 res, err := c.Get("https://some-other-host.tld/")
939 func TestResponseSetsTLSConnectionState(t *testing.T) {
940 run(t, testResponseSetsTLSConnectionState, []testMode{https1Mode})
942 func testResponseSetsTLSConnectionState(t *testing.T, mode testMode) {
943 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
944 w.Write([]byte("Hello"))
948 tr := c.Transport.(*Transport)
949 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
950 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
951 tr.Dial = func(netw, addr string) (net.Conn, error) {
952 return net.Dial(netw, ts.Listener.Addr().String())
954 res, err := c.Get("https://example.com/")
958 defer res.Body.Close()
960 t.Fatal("Response didn't set TLS Connection State.")
962 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
963 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
967 // Check that an HTTPS client can interpret a particular TLS error
968 // to determine that the server is speaking HTTP.
969 // See golang.org/issue/11111.
970 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
971 run(t, testHTTPSClientDetectsHTTPServer, []testMode{http1Mode})
973 func testHTTPSClientDetectsHTTPServer(t *testing.T, mode testMode) {
974 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts
975 ts.Config.ErrorLog = quietLog
977 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
978 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
979 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
983 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
984 func TestClientHeadContentLength(t *testing.T) { run(t, testClientHeadContentLength) }
985 func testClientHeadContentLength(t *testing.T, mode testMode) {
986 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
987 if v := r.FormValue("cl"); v != "" {
988 w.Header().Set("Content-Length", v)
999 for _, tt := range tests {
1000 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1001 res, err := cst.c.Do(req)
1005 if res.ContentLength != tt.want {
1006 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1008 bs, err := io.ReadAll(res.Body)
1013 t.Errorf("Unexpected content: %q", bs)
1018 func TestEmptyPasswordAuth(t *testing.T) { run(t, testEmptyPasswordAuth) }
1019 func testEmptyPasswordAuth(t *testing.T, mode testMode) {
1021 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1022 auth := r.Header.Get("Authorization")
1023 if strings.HasPrefix(auth, "Basic ") {
1025 decoded, err := base64.StdEncoding.DecodeString(encoded)
1029 expected := gopher + ":"
1030 s := string(decoded)
1032 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1035 t.Errorf("Invalid auth %q", auth)
1039 req, err := NewRequest("GET", ts.URL, nil)
1043 req.URL.User = url.User(gopher)
1045 resp, err := c.Do(req)
1049 defer resp.Body.Close()
1052 func TestBasicAuth(t *testing.T) {
1054 tr := &recordingTransport{}
1055 client := &Client{Transport: tr}
1057 url := "http://My%20User:My%20Pass@dummy.faketld/"
1058 expected := "My User:My Pass"
1061 if tr.req.Method != "GET" {
1062 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1064 if tr.req.URL.String() != url {
1065 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1067 if tr.req.Header == nil {
1068 t.Fatalf("expected non-nil request Header")
1070 auth := tr.req.Header.Get("Authorization")
1071 if strings.HasPrefix(auth, "Basic ") {
1073 decoded, err := base64.StdEncoding.DecodeString(encoded)
1077 s := string(decoded)
1079 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1082 t.Errorf("Invalid auth %q", auth)
1086 func TestBasicAuthHeadersPreserved(t *testing.T) {
1088 tr := &recordingTransport{}
1089 client := &Client{Transport: tr}
1091 // If Authorization header is provided, username in URL should not override it
1092 url := "http://My%20User@dummy.faketld/"
1093 req, err := NewRequest("GET", url, nil)
1097 req.SetBasicAuth("My User", "My Pass")
1098 expected := "My User:My Pass"
1101 if tr.req.Method != "GET" {
1102 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1104 if tr.req.URL.String() != url {
1105 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1107 if tr.req.Header == nil {
1108 t.Fatalf("expected non-nil request Header")
1110 auth := tr.req.Header.Get("Authorization")
1111 if strings.HasPrefix(auth, "Basic ") {
1113 decoded, err := base64.StdEncoding.DecodeString(encoded)
1117 s := string(decoded)
1119 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1122 t.Errorf("Invalid auth %q", auth)
1127 func TestStripPasswordFromError(t *testing.T) {
1128 client := &Client{Transport: &recordingTransport{}}
1129 testCases := []struct {
1135 desc: "Strip password from error message",
1136 in: "http://user:password@dummy.faketld/",
1137 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1140 desc: "Don't Strip password from domain name",
1141 in: "http://user:password@password.faketld/",
1142 out: `Get "http://user:***@password.faketld/": dummy impl`,
1145 desc: "Don't Strip password from path",
1146 in: "http://user:password@dummy.faketld/password",
1147 out: `Get "http://user:***@dummy.faketld/password": dummy impl`,
1150 desc: "Strip escaped password",
1151 in: "http://user:pa%2Fssword@dummy.faketld/",
1152 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1155 for _, tC := range testCases {
1156 t.Run(tC.desc, func(t *testing.T) {
1157 _, err := client.Get(tC.in)
1158 if err.Error() != tC.out {
1159 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1160 tC.in, tC.out, err.Error())
1166 func TestClientTimeout(t *testing.T) { run(t, testClientTimeout) }
1167 func testClientTimeout(t *testing.T, mode testMode) {
1170 nonce string // a unique per-request string
1171 sawSlowNonce bool // true if the handler saw /slow?nonce=<nonce>
1173 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1175 if r.URL.Path == "/" {
1176 Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
1179 if r.URL.Path == "/slow" {
1181 if r.Form.Get("nonce") == nonce {
1184 t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
1188 w.Write([]byte("Hello"))
1190 <-r.Context().Done()
1195 // Try to trigger a timeout after reading part of the response body.
1196 // The initial timeout is empirically usually long enough on a decently fast
1197 // machine, but if we undershoot we'll retry with exponentially longer
1198 // timeouts until the test either passes or times out completely.
1199 // This keeps the test reasonably fast in the typical case but allows it to
1200 // also eventually succeed on arbitrarily slow machines.
1201 timeout := 10 * time.Millisecond
1203 for ; ; timeout *= 2 {
1205 // The only way we can feasibly hit this while the test is running is if
1206 // the request fails without actually waiting for the timeout to occur.
1207 t.Fatalf("timeout overflow")
1209 if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
1210 t.Fatalf("failed to produce expected timeout before test deadline")
1212 t.Logf("attempting test with timeout %v", timeout)
1213 cst.c.Timeout = timeout
1216 nonce = fmt.Sprint(nextNonce)
1218 sawSlowNonce = false
1220 res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
1222 if strings.Contains(err.Error(), "Client.Timeout") {
1223 // Timed out before handler could respond.
1224 t.Logf("timeout before response received")
1227 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1228 testenv.SkipFlaky(t, 43120)
1237 t.Fatal("handler never got /slow request, but client returned response")
1240 _, err = io.ReadAll(res.Body)
1244 t.Fatal("expected error from ReadAll")
1246 ne, ok := err.(net.Error)
1248 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1249 } else if !ne.Timeout() {
1250 t.Errorf("net.Error.Timeout = false; want true")
1252 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1253 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1254 testenv.SkipFlaky(t, 43120)
1256 t.Errorf("error string = %q; missing timeout substring", got)
1263 // Client.Timeout firing before getting to the body
1264 func TestClientTimeout_Headers(t *testing.T) { run(t, testClientTimeout_Headers) }
1265 func testClientTimeout_Headers(t *testing.T, mode testMode) {
1266 donec := make(chan bool, 1)
1267 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1270 // Note that we use a channel send here and not a close.
1271 // The race detector doesn't know that we're waiting for a timeout
1272 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1273 // with us closing it. If we timed out immediately, we could close the testserver
1274 // before we entered the handler. We're not timing out immediately and there's
1275 // no way we would be done before we entered the handler, but the race detector
1276 // doesn't know this, so synchronize explicitly.
1277 defer func() { donec <- true }()
1279 cst.c.Timeout = 5 * time.Millisecond
1280 res, err := cst.c.Get(cst.ts.URL)
1283 t.Fatal("got response from Get; expected error")
1285 if _, ok := err.(*url.Error); !ok {
1286 t.Fatalf("Got error of type %T; want *url.Error", err)
1288 ne, ok := err.(net.Error)
1290 t.Fatalf("Got error of type %T; want some net.Error", err)
1293 t.Error("net.Error.Timeout = false; want true")
1295 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1296 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1297 testenv.SkipFlaky(t, 43120)
1299 t.Errorf("error string = %q; missing timeout substring", got)
1303 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1305 func TestClientTimeoutCancel(t *testing.T) { run(t, testClientTimeoutCancel) }
1306 func testClientTimeoutCancel(t *testing.T, mode testMode) {
1307 testDone := make(chan struct{})
1308 ctx, cancel := context.WithCancel(context.Background())
1310 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1314 defer close(testDone)
1316 cst.c.Timeout = 1 * time.Hour
1317 req, _ := NewRequest("GET", cst.ts.URL, nil)
1318 req.Cancel = ctx.Done()
1319 res, err := cst.c.Do(req)
1324 _, err = io.Copy(io.Discard, res.Body)
1325 if err != ExportErrRequestCanceled {
1326 t.Fatalf("error = %v; want errRequestCanceled", err)
1330 // Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1331 func TestClientTimeoutDoesNotExpire(t *testing.T) { run(t, testClientTimeoutDoesNotExpire) }
1332 func testClientTimeoutDoesNotExpire(t *testing.T, mode testMode) {
1333 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1334 w.Write([]byte("body"))
1337 cst.c.Timeout = 1 * time.Hour
1338 req, _ := NewRequest("GET", cst.ts.URL, nil)
1339 res, err := cst.c.Do(req)
1343 if _, err = io.Copy(io.Discard, res.Body); err != nil {
1344 t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1346 if err = res.Body.Close(); err != nil {
1347 t.Fatalf("res.Body.Close() = %v, want nil", err)
1351 func TestClientRedirectEatsBody_h1(t *testing.T) { run(t, testClientRedirectEatsBody) }
1352 func testClientRedirectEatsBody(t *testing.T, mode testMode) {
1353 saw := make(chan string, 2)
1354 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1356 if r.URL.Path == "/" {
1357 Redirect(w, r, "/foo", StatusFound) // which includes a body
1361 res, err := cst.c.Get(cst.ts.URL)
1365 _, err = io.ReadAll(res.Body)
1375 t.Fatal("server didn't see a request")
1380 case second = <-saw:
1382 t.Fatal("server didn't see a second request")
1385 if first != second {
1386 t.Fatal("server saw different client ports before & after the redirect")
1390 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1391 type eofReaderFunc func()
1393 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1398 func TestReferer(t *testing.T) {
1400 lastReq, newReq, explicitRef string // from -> to URLs, explicitly set Referer value
1404 {lastReq: "http://gopher@test.com", newReq: "http://link.com", want: "http://test.com"},
1405 {lastReq: "https://gopher@test.com", newReq: "https://link.com", want: "https://test.com"},
1407 // don't send a user and password:
1408 {lastReq: "http://gopher:go@test.com", newReq: "http://link.com", want: "http://test.com"},
1409 {lastReq: "https://gopher:go@test.com", newReq: "https://link.com", want: "https://test.com"},
1412 {lastReq: "http://test.com", newReq: "http://link.com", want: "http://test.com"},
1413 {lastReq: "https://test.com", newReq: "https://link.com", want: "https://test.com"},
1415 // https to http doesn't send a referer:
1416 {lastReq: "https://test.com", newReq: "http://link.com", want: ""},
1417 {lastReq: "https://gopher:go@test.com", newReq: "http://link.com", want: ""},
1419 // https to http should remove an existing referer:
1420 {lastReq: "https://test.com", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
1421 {lastReq: "https://gopher:go@test.com", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
1423 // don't override an existing referer:
1424 {lastReq: "https://test.com", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
1425 {lastReq: "https://gopher:go@test.com", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
1427 for _, tt := range tests {
1428 l, err := url.Parse(tt.lastReq)
1432 n, err := url.Parse(tt.newReq)
1436 r := ExportRefererForURL(l, n, tt.explicitRef)
1438 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1443 // issue15577Tripper returns a Response with a redirect response
1444 // header and doesn't populate its Response.Request field.
1445 type issue15577Tripper struct{}
1447 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1450 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1451 Body: io.NopCloser(strings.NewReader("")),
1456 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1457 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1459 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1460 Transport: issue15577Tripper{},
1462 // Check that this doesn't crash:
1463 c.Get("http://dummy.tld")
1466 // Issue 4800: copy (some) headers when Client follows a redirect.
1467 // Issue 35104: Since both URLs have the same host (localhost)
1468 // but different ports, sensitive headers like Cookie and Authorization
1470 func TestClientCopyHeadersOnRedirect(t *testing.T) { run(t, testClientCopyHeadersOnRedirect) }
1471 func testClientCopyHeadersOnRedirect(t *testing.T, mode testMode) {
1473 ua = "some-agent/1.2"
1477 ts1 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1479 "User-Agent": []string{ua},
1480 "X-Foo": []string{xfoo},
1481 "Referer": []string{ts2URL},
1482 "Accept-Encoding": []string{"gzip"},
1483 "Cookie": []string{"foo=bar"},
1484 "Authorization": []string{"secretpassword"},
1486 if !reflect.DeepEqual(r.Header, want) {
1487 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1490 w.Header().Set("Result", "got errors")
1492 w.Header().Set("Result", "ok")
1495 ts2 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1496 Redirect(w, r, ts1.URL, StatusFound)
1501 c.CheckRedirect = func(r *Request, via []*Request) error {
1503 "User-Agent": []string{ua},
1504 "X-Foo": []string{xfoo},
1505 "Referer": []string{ts2URL},
1506 "Cookie": []string{"foo=bar"},
1507 "Authorization": []string{"secretpassword"},
1509 if !reflect.DeepEqual(r.Header, want) {
1510 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1515 req, _ := NewRequest("GET", ts2.URL, nil)
1516 req.Header.Add("User-Agent", ua)
1517 req.Header.Add("X-Foo", xfoo)
1518 req.Header.Add("Cookie", "foo=bar")
1519 req.Header.Add("Authorization", "secretpassword")
1520 res, err := c.Do(req)
1524 defer res.Body.Close()
1525 if res.StatusCode != 200 {
1528 if got := res.Header.Get("Result"); got != "ok" {
1529 t.Errorf("result = %q; want ok", got)
1533 // Issue 22233: copy host when Client follows a relative redirect.
1534 func TestClientCopyHostOnRedirect(t *testing.T) { run(t, testClientCopyHostOnRedirect) }
1535 func testClientCopyHostOnRedirect(t *testing.T, mode testMode) {
1536 // Virtual hostname: should not receive any request.
1537 virtual := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1538 t.Errorf("Virtual host received request %v", r.URL)
1540 io.WriteString(w, "should not see this response")
1542 defer virtual.Close()
1543 virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1544 virtualHost = strings.TrimPrefix(virtualHost, "https://")
1545 t.Logf("Virtual host is %v", virtualHost)
1547 // Actual hostname: should not receive any request.
1548 const wantBody = "response body"
1551 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1554 // Relative redirect.
1555 if r.Host != virtualHost {
1556 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1560 w.Header().Set("Location", "/hop")
1563 // Absolute redirect.
1564 if r.Host != virtualHost {
1565 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1569 w.Header().Set("Location", tsURL+"/final")
1572 if r.Host != tsHost {
1573 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1578 io.WriteString(w, wantBody)
1580 t.Errorf("Serving unexpected path %q", r.URL.Path)
1585 tsHost = strings.TrimPrefix(ts.URL, "http://")
1586 tsHost = strings.TrimPrefix(tsHost, "https://")
1587 t.Logf("Server host is %v", tsHost)
1590 req, _ := NewRequest("GET", ts.URL, nil)
1591 req.Host = virtualHost
1592 resp, err := c.Do(req)
1596 defer resp.Body.Close()
1597 if resp.StatusCode != 200 {
1598 t.Fatal(resp.Status)
1600 if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1601 t.Errorf("body = %q; want %q", got, wantBody)
1605 // Issue 17494: cookies should be altered when Client follows redirects.
1606 func TestClientAltersCookiesOnRedirect(t *testing.T) { run(t, testClientAltersCookiesOnRedirect) }
1607 func testClientAltersCookiesOnRedirect(t *testing.T, mode testMode) {
1608 cookieMap := func(cs []*Cookie) map[string][]string {
1609 m := make(map[string][]string)
1610 for _, c := range cs {
1611 m[c.Name] = append(m[c.Name], c.Value)
1616 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1617 var want map[string][]string
1618 got := cookieMap(r.Cookies())
1620 c, _ := r.Cookie("Cycle")
1623 want = map[string][]string{
1624 "Cookie1": {"OldValue1a", "OldValue1b"},
1625 "Cookie2": {"OldValue2"},
1626 "Cookie3": {"OldValue3a", "OldValue3b"},
1627 "Cookie4": {"OldValue4"},
1630 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1631 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1632 Redirect(w, r, "/", StatusFound)
1634 want = map[string][]string{
1635 "Cookie1": {"OldValue1a", "OldValue1b"},
1636 "Cookie3": {"OldValue3a", "OldValue3b"},
1637 "Cookie4": {"OldValue4"},
1640 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1641 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1642 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1643 Redirect(w, r, "/", StatusFound)
1645 want = map[string][]string{
1646 "Cookie1": {"OldValue1a", "OldValue1b"},
1647 "Cookie3": {"NewValue3"},
1648 "Cookie4": {"NewValue4"},
1651 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1652 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1653 Redirect(w, r, "/", StatusFound)
1655 want = map[string][]string{
1656 "Cookie1": {"OldValue1a", "OldValue1b"},
1657 "Cookie3": {"NewValue3"},
1658 "Cookie4": {"NewValue4"},
1659 "Cookie5": {"NewValue5"},
1662 // Don't redirect to ensure the loop ends.
1664 t.Errorf("unexpected redirect cycle")
1668 if !reflect.DeepEqual(got, want) {
1669 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1673 jar, _ := cookiejar.New(nil)
1677 u, _ := url.Parse(ts.URL)
1678 req, _ := NewRequest("GET", ts.URL, nil)
1679 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1680 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1681 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1682 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1683 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1684 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1685 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1686 res, err := c.Do(req)
1690 defer res.Body.Close()
1691 if res.StatusCode != 200 {
1696 // Part of Issue 4800
1697 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1704 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1705 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1707 // Sensitive headers:
1708 {"cookie", "http://foo.com/", "http://bar.com/", false},
1709 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1710 {"authorization", "http://foo.com/", "http://bar.com/", false},
1711 {"authorization", "http://foo.com/", "https://foo.com/", true},
1712 {"authorization", "http://foo.com:1234/", "http://foo.com:4321/", true},
1713 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1715 // But subdomains should work:
1716 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1717 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1718 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1719 {"www-authenticate", "http://foo.com/", "https://foo.com/", true},
1720 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1721 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1722 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1723 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1724 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", true},
1726 {"authorization", "http://foo.com/", "http://foo.com/", true},
1727 {"authorization", "http://foo.com/", "http://sub.foo.com/", true},
1728 {"authorization", "http://foo.com/", "http://notfoo.com/", false},
1729 {"authorization", "http://foo.com/", "https://foo.com/", true},
1730 {"authorization", "http://foo.com:80/", "http://foo.com/", true},
1731 {"authorization", "http://foo.com:80/", "http://sub.foo.com/", true},
1732 {"authorization", "http://foo.com:443/", "https://foo.com/", true},
1733 {"authorization", "http://foo.com:443/", "https://sub.foo.com/", true},
1734 {"authorization", "http://foo.com:1234/", "http://foo.com/", true},
1736 for i, tt := range tests {
1737 u0, err := url.Parse(tt.initialURL)
1739 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1742 u1, err := url.Parse(tt.destURL)
1744 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1747 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1749 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1750 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1755 func TestClientRedirectTypes(t *testing.T) { run(t, testClientRedirectTypes) }
1756 func testClientRedirectTypes(t *testing.T, mode testMode) {
1757 tests := [...]struct {
1760 wantMethod string // desired subsequent client method
1762 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1763 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1764 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1765 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1766 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1768 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1769 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1770 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1771 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1772 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1774 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1775 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1776 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1777 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1778 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1780 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1781 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1782 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1783 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1784 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1786 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1787 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1788 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1789 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1790 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1792 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1793 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1794 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1795 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1796 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1799 handlerc := make(chan HandlerFunc, 1)
1801 ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
1807 for i, tt := range tests {
1808 handlerc <- func(w ResponseWriter, r *Request) {
1809 w.Header().Set("Location", ts.URL)
1810 w.WriteHeader(tt.serverStatus)
1813 req, err := NewRequest(tt.method, ts.URL, nil)
1815 t.Errorf("#%d: NewRequest: %v", i, err)
1819 c.CheckRedirect = func(req *Request, via []*Request) error {
1820 if got, want := req.Method, tt.wantMethod; got != want {
1821 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1823 handlerc <- func(rw ResponseWriter, req *Request) {
1824 // TODO: Check that the body is valid when we do 307 and 308 support
1829 res, err := c.Do(req)
1831 t.Errorf("#%d: Response: %v", i, err)
1839 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1840 // Its Read returns readErr and increments *readCalls atomically.
1841 // Its Close returns nil and increments *closeCalls atomically.
1842 type issue18239Body struct {
1848 func (b issue18239Body) Read([]byte) (int, error) {
1849 atomic.AddInt32(b.readCalls, 1)
1853 func (b issue18239Body) Close() error {
1854 atomic.AddInt32(b.closeCalls, 1)
1858 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1859 // if Request.GetBody is not defined.
1860 func TestTransportBodyReadError(t *testing.T) { run(t, testTransportBodyReadError) }
1861 func testTransportBodyReadError(t *testing.T, mode testMode) {
1862 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1863 if r.URL.Path == "/ping" {
1866 buf := make([]byte, 1)
1867 n, err := r.Body.Read(buf)
1868 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1871 tr := c.Transport.(*Transport)
1873 // Do one initial successful request to create an idle TCP connection
1874 // for the subsequent request to reuse. (The Transport only retries
1875 // requests on reused connections.)
1876 res, err := c.Get(ts.URL + "/ping")
1882 var readCallsAtomic int32
1883 var closeCallsAtomic int32 // atomic
1884 someErr := errors.New("some body read error")
1885 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1887 req, err := NewRequest("POST", ts.URL, body)
1892 _, err = tr.RoundTrip(req)
1894 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1897 // And verify that our Body wasn't used multiple times, which
1898 // would indicate retries. (as it buggily was during part of
1899 // Go 1.8's dev cycle)
1900 readCalls := atomic.LoadInt32(&readCallsAtomic)
1901 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1903 t.Errorf("read calls = %d; want 1", readCalls)
1905 if closeCalls != 1 {
1906 t.Errorf("close calls = %d; want 1", closeCalls)
1910 type roundTripperWithoutCloseIdle struct{}
1912 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1914 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1916 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1917 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
1919 func TestClientCloseIdleConnections(t *testing.T) {
1920 c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1921 c.CloseIdleConnections() // verify we don't crash at least
1924 var tr RoundTripper = roundTripperWithCloseIdle(func() {
1927 c = &Client{Transport: tr}
1928 c.CloseIdleConnections()
1930 t.Error("not closed")
1934 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1935 errDial := errors.New("not actually dialing")
1937 Timeout: 5 * time.Second,
1938 Transport: &Transport{
1939 DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1940 deadline, ok := ctx.Deadline()
1942 t.Error("no deadline")
1944 t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1950 c.Get("https://example.tld/")
1953 // Issue 33545: lock-in the behavior promised by Client.Do's
1954 // docs about request cancellation vs timing out.
1955 func TestClientDoCanceledVsTimeout(t *testing.T) { run(t, testClientDoCanceledVsTimeout) }
1956 func testClientDoCanceledVsTimeout(t *testing.T, mode testMode) {
1957 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1958 w.Write([]byte("Hello, World!"))
1961 cases := []string{"timeout", "canceled"}
1963 for _, name := range cases {
1964 t.Run(name, func(t *testing.T) {
1965 var ctx context.Context
1967 if name == "timeout" {
1968 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
1970 ctx, cancel = context.WithCancel(context.Background())
1975 req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
1976 _, err := cst.c.Do(req)
1978 t.Fatal("Unexpectedly got a nil error")
1981 ue := err.(*url.Error)
1983 var wantIsTimeout bool
1984 var wantErr error = context.Canceled
1985 if name == "timeout" {
1986 wantErr = context.DeadlineExceeded
1987 wantIsTimeout = true
1989 if g, w := ue.Timeout(), wantIsTimeout; g != w {
1990 t.Fatalf("url.Timeout() = %t, want %t", g, w)
1992 if g, w := ue.Err, wantErr; g != w {
1993 t.Errorf("url.Error.Err = %v; want %v", g, w)
1999 type nilBodyRoundTripper struct{}
2001 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
2003 StatusCode: StatusOK,
2004 Status: StatusText(StatusOK),
2010 func TestClientPopulatesNilResponseBody(t *testing.T) {
2011 c := &Client{Transport: nilBodyRoundTripper{}}
2013 resp, err := c.Get("http://localhost/anything")
2015 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2018 if resp.Body == nil {
2019 t.Fatalf("Client failed to provide a non-nil Body as documented")
2022 if err := resp.Body.Close(); err != nil {
2023 t.Fatalf("error from Close on substitute Response.Body: %v", err)
2027 if b, err := io.ReadAll(resp.Body); err != nil {
2028 t.Errorf("read error from substitute Response.Body: %v", err)
2029 } else if len(b) != 0 {
2030 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2034 // Issue 40382: Client calls Close multiple times on Request.Body.
2035 func TestClientCallsCloseOnlyOnce(t *testing.T) { run(t, testClientCallsCloseOnlyOnce) }
2036 func testClientCallsCloseOnlyOnce(t *testing.T, mode testMode) {
2037 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2038 w.WriteHeader(StatusNoContent)
2041 // Issue occurred non-deterministically: needed to occur after a successful
2042 // write (into TCP buffer) but before end of body.
2043 for i := 0; i < 50 && !t.Failed(); i++ {
2044 body := &issue40382Body{t: t, n: 300000}
2045 req, err := NewRequest(MethodPost, cst.ts.URL, body)
2049 resp, err := cst.tr.RoundTrip(req)
2057 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2058 // Its Read reads n bytes before returning io.EOF.
2059 // Its Close returns nil but fails the test if called more than once.
2060 type issue40382Body struct {
2063 closeCallsAtomic int32
2066 func (b *issue40382Body) Read(p []byte) (int, error) {
2082 func (b *issue40382Body) Close() error {
2083 if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2084 b.t.Error("Body closed more than once")
2089 func TestProbeZeroLengthBody(t *testing.T) { run(t, testProbeZeroLengthBody) }
2090 func testProbeZeroLengthBody(t *testing.T, mode testMode) {
2091 reqc := make(chan struct{})
2092 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2094 if _, err := io.Copy(w, r.Body); err != nil {
2095 t.Errorf("error copying request body: %v", err)
2099 bodyr, bodyw := io.Pipe()
2101 var wg sync.WaitGroup
2105 req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2106 res, err := cst.c.Do(req)
2107 b, err := io.ReadAll(res.Body)
2116 // Request should be sent after trying to probe the request body for 200ms.
2117 case <-time.After(60 * time.Second):
2118 t.Errorf("request not sent after 60s")
2121 // Write the request body and wait for the request to complete.
2122 const content = "body"
2123 bodyw.Write([]byte(content))
2126 if gotBody != content {
2127 t.Fatalf("server got body %q, want %q", gotBody, content)