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) { run(t, testClient) }
71 func testClient(t *testing.T, mode testMode) {
72 ts := newClientServerTest(t, mode, robotsTxtHandler).ts
75 r, err := c.Get(ts.URL)
78 b, err = pedanticReadAll(r.Body)
83 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
84 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
88 func TestClientHead(t *testing.T) { run(t, testClientHead) }
89 func testClientHead(t *testing.T, mode testMode) {
90 cst := newClientServerTest(t, mode, robotsTxtHandler)
91 r, err := cst.c.Head(cst.ts.URL)
95 if _, ok := r.Header["Last-Modified"]; !ok {
96 t.Error("Last-Modified header not found.")
100 type recordingTransport struct {
104 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
106 return nil, errors.New("dummy impl")
109 func TestGetRequestFormat(t *testing.T) {
112 tr := &recordingTransport{}
113 client := &Client{Transport: tr}
114 url := "http://dummy.faketld/"
115 client.Get(url) // Note: doesn't hit network
116 if tr.req.Method != "GET" {
117 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
119 if tr.req.URL.String() != url {
120 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
122 if tr.req.Header == nil {
123 t.Errorf("expected non-nil request Header")
127 func TestPostRequestFormat(t *testing.T) {
129 tr := &recordingTransport{}
130 client := &Client{Transport: tr}
132 url := "http://dummy.faketld/"
133 json := `{"key":"value"}`
134 b := strings.NewReader(json)
135 client.Post(url, "application/json", b) // Note: doesn't hit network
137 if tr.req.Method != "POST" {
138 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
140 if tr.req.URL.String() != url {
141 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
143 if tr.req.Header == nil {
144 t.Fatalf("expected non-nil request Header")
147 t.Error("got Close true, want false")
149 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
150 t.Errorf("got ContentLength %d, want %d", g, e)
154 func TestPostFormRequestFormat(t *testing.T) {
156 tr := &recordingTransport{}
157 client := &Client{Transport: tr}
159 urlStr := "http://dummy.faketld/"
160 form := make(url.Values)
161 form.Set("foo", "bar")
162 form.Add("foo", "bar2")
163 form.Set("bar", "baz")
164 client.PostForm(urlStr, form) // Note: doesn't hit network
166 if tr.req.Method != "POST" {
167 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
169 if tr.req.URL.String() != urlStr {
170 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
172 if tr.req.Header == nil {
173 t.Fatalf("expected non-nil request Header")
175 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
176 t.Errorf("got Content-Type %q, want %q", g, e)
179 t.Error("got Close true, want false")
181 // Depending on map iteration, body can be either of these.
182 expectedBody := "foo=bar&foo=bar2&bar=baz"
183 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
184 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
185 t.Errorf("got ContentLength %d, want %d", g, e)
187 bodyb, err := io.ReadAll(tr.req.Body)
189 t.Fatalf("ReadAll on req.Body: %v", err)
191 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
192 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
196 func TestClientRedirects(t *testing.T) { run(t, testClientRedirects) }
197 func testClientRedirects(t *testing.T, mode testMode) {
198 var ts *httptest.Server
199 ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
200 n, _ := strconv.Atoi(r.FormValue("n"))
201 // Test Referer header. (7 is arbitrary position to test at)
203 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
204 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
208 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
211 fmt.Fprintf(w, "n=%d", n)
215 _, err := c.Get(ts.URL)
216 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
217 t.Errorf("with default client Get, expected error %q, got %q", e, g)
220 // HEAD request should also have the ability to follow redirects.
221 _, err = c.Head(ts.URL)
222 if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
223 t.Errorf("with default client Head, expected error %q, got %q", e, g)
226 // Do should also follow redirects.
227 greq, _ := NewRequest("GET", ts.URL, nil)
229 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
230 t.Errorf("with default client Do, expected error %q, got %q", e, g)
233 // Requests with an empty Method should also redirect (Issue 12705)
236 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
237 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
241 var lastVia []*Request
243 c.CheckRedirect = func(req *Request, via []*Request) error {
248 res, err := c.Get(ts.URL)
250 t.Fatalf("Get error: %v", err)
253 finalURL := res.Request.URL.String()
254 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
255 t.Errorf("with custom client, expected error %q, got %q", e, g)
257 if !strings.HasSuffix(finalURL, "/?n=15") {
258 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
260 if e, g := 15, len(lastVia); e != g {
261 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
264 // Test that Request.Cancel is propagated between requests (Issue 14053)
265 creq, _ := NewRequest("HEAD", ts.URL, nil)
266 cancel := make(chan struct{})
268 if _, err := c.Do(creq); err != nil {
272 t.Fatal("didn't see redirect")
274 if lastReq.Cancel != cancel {
275 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
278 checkErr = errors.New("no redirects allowed")
279 res, err = c.Get(ts.URL)
280 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
281 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
284 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
287 if res.Header.Get("Location") == "" {
288 t.Errorf("no Location header in Response")
292 // Tests that Client redirects' contexts are derived from the original request's context.
293 func TestClientRedirectsContext(t *testing.T) { run(t, testClientRedirectsContext) }
294 func testClientRedirectsContext(t *testing.T, mode testMode) {
295 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
296 Redirect(w, r, "/", StatusTemporaryRedirect)
299 ctx, cancel := context.WithCancel(context.Background())
301 c.CheckRedirect = func(req *Request, via []*Request) error {
304 case <-req.Context().Done():
306 case <-time.After(5 * time.Second):
307 return errors.New("redirected request's context never expired after root request canceled")
310 req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
312 ue, ok := err.(*url.Error)
314 t.Fatalf("got error %T; want *url.Error", err)
316 if ue.Err != context.Canceled {
317 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
321 type redirectTest struct {
323 want int // response code
327 func TestPostRedirects(t *testing.T) {
328 postRedirectTests := []redirectTest{
330 {"/?code=301&next=302", 200, "c301"},
331 {"/?code=302&next=302", 200, "c302"},
332 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
333 {"/?code=304", 304, "c304"},
334 {"/?code=305", 305, "c305"},
335 {"/?code=307&next=303,308,302", 200, "c307"},
336 {"/?code=308&next=302,301", 200, "c308"},
337 {"/?code=404", 404, "c404"},
340 wantSegments := []string{
342 `POST /?code=301&next=302 "c301"`,
345 `POST /?code=302&next=302 "c302"`,
348 `POST /?code=303&next=301 "c303wc301"`,
351 `POST /?code=304 "c304"`,
352 `POST /?code=305 "c305"`,
353 `POST /?code=307&next=303,308,302 "c307"`,
354 `POST /?code=303&next=308,302 "c307"`,
355 `GET /?code=308&next=302 ""`,
356 `GET /?code=302 "c307"`,
358 `POST /?code=308&next=302,301 "c308"`,
359 `POST /?code=302&next=301 "c308"`,
362 `POST /?code=404 "c404"`,
364 want := strings.Join(wantSegments, "\n")
365 run(t, func(t *testing.T, mode testMode) {
366 testRedirectsByMethod(t, mode, "POST", postRedirectTests, want)
370 func TestDeleteRedirects(t *testing.T) {
371 deleteRedirectTests := []redirectTest{
373 {"/?code=301&next=302,308", 200, "c301"},
374 {"/?code=302&next=302", 200, "c302"},
375 {"/?code=303", 200, "c303"},
376 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
377 {"/?code=308&next=307", 200, "c308"},
378 {"/?code=404", 404, "c404"},
381 wantSegments := []string{
383 `DELETE /?code=301&next=302,308 "c301"`,
384 `GET /?code=302&next=308 ""`,
387 `DELETE /?code=302&next=302 "c302"`,
390 `DELETE /?code=303 "c303"`,
392 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
393 `DELETE /?code=301&next=308,303,302,304 "c307"`,
394 `GET /?code=308&next=303,302,304 ""`,
395 `GET /?code=303&next=302,304 "c307"`,
396 `GET /?code=302&next=304 ""`,
398 `DELETE /?code=308&next=307 "c308"`,
399 `DELETE /?code=307 "c308"`,
401 `DELETE /?code=404 "c404"`,
403 want := strings.Join(wantSegments, "\n")
404 run(t, func(t *testing.T, mode testMode) {
405 testRedirectsByMethod(t, mode, "DELETE", deleteRedirectTests, want)
409 func testRedirectsByMethod(t *testing.T, mode testMode, method string, table []redirectTest, want string) {
414 var ts *httptest.Server
415 ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
417 slurp, _ := io.ReadAll(r.Body)
418 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
419 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
420 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
424 urlQuery := r.URL.Query()
425 if v := urlQuery.Get("code"); v != "" {
427 if final := urlQuery.Get("next"); final != "" {
428 first, rest, _ := strings.Cut(final, ",")
429 location = fmt.Sprintf("%s?code=%s", location, first)
431 location = fmt.Sprintf("%s&next=%s", location, rest)
434 code, _ := strconv.Atoi(v)
436 w.Header().Set("Location", location)
443 for _, tt := range table {
444 content := tt.redirectBody
445 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
446 req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
447 res, err := c.Do(req)
452 if res.StatusCode != tt.want {
453 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
460 got = strings.TrimSpace(got)
461 want = strings.TrimSpace(want)
464 got, want, lines := removeCommonLines(got, want)
465 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
469 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
471 nl := strings.IndexByte(a, '\n')
473 return a, b, commonLines
476 if !strings.HasPrefix(b, line) {
477 return a, b, commonLines
485 func TestClientRedirectUseResponse(t *testing.T) { run(t, testClientRedirectUseResponse) }
486 func testClientRedirectUseResponse(t *testing.T, mode testMode) {
487 const body = "Hello, world."
488 var ts *httptest.Server
489 ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
490 if strings.Contains(r.URL.Path, "/other") {
491 io.WriteString(w, "wrong body")
493 w.Header().Set("Location", ts.URL+"/other")
494 w.WriteHeader(StatusFound)
495 io.WriteString(w, body)
500 c.CheckRedirect = func(req *Request, via []*Request) error {
501 if req.Response == nil {
502 t.Error("expected non-nil Request.Response")
504 return ErrUseLastResponse
506 res, err := c.Get(ts.URL)
510 if res.StatusCode != StatusFound {
511 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
513 defer res.Body.Close()
514 slurp, err := io.ReadAll(res.Body)
518 if string(slurp) != body {
519 t.Errorf("body = %q; want %q", slurp, body)
523 // Issues 17773 and 49281: don't follow a 3xx if the response doesn't
524 // have a Location header.
525 func TestClientRedirectNoLocation(t *testing.T) { run(t, testClientRedirectNoLocation) }
526 func testClientRedirectNoLocation(t *testing.T, mode testMode) {
527 for _, code := range []int{301, 308} {
528 t.Run(fmt.Sprint(code), func(t *testing.T) {
530 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
531 w.Header().Set("Foo", "Bar")
534 res, err := cst.c.Get(cst.ts.URL)
539 if res.StatusCode != code {
540 t.Errorf("status = %d; want %d", res.StatusCode, code)
542 if got := res.Header.Get("Foo"); got != "Bar" {
543 t.Errorf("Foo header = %q; want Bar", got)
549 // Don't follow a 307/308 if we can't resent the request body.
550 func TestClientRedirect308NoGetBody(t *testing.T) { run(t, testClientRedirect308NoGetBody) }
551 func testClientRedirect308NoGetBody(t *testing.T, mode testMode) {
552 const fakeURL = "https://localhost:1234/" // won't be hit
553 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
554 w.Header().Set("Location", fakeURL)
557 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
562 req.GetBody = nil // so it can't rewind.
563 res, err := c.Do(req)
568 if res.StatusCode != 308 {
569 t.Errorf("status = %d; want %d", res.StatusCode, 308)
571 if got := res.Header.Get("Location"); got != fakeURL {
572 t.Errorf("Location header = %q; want %q", got, fakeURL)
576 var expectedCookies = []*Cookie{
577 {Name: "ChocolateChip", Value: "tasty"},
578 {Name: "First", Value: "Hit"},
579 {Name: "Second", Value: "Hit"},
582 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
583 for _, cookie := range r.Cookies() {
586 if r.URL.Path == "/" {
587 SetCookie(w, expectedCookies[1])
588 Redirect(w, r, "/second", StatusMovedPermanently)
590 SetCookie(w, expectedCookies[2])
591 w.Write([]byte("hello"))
595 func TestClientSendsCookieFromJar(t *testing.T) {
597 tr := &recordingTransport{}
598 client := &Client{Transport: tr}
599 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
600 us := "http://dummy.faketld/"
601 u, _ := url.Parse(us)
602 client.Jar.SetCookies(u, expectedCookies)
604 client.Get(us) // Note: doesn't hit network
605 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
607 client.Head(us) // Note: doesn't hit network
608 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
610 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
611 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
613 client.PostForm(us, url.Values{}) // Note: doesn't hit network
614 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
616 req, _ := NewRequest("GET", us, nil)
617 client.Do(req) // Note: doesn't hit network
618 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
620 req, _ = NewRequest("POST", us, nil)
621 client.Do(req) // Note: doesn't hit network
622 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
625 // Just enough correctness for our redirect tests. Uses the URL.Host as the
626 // scope of all cookies.
627 type TestJar struct {
629 perURL map[string][]*Cookie
632 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
636 j.perURL = make(map[string][]*Cookie)
638 j.perURL[u.Host] = cookies
641 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
644 return j.perURL[u.Host]
647 func TestRedirectCookiesJar(t *testing.T) { run(t, testRedirectCookiesJar) }
648 func testRedirectCookiesJar(t *testing.T, mode testMode) {
649 var ts *httptest.Server
650 ts = newClientServerTest(t, mode, echoCookiesRedirectHandler).ts
653 u, _ := url.Parse(ts.URL)
654 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
655 resp, err := c.Get(ts.URL)
657 t.Fatalf("Get: %v", err)
660 matchReturnedCookies(t, expectedCookies, resp.Cookies())
663 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
664 if len(given) != len(expected) {
665 t.Logf("Received cookies: %v", given)
666 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
668 for _, ec := range expected {
670 for _, c := range given {
671 if ec.Name == c.Name && ec.Value == c.Value {
677 t.Errorf("Missing cookie %v", ec)
682 func TestJarCalls(t *testing.T) { run(t, testJarCalls, []testMode{http1Mode}) }
683 func testJarCalls(t *testing.T, mode testMode) {
684 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
685 pathSuffix := r.RequestURI[1:]
686 if r.RequestURI == "/nosetcookie" {
687 return // don't set cookies for this path
689 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
690 if r.RequestURI == "/" {
691 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
694 jar := new(RecordingJar)
697 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
698 return net.Dial("tcp", ts.Listener.Addr().String())
700 _, err := c.Get("http://firsthost.fake/")
704 _, err = c.Get("http://firsthost.fake/nosetcookie")
708 got := jar.log.String()
709 want := `Cookies("http://firsthost.fake/")
710 SetCookie("http://firsthost.fake/", [name=val])
711 Cookies("http://secondhost.fake/secondpath")
712 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
713 Cookies("http://firsthost.fake/nosetcookie")
716 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
720 // RecordingJar keeps a log of calls made to it, without
721 // tracking any cookies.
722 type RecordingJar struct {
727 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
728 j.logf("SetCookie(%q, %v)\n", u, cookies)
731 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
732 j.logf("Cookies(%q)\n", u)
736 func (j *RecordingJar) logf(format string, args ...any) {
739 fmt.Fprintf(&j.log, format, args...)
742 func TestStreamingGet(t *testing.T) { run(t, testStreamingGet) }
743 func testStreamingGet(t *testing.T, mode testMode) {
744 say := make(chan string)
745 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
747 for str := range say {
754 res, err := c.Get(cst.ts.URL)
759 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
761 n, err := io.ReadFull(res.Body, buf[0:len(str)])
763 t.Fatalf("ReadFull on %q: %v", str, err)
766 t.Fatalf("Receiving %q, only read %d bytes", str, n)
768 got := string(buf[0:n])
770 t.Fatalf("Expected %q, got %q", str, got)
774 _, err = io.ReadFull(res.Body, buf[0:1])
776 t.Fatalf("at end expected EOF, got %v", err)
780 type writeCountingConn struct {
785 func (c *writeCountingConn) Write(p []byte) (int, error) {
787 return c.Conn.Write(p)
790 // TestClientWrites verifies that client requests are buffered and we
791 // don't send a TCP packet per line of the http request + body.
792 func TestClientWrites(t *testing.T) { run(t, testClientWrites, []testMode{http1Mode}) }
793 func testClientWrites(t *testing.T, mode testMode) {
794 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
798 dialer := func(netz string, addr string) (net.Conn, error) {
799 c, err := net.Dial(netz, addr)
801 c = &writeCountingConn{c, &writes}
806 c.Transport.(*Transport).Dial = dialer
808 _, err := c.Get(ts.URL)
813 t.Errorf("Get request did %d Write calls, want 1", writes)
817 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
822 t.Errorf("Post request did %d Write calls, want 1", writes)
826 func TestClientInsecureTransport(t *testing.T) {
827 run(t, testClientInsecureTransport, []testMode{https1Mode, http2Mode})
829 func testClientInsecureTransport(t *testing.T, mode testMode) {
830 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
831 w.Write([]byte("Hello"))
833 errc := make(chanWriter, 10) // but only expecting 1
834 ts.Config.ErrorLog = log.New(errc, "", 0)
837 // TODO(bradfitz): add tests for skipping hostname checks too?
838 // would require a new cert for testing, and probably
839 // redundant with these tests.
841 for _, insecure := range []bool{true, false} {
842 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
843 InsecureSkipVerify: insecure,
845 res, err := c.Get(ts.URL)
846 if (err == nil) != insecure {
847 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
856 if !strings.Contains(v, "TLS handshake error") {
857 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
859 case <-time.After(5 * time.Second):
860 t.Errorf("timeout waiting for logged error")
865 func TestClientErrorWithRequestURI(t *testing.T) {
867 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
868 req.RequestURI = "/this/field/is/illegal/and/should/error/"
869 _, err := DefaultClient.Do(req)
871 t.Fatalf("expected an error")
873 if !strings.Contains(err.Error(), "RequestURI") {
874 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
878 func TestClientWithCorrectTLSServerName(t *testing.T) {
879 run(t, testClientWithCorrectTLSServerName, []testMode{https1Mode, http2Mode})
881 func testClientWithCorrectTLSServerName(t *testing.T, mode testMode) {
882 const serverName = "example.com"
883 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
884 if r.TLS.ServerName != serverName {
885 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
890 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
891 if _, err := c.Get(ts.URL); err != nil {
892 t.Fatalf("expected successful TLS connection, got error: %v", err)
896 func TestClientWithIncorrectTLSServerName(t *testing.T) {
897 run(t, testClientWithIncorrectTLSServerName, []testMode{https1Mode, http2Mode})
899 func testClientWithIncorrectTLSServerName(t *testing.T, mode testMode) {
900 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts
901 errc := make(chanWriter, 10) // but only expecting 1
902 ts.Config.ErrorLog = log.New(errc, "", 0)
905 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
906 _, err := c.Get(ts.URL)
908 t.Fatalf("expected an error")
910 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
911 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
915 if !strings.Contains(v, "TLS handshake error") {
916 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
918 case <-time.After(5 * time.Second):
919 t.Errorf("timeout waiting for logged error")
923 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
926 // tls.Config.ServerName (non-empty, set to "example.com") takes
927 // precedence over "some-other-host.tld" which previously incorrectly
928 // took precedence. We don't actually connect to (or even resolve)
929 // "some-other-host.tld", though, because of the Transport.Dial hook.
931 // The httptest.Server has a cert with "example.com" as its name.
932 func TestTransportUsesTLSConfigServerName(t *testing.T) {
933 run(t, testTransportUsesTLSConfigServerName, []testMode{https1Mode, http2Mode})
935 func testTransportUsesTLSConfigServerName(t *testing.T, mode testMode) {
936 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
937 w.Write([]byte("Hello"))
941 tr := c.Transport.(*Transport)
942 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
943 tr.Dial = func(netw, addr string) (net.Conn, error) {
944 return net.Dial(netw, ts.Listener.Addr().String())
946 res, err := c.Get("https://some-other-host.tld/")
953 func TestResponseSetsTLSConnectionState(t *testing.T) {
954 run(t, testResponseSetsTLSConnectionState, []testMode{https1Mode})
956 func testResponseSetsTLSConnectionState(t *testing.T, mode testMode) {
957 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
958 w.Write([]byte("Hello"))
962 tr := c.Transport.(*Transport)
963 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
964 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
965 tr.Dial = func(netw, addr string) (net.Conn, error) {
966 return net.Dial(netw, ts.Listener.Addr().String())
968 res, err := c.Get("https://example.com/")
972 defer res.Body.Close()
974 t.Fatal("Response didn't set TLS Connection State.")
976 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
977 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
981 // Check that an HTTPS client can interpret a particular TLS error
982 // to determine that the server is speaking HTTP.
983 // See golang.org/issue/11111.
984 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
985 run(t, testHTTPSClientDetectsHTTPServer, []testMode{http1Mode})
987 func testHTTPSClientDetectsHTTPServer(t *testing.T, mode testMode) {
988 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts
989 ts.Config.ErrorLog = quietLog
991 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
992 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
993 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
997 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
998 func TestClientHeadContentLength(t *testing.T) { run(t, testClientHeadContentLength) }
999 func testClientHeadContentLength(t *testing.T, mode testMode) {
1000 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1001 if v := r.FormValue("cl"); v != "" {
1002 w.Header().Set("Content-Length", v)
1009 {"/?cl=1234", 1234},
1013 for _, tt := range tests {
1014 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1015 res, err := cst.c.Do(req)
1019 if res.ContentLength != tt.want {
1020 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1022 bs, err := io.ReadAll(res.Body)
1027 t.Errorf("Unexpected content: %q", bs)
1032 func TestEmptyPasswordAuth(t *testing.T) { run(t, testEmptyPasswordAuth) }
1033 func testEmptyPasswordAuth(t *testing.T, mode testMode) {
1035 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1036 auth := r.Header.Get("Authorization")
1037 if strings.HasPrefix(auth, "Basic ") {
1039 decoded, err := base64.StdEncoding.DecodeString(encoded)
1043 expected := gopher + ":"
1044 s := string(decoded)
1046 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1049 t.Errorf("Invalid auth %q", auth)
1053 req, err := NewRequest("GET", ts.URL, nil)
1057 req.URL.User = url.User(gopher)
1059 resp, err := c.Do(req)
1063 defer resp.Body.Close()
1066 func TestBasicAuth(t *testing.T) {
1068 tr := &recordingTransport{}
1069 client := &Client{Transport: tr}
1071 url := "http://My%20User:My%20Pass@dummy.faketld/"
1072 expected := "My User:My Pass"
1075 if tr.req.Method != "GET" {
1076 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1078 if tr.req.URL.String() != url {
1079 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1081 if tr.req.Header == nil {
1082 t.Fatalf("expected non-nil request Header")
1084 auth := tr.req.Header.Get("Authorization")
1085 if strings.HasPrefix(auth, "Basic ") {
1087 decoded, err := base64.StdEncoding.DecodeString(encoded)
1091 s := string(decoded)
1093 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1096 t.Errorf("Invalid auth %q", auth)
1100 func TestBasicAuthHeadersPreserved(t *testing.T) {
1102 tr := &recordingTransport{}
1103 client := &Client{Transport: tr}
1105 // If Authorization header is provided, username in URL should not override it
1106 url := "http://My%20User@dummy.faketld/"
1107 req, err := NewRequest("GET", url, nil)
1111 req.SetBasicAuth("My User", "My Pass")
1112 expected := "My User:My Pass"
1115 if tr.req.Method != "GET" {
1116 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1118 if tr.req.URL.String() != url {
1119 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1121 if tr.req.Header == nil {
1122 t.Fatalf("expected non-nil request Header")
1124 auth := tr.req.Header.Get("Authorization")
1125 if strings.HasPrefix(auth, "Basic ") {
1127 decoded, err := base64.StdEncoding.DecodeString(encoded)
1131 s := string(decoded)
1133 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1136 t.Errorf("Invalid auth %q", auth)
1141 func TestStripPasswordFromError(t *testing.T) {
1142 client := &Client{Transport: &recordingTransport{}}
1143 testCases := []struct {
1149 desc: "Strip password from error message",
1150 in: "http://user:password@dummy.faketld/",
1151 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1154 desc: "Don't Strip password from domain name",
1155 in: "http://user:password@password.faketld/",
1156 out: `Get "http://user:***@password.faketld/": dummy impl`,
1159 desc: "Don't Strip password from path",
1160 in: "http://user:password@dummy.faketld/password",
1161 out: `Get "http://user:***@dummy.faketld/password": dummy impl`,
1164 desc: "Strip escaped password",
1165 in: "http://user:pa%2Fssword@dummy.faketld/",
1166 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1169 for _, tC := range testCases {
1170 t.Run(tC.desc, func(t *testing.T) {
1171 _, err := client.Get(tC.in)
1172 if err.Error() != tC.out {
1173 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1174 tC.in, tC.out, err.Error())
1180 func TestClientTimeout(t *testing.T) { run(t, testClientTimeout) }
1181 func testClientTimeout(t *testing.T, mode testMode) {
1184 nonce string // a unique per-request string
1185 sawSlowNonce bool // true if the handler saw /slow?nonce=<nonce>
1187 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1189 if r.URL.Path == "/" {
1190 Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
1193 if r.URL.Path == "/slow" {
1195 if r.Form.Get("nonce") == nonce {
1198 t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
1202 w.Write([]byte("Hello"))
1204 <-r.Context().Done()
1209 // Try to trigger a timeout after reading part of the response body.
1210 // The initial timeout is emprically usually long enough on a decently fast
1211 // machine, but if we undershoot we'll retry with exponentially longer
1212 // timeouts until the test either passes or times out completely.
1213 // This keeps the test reasonably fast in the typical case but allows it to
1214 // also eventually succeed on arbitrarily slow machines.
1215 timeout := 10 * time.Millisecond
1217 for ; ; timeout *= 2 {
1219 // The only way we can feasibly hit this while the test is running is if
1220 // the request fails without actually waiting for the timeout to occur.
1221 t.Fatalf("timeout overflow")
1223 if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
1224 t.Fatalf("failed to produce expected timeout before test deadline")
1226 t.Logf("attempting test with timeout %v", timeout)
1227 cst.c.Timeout = timeout
1230 nonce = fmt.Sprint(nextNonce)
1232 sawSlowNonce = false
1234 res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
1236 if strings.Contains(err.Error(), "Client.Timeout") {
1237 // Timed out before handler could respond.
1238 t.Logf("timeout before response received")
1241 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1242 testenv.SkipFlaky(t, 43120)
1251 t.Fatal("handler never got /slow request, but client returned response")
1254 _, err = io.ReadAll(res.Body)
1258 t.Fatal("expected error from ReadAll")
1260 ne, ok := err.(net.Error)
1262 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1263 } else if !ne.Timeout() {
1264 t.Errorf("net.Error.Timeout = false; want true")
1266 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1267 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1268 testenv.SkipFlaky(t, 43120)
1270 t.Errorf("error string = %q; missing timeout substring", got)
1277 // Client.Timeout firing before getting to the body
1278 func TestClientTimeout_Headers(t *testing.T) { run(t, testClientTimeout_Headers) }
1279 func testClientTimeout_Headers(t *testing.T, mode testMode) {
1280 donec := make(chan bool, 1)
1281 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1284 // Note that we use a channel send here and not a close.
1285 // The race detector doesn't know that we're waiting for a timeout
1286 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1287 // with us closing it. If we timed out immediately, we could close the testserver
1288 // before we entered the handler. We're not timing out immediately and there's
1289 // no way we would be done before we entered the handler, but the race detector
1290 // doesn't know this, so synchronize explicitly.
1291 defer func() { donec <- true }()
1293 cst.c.Timeout = 5 * time.Millisecond
1294 res, err := cst.c.Get(cst.ts.URL)
1297 t.Fatal("got response from Get; expected error")
1299 if _, ok := err.(*url.Error); !ok {
1300 t.Fatalf("Got error of type %T; want *url.Error", err)
1302 ne, ok := err.(net.Error)
1304 t.Fatalf("Got error of type %T; want some net.Error", err)
1307 t.Error("net.Error.Timeout = false; want true")
1309 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1310 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1311 testenv.SkipFlaky(t, 43120)
1313 t.Errorf("error string = %q; missing timeout substring", got)
1317 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1319 func TestClientTimeoutCancel(t *testing.T) { run(t, testClientTimeoutCancel) }
1320 func testClientTimeoutCancel(t *testing.T, mode testMode) {
1321 testDone := make(chan struct{})
1322 ctx, cancel := context.WithCancel(context.Background())
1324 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1328 defer close(testDone)
1330 cst.c.Timeout = 1 * time.Hour
1331 req, _ := NewRequest("GET", cst.ts.URL, nil)
1332 req.Cancel = ctx.Done()
1333 res, err := cst.c.Do(req)
1338 _, err = io.Copy(io.Discard, res.Body)
1339 if err != ExportErrRequestCanceled {
1340 t.Fatalf("error = %v; want errRequestCanceled", err)
1344 // Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1345 func TestClientTimeoutDoesNotExpire(t *testing.T) { run(t, testClientTimeoutDoesNotExpire) }
1346 func testClientTimeoutDoesNotExpire(t *testing.T, mode testMode) {
1347 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1348 w.Write([]byte("body"))
1351 cst.c.Timeout = 1 * time.Hour
1352 req, _ := NewRequest("GET", cst.ts.URL, nil)
1353 res, err := cst.c.Do(req)
1357 if _, err = io.Copy(io.Discard, res.Body); err != nil {
1358 t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1360 if err = res.Body.Close(); err != nil {
1361 t.Fatalf("res.Body.Close() = %v, want nil", err)
1365 func TestClientRedirectEatsBody_h1(t *testing.T) { run(t, testClientRedirectEatsBody) }
1366 func testClientRedirectEatsBody(t *testing.T, mode testMode) {
1367 saw := make(chan string, 2)
1368 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1370 if r.URL.Path == "/" {
1371 Redirect(w, r, "/foo", StatusFound) // which includes a body
1375 res, err := cst.c.Get(cst.ts.URL)
1379 _, err = io.ReadAll(res.Body)
1389 t.Fatal("server didn't see a request")
1394 case second = <-saw:
1396 t.Fatal("server didn't see a second request")
1399 if first != second {
1400 t.Fatal("server saw different client ports before & after the redirect")
1404 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1405 type eofReaderFunc func()
1407 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1412 func TestReferer(t *testing.T) {
1414 lastReq, newReq string // from -> to URLs
1418 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1419 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1421 // don't send a user and password:
1422 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1423 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1426 {"http://test.com", "http://link.com", "http://test.com"},
1427 {"https://test.com", "https://link.com", "https://test.com"},
1429 // https to http doesn't send a referer:
1430 {"https://test.com", "http://link.com", ""},
1431 {"https://gopher:go@test.com", "http://link.com", ""},
1433 for _, tt := range tests {
1434 l, err := url.Parse(tt.lastReq)
1438 n, err := url.Parse(tt.newReq)
1442 r := ExportRefererForURL(l, n)
1444 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1449 // issue15577Tripper returns a Response with a redirect response
1450 // header and doesn't populate its Response.Request field.
1451 type issue15577Tripper struct{}
1453 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1456 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1457 Body: io.NopCloser(strings.NewReader("")),
1462 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1463 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1465 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1466 Transport: issue15577Tripper{},
1468 // Check that this doesn't crash:
1469 c.Get("http://dummy.tld")
1472 // Issue 4800: copy (some) headers when Client follows a redirect.
1473 // Issue 35104: Since both URLs have the same host (localhost)
1474 // but different ports, sensitive headers like Cookie and Authorization
1476 func TestClientCopyHeadersOnRedirect(t *testing.T) { run(t, testClientCopyHeadersOnRedirect) }
1477 func testClientCopyHeadersOnRedirect(t *testing.T, mode testMode) {
1479 ua = "some-agent/1.2"
1483 ts1 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1485 "User-Agent": []string{ua},
1486 "X-Foo": []string{xfoo},
1487 "Referer": []string{ts2URL},
1488 "Accept-Encoding": []string{"gzip"},
1489 "Cookie": []string{"foo=bar"},
1490 "Authorization": []string{"secretpassword"},
1492 if !reflect.DeepEqual(r.Header, want) {
1493 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1496 w.Header().Set("Result", "got errors")
1498 w.Header().Set("Result", "ok")
1501 ts2 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1502 Redirect(w, r, ts1.URL, StatusFound)
1507 c.CheckRedirect = func(r *Request, via []*Request) error {
1509 "User-Agent": []string{ua},
1510 "X-Foo": []string{xfoo},
1511 "Referer": []string{ts2URL},
1512 "Cookie": []string{"foo=bar"},
1513 "Authorization": []string{"secretpassword"},
1515 if !reflect.DeepEqual(r.Header, want) {
1516 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1521 req, _ := NewRequest("GET", ts2.URL, nil)
1522 req.Header.Add("User-Agent", ua)
1523 req.Header.Add("X-Foo", xfoo)
1524 req.Header.Add("Cookie", "foo=bar")
1525 req.Header.Add("Authorization", "secretpassword")
1526 res, err := c.Do(req)
1530 defer res.Body.Close()
1531 if res.StatusCode != 200 {
1534 if got := res.Header.Get("Result"); got != "ok" {
1535 t.Errorf("result = %q; want ok", got)
1539 // Issue 22233: copy host when Client follows a relative redirect.
1540 func TestClientCopyHostOnRedirect(t *testing.T) { run(t, testClientCopyHostOnRedirect) }
1541 func testClientCopyHostOnRedirect(t *testing.T, mode testMode) {
1542 // Virtual hostname: should not receive any request.
1543 virtual := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1544 t.Errorf("Virtual host received request %v", r.URL)
1546 io.WriteString(w, "should not see this response")
1548 defer virtual.Close()
1549 virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1550 virtualHost = strings.TrimPrefix(virtualHost, "https://")
1551 t.Logf("Virtual host is %v", virtualHost)
1553 // Actual hostname: should not receive any request.
1554 const wantBody = "response body"
1557 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1560 // Relative redirect.
1561 if r.Host != virtualHost {
1562 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1566 w.Header().Set("Location", "/hop")
1569 // Absolute redirect.
1570 if r.Host != virtualHost {
1571 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1575 w.Header().Set("Location", tsURL+"/final")
1578 if r.Host != tsHost {
1579 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1584 io.WriteString(w, wantBody)
1586 t.Errorf("Serving unexpected path %q", r.URL.Path)
1591 tsHost = strings.TrimPrefix(ts.URL, "http://")
1592 tsHost = strings.TrimPrefix(tsHost, "https://")
1593 t.Logf("Server host is %v", tsHost)
1596 req, _ := NewRequest("GET", ts.URL, nil)
1597 req.Host = virtualHost
1598 resp, err := c.Do(req)
1602 defer resp.Body.Close()
1603 if resp.StatusCode != 200 {
1604 t.Fatal(resp.Status)
1606 if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1607 t.Errorf("body = %q; want %q", got, wantBody)
1611 // Issue 17494: cookies should be altered when Client follows redirects.
1612 func TestClientAltersCookiesOnRedirect(t *testing.T) { run(t, testClientAltersCookiesOnRedirect) }
1613 func testClientAltersCookiesOnRedirect(t *testing.T, mode testMode) {
1614 cookieMap := func(cs []*Cookie) map[string][]string {
1615 m := make(map[string][]string)
1616 for _, c := range cs {
1617 m[c.Name] = append(m[c.Name], c.Value)
1622 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1623 var want map[string][]string
1624 got := cookieMap(r.Cookies())
1626 c, _ := r.Cookie("Cycle")
1629 want = map[string][]string{
1630 "Cookie1": {"OldValue1a", "OldValue1b"},
1631 "Cookie2": {"OldValue2"},
1632 "Cookie3": {"OldValue3a", "OldValue3b"},
1633 "Cookie4": {"OldValue4"},
1636 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1637 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1638 Redirect(w, r, "/", StatusFound)
1640 want = map[string][]string{
1641 "Cookie1": {"OldValue1a", "OldValue1b"},
1642 "Cookie3": {"OldValue3a", "OldValue3b"},
1643 "Cookie4": {"OldValue4"},
1646 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1647 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1648 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1649 Redirect(w, r, "/", StatusFound)
1651 want = map[string][]string{
1652 "Cookie1": {"OldValue1a", "OldValue1b"},
1653 "Cookie3": {"NewValue3"},
1654 "Cookie4": {"NewValue4"},
1657 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1658 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1659 Redirect(w, r, "/", StatusFound)
1661 want = map[string][]string{
1662 "Cookie1": {"OldValue1a", "OldValue1b"},
1663 "Cookie3": {"NewValue3"},
1664 "Cookie4": {"NewValue4"},
1665 "Cookie5": {"NewValue5"},
1668 // Don't redirect to ensure the loop ends.
1670 t.Errorf("unexpected redirect cycle")
1674 if !reflect.DeepEqual(got, want) {
1675 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1679 jar, _ := cookiejar.New(nil)
1683 u, _ := url.Parse(ts.URL)
1684 req, _ := NewRequest("GET", ts.URL, nil)
1685 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1686 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1687 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1688 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1689 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1690 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1691 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1692 res, err := c.Do(req)
1696 defer res.Body.Close()
1697 if res.StatusCode != 200 {
1702 // Part of Issue 4800
1703 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1710 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1711 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1713 // Sensitive headers:
1714 {"cookie", "http://foo.com/", "http://bar.com/", false},
1715 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1716 {"authorization", "http://foo.com/", "http://bar.com/", false},
1717 {"authorization", "http://foo.com/", "https://foo.com/", true},
1718 {"authorization", "http://foo.com:1234/", "http://foo.com:4321/", true},
1719 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1721 // But subdomains should work:
1722 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1723 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1724 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1725 {"www-authenticate", "http://foo.com/", "https://foo.com/", true},
1726 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1727 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1728 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1729 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1730 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", true},
1732 {"authorization", "http://foo.com/", "http://foo.com/", true},
1733 {"authorization", "http://foo.com/", "http://sub.foo.com/", true},
1734 {"authorization", "http://foo.com/", "http://notfoo.com/", false},
1735 {"authorization", "http://foo.com/", "https://foo.com/", true},
1736 {"authorization", "http://foo.com:80/", "http://foo.com/", true},
1737 {"authorization", "http://foo.com:80/", "http://sub.foo.com/", true},
1738 {"authorization", "http://foo.com:443/", "https://foo.com/", true},
1739 {"authorization", "http://foo.com:443/", "https://sub.foo.com/", true},
1740 {"authorization", "http://foo.com:1234/", "http://foo.com/", true},
1742 for i, tt := range tests {
1743 u0, err := url.Parse(tt.initialURL)
1745 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1748 u1, err := url.Parse(tt.destURL)
1750 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1753 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1755 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1756 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1761 func TestClientRedirectTypes(t *testing.T) { run(t, testClientRedirectTypes) }
1762 func testClientRedirectTypes(t *testing.T, mode testMode) {
1763 tests := [...]struct {
1766 wantMethod string // desired subsequent client method
1768 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1769 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1770 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1771 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1772 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1774 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1775 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1776 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1777 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1778 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1780 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1781 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1782 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1783 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1784 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1786 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1787 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1788 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1789 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1790 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1792 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1793 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1794 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1795 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1796 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1798 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1799 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1800 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1801 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1802 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1805 handlerc := make(chan HandlerFunc, 1)
1807 ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
1813 for i, tt := range tests {
1814 handlerc <- func(w ResponseWriter, r *Request) {
1815 w.Header().Set("Location", ts.URL)
1816 w.WriteHeader(tt.serverStatus)
1819 req, err := NewRequest(tt.method, ts.URL, nil)
1821 t.Errorf("#%d: NewRequest: %v", i, err)
1825 c.CheckRedirect = func(req *Request, via []*Request) error {
1826 if got, want := req.Method, tt.wantMethod; got != want {
1827 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1829 handlerc <- func(rw ResponseWriter, req *Request) {
1830 // TODO: Check that the body is valid when we do 307 and 308 support
1835 res, err := c.Do(req)
1837 t.Errorf("#%d: Response: %v", i, err)
1845 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1846 // Its Read returns readErr and increments *readCalls atomically.
1847 // Its Close returns nil and increments *closeCalls atomically.
1848 type issue18239Body struct {
1854 func (b issue18239Body) Read([]byte) (int, error) {
1855 atomic.AddInt32(b.readCalls, 1)
1859 func (b issue18239Body) Close() error {
1860 atomic.AddInt32(b.closeCalls, 1)
1864 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1865 // if Request.GetBody is not defined.
1866 func TestTransportBodyReadError(t *testing.T) { run(t, testTransportBodyReadError) }
1867 func testTransportBodyReadError(t *testing.T, mode testMode) {
1868 ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1869 if r.URL.Path == "/ping" {
1872 buf := make([]byte, 1)
1873 n, err := r.Body.Read(buf)
1874 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1877 tr := c.Transport.(*Transport)
1879 // Do one initial successful request to create an idle TCP connection
1880 // for the subsequent request to reuse. (The Transport only retries
1881 // requests on reused connections.)
1882 res, err := c.Get(ts.URL + "/ping")
1888 var readCallsAtomic int32
1889 var closeCallsAtomic int32 // atomic
1890 someErr := errors.New("some body read error")
1891 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1893 req, err := NewRequest("POST", ts.URL, body)
1898 _, err = tr.RoundTrip(req)
1900 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1903 // And verify that our Body wasn't used multiple times, which
1904 // would indicate retries. (as it buggily was during part of
1905 // Go 1.8's dev cycle)
1906 readCalls := atomic.LoadInt32(&readCallsAtomic)
1907 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1909 t.Errorf("read calls = %d; want 1", readCalls)
1911 if closeCalls != 1 {
1912 t.Errorf("close calls = %d; want 1", closeCalls)
1916 type roundTripperWithoutCloseIdle struct{}
1918 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1920 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1922 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1923 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
1925 func TestClientCloseIdleConnections(t *testing.T) {
1926 c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1927 c.CloseIdleConnections() // verify we don't crash at least
1930 var tr RoundTripper = roundTripperWithCloseIdle(func() {
1933 c = &Client{Transport: tr}
1934 c.CloseIdleConnections()
1936 t.Error("not closed")
1940 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1941 errDial := errors.New("not actually dialing")
1943 Timeout: 5 * time.Second,
1944 Transport: &Transport{
1945 DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1946 deadline, ok := ctx.Deadline()
1948 t.Error("no deadline")
1950 t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1956 c.Get("https://example.tld/")
1959 // Issue 33545: lock-in the behavior promised by Client.Do's
1960 // docs about request cancellation vs timing out.
1961 func TestClientDoCanceledVsTimeout(t *testing.T) { run(t, testClientDoCanceledVsTimeout) }
1962 func testClientDoCanceledVsTimeout(t *testing.T, mode testMode) {
1963 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1964 w.Write([]byte("Hello, World!"))
1967 cases := []string{"timeout", "canceled"}
1969 for _, name := range cases {
1970 t.Run(name, func(t *testing.T) {
1971 var ctx context.Context
1973 if name == "timeout" {
1974 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
1976 ctx, cancel = context.WithCancel(context.Background())
1981 req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
1982 _, err := cst.c.Do(req)
1984 t.Fatal("Unexpectedly got a nil error")
1987 ue := err.(*url.Error)
1989 var wantIsTimeout bool
1990 var wantErr error = context.Canceled
1991 if name == "timeout" {
1992 wantErr = context.DeadlineExceeded
1993 wantIsTimeout = true
1995 if g, w := ue.Timeout(), wantIsTimeout; g != w {
1996 t.Fatalf("url.Timeout() = %t, want %t", g, w)
1998 if g, w := ue.Err, wantErr; g != w {
1999 t.Errorf("url.Error.Err = %v; want %v", g, w)
2005 type nilBodyRoundTripper struct{}
2007 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
2009 StatusCode: StatusOK,
2010 Status: StatusText(StatusOK),
2016 func TestClientPopulatesNilResponseBody(t *testing.T) {
2017 c := &Client{Transport: nilBodyRoundTripper{}}
2019 resp, err := c.Get("http://localhost/anything")
2021 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2024 if resp.Body == nil {
2025 t.Fatalf("Client failed to provide a non-nil Body as documented")
2028 if err := resp.Body.Close(); err != nil {
2029 t.Fatalf("error from Close on substitute Response.Body: %v", err)
2033 if b, err := io.ReadAll(resp.Body); err != nil {
2034 t.Errorf("read error from substitute Response.Body: %v", err)
2035 } else if len(b) != 0 {
2036 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2040 // Issue 40382: Client calls Close multiple times on Request.Body.
2041 func TestClientCallsCloseOnlyOnce(t *testing.T) { run(t, testClientCallsCloseOnlyOnce) }
2042 func testClientCallsCloseOnlyOnce(t *testing.T, mode testMode) {
2043 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2044 w.WriteHeader(StatusNoContent)
2047 // Issue occurred non-deterministically: needed to occur after a successful
2048 // write (into TCP buffer) but before end of body.
2049 for i := 0; i < 50 && !t.Failed(); i++ {
2050 body := &issue40382Body{t: t, n: 300000}
2051 req, err := NewRequest(MethodPost, cst.ts.URL, body)
2055 resp, err := cst.tr.RoundTrip(req)
2063 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2064 // Its Read reads n bytes before returning io.EOF.
2065 // Its Close returns nil but fails the test if called more than once.
2066 type issue40382Body struct {
2069 closeCallsAtomic int32
2072 func (b *issue40382Body) Read(p []byte) (int, error) {
2088 func (b *issue40382Body) Close() error {
2089 if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2090 b.t.Error("Body closed more than once")
2095 func TestProbeZeroLengthBody(t *testing.T) { run(t, testProbeZeroLengthBody) }
2096 func testProbeZeroLengthBody(t *testing.T, mode testMode) {
2097 reqc := make(chan struct{})
2098 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2100 if _, err := io.Copy(w, r.Body); err != nil {
2101 t.Errorf("error copying request body: %v", err)
2105 bodyr, bodyw := io.Pipe()
2107 var wg sync.WaitGroup
2111 req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2112 res, err := cst.c.Do(req)
2113 b, err := io.ReadAll(res.Body)
2122 // Request should be sent after trying to probe the request body for 200ms.
2123 case <-time.After(60 * time.Second):
2124 t.Errorf("request not sent after 60s")
2127 // Write the request body and wait for the request to complete.
2128 const content = "body"
2129 bodyw.Write([]byte(content))
2132 if gotBody != content {
2133 t.Fatalf("server got body %q, want %q", gotBody, content)