1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
32 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
33 w.Header().Set("Last-Modified", "sometime")
34 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
37 // pedanticReadAll works like io.ReadAll but additionally
38 // verifies that r obeys the documented io.Reader contract.
39 func pedanticReadAll(r io.Reader) (b []byte, err error) {
44 if n == 0 && err == nil {
45 return nil, fmt.Errorf("Read: n=0 with err=nil")
47 b = append(b, buf[:n]...)
50 if n != 0 || err != io.EOF {
51 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
61 type chanWriter chan string
63 func (w chanWriter) Write(p []byte) (n int, err error) {
68 func TestClient(t *testing.T) {
71 ts := httptest.NewServer(robotsTxtHandler)
75 r, err := c.Get(ts.URL)
78 b, err = pedanticReadAll(r.Body)
83 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
84 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
88 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
89 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
91 func testClientHead(t *testing.T, h2 bool) {
93 cst := newClientServerTest(t, h2, robotsTxtHandler)
96 r, err := cst.c.Head(cst.ts.URL)
100 if _, ok := r.Header["Last-Modified"]; !ok {
101 t.Error("Last-Modified header not found.")
105 type recordingTransport struct {
109 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
111 return nil, errors.New("dummy impl")
114 func TestGetRequestFormat(t *testing.T) {
117 tr := &recordingTransport{}
118 client := &Client{Transport: tr}
119 url := "http://dummy.faketld/"
120 client.Get(url) // Note: doesn't hit network
121 if tr.req.Method != "GET" {
122 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
124 if tr.req.URL.String() != url {
125 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
127 if tr.req.Header == nil {
128 t.Errorf("expected non-nil request Header")
132 func TestPostRequestFormat(t *testing.T) {
134 tr := &recordingTransport{}
135 client := &Client{Transport: tr}
137 url := "http://dummy.faketld/"
138 json := `{"key":"value"}`
139 b := strings.NewReader(json)
140 client.Post(url, "application/json", b) // Note: doesn't hit network
142 if tr.req.Method != "POST" {
143 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
145 if tr.req.URL.String() != url {
146 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
148 if tr.req.Header == nil {
149 t.Fatalf("expected non-nil request Header")
152 t.Error("got Close true, want false")
154 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
155 t.Errorf("got ContentLength %d, want %d", g, e)
159 func TestPostFormRequestFormat(t *testing.T) {
161 tr := &recordingTransport{}
162 client := &Client{Transport: tr}
164 urlStr := "http://dummy.faketld/"
165 form := make(url.Values)
166 form.Set("foo", "bar")
167 form.Add("foo", "bar2")
168 form.Set("bar", "baz")
169 client.PostForm(urlStr, form) // Note: doesn't hit network
171 if tr.req.Method != "POST" {
172 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
174 if tr.req.URL.String() != urlStr {
175 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
177 if tr.req.Header == nil {
178 t.Fatalf("expected non-nil request Header")
180 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
181 t.Errorf("got Content-Type %q, want %q", g, e)
184 t.Error("got Close true, want false")
186 // Depending on map iteration, body can be either of these.
187 expectedBody := "foo=bar&foo=bar2&bar=baz"
188 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
189 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
190 t.Errorf("got ContentLength %d, want %d", g, e)
192 bodyb, err := io.ReadAll(tr.req.Body)
194 t.Fatalf("ReadAll on req.Body: %v", err)
196 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
197 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
201 func TestClientRedirects(t *testing.T) {
204 var ts *httptest.Server
205 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
206 n, _ := strconv.Atoi(r.FormValue("n"))
207 // Test Referer header. (7 is arbitrary position to test at)
209 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
210 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
214 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
217 fmt.Fprintf(w, "n=%d", n)
222 _, err := c.Get(ts.URL)
223 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
224 t.Errorf("with default client Get, expected error %q, got %q", e, g)
227 // HEAD request should also have the ability to follow redirects.
228 _, err = c.Head(ts.URL)
229 if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
230 t.Errorf("with default client Head, expected error %q, got %q", e, g)
233 // Do should also follow redirects.
234 greq, _ := NewRequest("GET", ts.URL, nil)
236 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
237 t.Errorf("with default client Do, expected error %q, got %q", e, g)
240 // Requests with an empty Method should also redirect (Issue 12705)
243 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
244 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
248 var lastVia []*Request
250 c.CheckRedirect = func(req *Request, via []*Request) error {
255 res, err := c.Get(ts.URL)
257 t.Fatalf("Get error: %v", err)
260 finalURL := res.Request.URL.String()
261 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
262 t.Errorf("with custom client, expected error %q, got %q", e, g)
264 if !strings.HasSuffix(finalURL, "/?n=15") {
265 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
267 if e, g := 15, len(lastVia); e != g {
268 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
271 // Test that Request.Cancel is propagated between requests (Issue 14053)
272 creq, _ := NewRequest("HEAD", ts.URL, nil)
273 cancel := make(chan struct{})
275 if _, err := c.Do(creq); err != nil {
279 t.Fatal("didn't see redirect")
281 if lastReq.Cancel != cancel {
282 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
285 checkErr = errors.New("no redirects allowed")
286 res, err = c.Get(ts.URL)
287 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
288 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
291 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
294 if res.Header.Get("Location") == "" {
295 t.Errorf("no Location header in Response")
299 // Tests that Client redirects' contexts are derived from the original request's context.
300 func TestClientRedirectContext(t *testing.T) {
303 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
304 Redirect(w, r, "/", StatusTemporaryRedirect)
308 ctx, cancel := context.WithCancel(context.Background())
310 c.CheckRedirect = func(req *Request, via []*Request) error {
313 case <-req.Context().Done():
315 case <-time.After(5 * time.Second):
316 return errors.New("redirected request's context never expired after root request canceled")
319 req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
321 ue, ok := err.(*url.Error)
323 t.Fatalf("got error %T; want *url.Error", err)
325 if ue.Err != context.Canceled {
326 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
330 type redirectTest struct {
332 want int // response code
336 func TestPostRedirects(t *testing.T) {
337 postRedirectTests := []redirectTest{
339 {"/?code=301&next=302", 200, "c301"},
340 {"/?code=302&next=302", 200, "c302"},
341 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
342 {"/?code=304", 304, "c304"},
343 {"/?code=305", 305, "c305"},
344 {"/?code=307&next=303,308,302", 200, "c307"},
345 {"/?code=308&next=302,301", 200, "c308"},
346 {"/?code=404", 404, "c404"},
349 wantSegments := []string{
351 `POST /?code=301&next=302 "c301"`,
354 `POST /?code=302&next=302 "c302"`,
357 `POST /?code=303&next=301 "c303wc301"`,
360 `POST /?code=304 "c304"`,
361 `POST /?code=305 "c305"`,
362 `POST /?code=307&next=303,308,302 "c307"`,
363 `POST /?code=303&next=308,302 "c307"`,
364 `GET /?code=308&next=302 ""`,
365 `GET /?code=302 "c307"`,
367 `POST /?code=308&next=302,301 "c308"`,
368 `POST /?code=302&next=301 "c308"`,
371 `POST /?code=404 "c404"`,
373 want := strings.Join(wantSegments, "\n")
374 testRedirectsByMethod(t, "POST", postRedirectTests, want)
377 func TestDeleteRedirects(t *testing.T) {
378 deleteRedirectTests := []redirectTest{
380 {"/?code=301&next=302,308", 200, "c301"},
381 {"/?code=302&next=302", 200, "c302"},
382 {"/?code=303", 200, "c303"},
383 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
384 {"/?code=308&next=307", 200, "c308"},
385 {"/?code=404", 404, "c404"},
388 wantSegments := []string{
390 `DELETE /?code=301&next=302,308 "c301"`,
391 `GET /?code=302&next=308 ""`,
394 `DELETE /?code=302&next=302 "c302"`,
397 `DELETE /?code=303 "c303"`,
399 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
400 `DELETE /?code=301&next=308,303,302,304 "c307"`,
401 `GET /?code=308&next=303,302,304 ""`,
402 `GET /?code=303&next=302,304 "c307"`,
403 `GET /?code=302&next=304 ""`,
405 `DELETE /?code=308&next=307 "c308"`,
406 `DELETE /?code=307 "c308"`,
408 `DELETE /?code=404 "c404"`,
410 want := strings.Join(wantSegments, "\n")
411 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
414 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
420 var ts *httptest.Server
421 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
423 slurp, _ := io.ReadAll(r.Body)
424 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
425 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
426 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
430 urlQuery := r.URL.Query()
431 if v := urlQuery.Get("code"); v != "" {
433 if final := urlQuery.Get("next"); final != "" {
434 splits := strings.Split(final, ",")
435 first, rest := splits[0], splits[1:]
436 location = fmt.Sprintf("%s?code=%s", location, first)
438 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
441 code, _ := strconv.Atoi(v)
443 w.Header().Set("Location", location)
451 for _, tt := range table {
452 content := tt.redirectBody
453 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
454 req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
455 res, err := c.Do(req)
460 if res.StatusCode != tt.want {
461 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
468 got = strings.TrimSpace(got)
469 want = strings.TrimSpace(want)
472 got, want, lines := removeCommonLines(got, want)
473 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
477 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
479 nl := strings.IndexByte(a, '\n')
481 return a, b, commonLines
484 if !strings.HasPrefix(b, line) {
485 return a, b, commonLines
493 func TestClientRedirectUseResponse(t *testing.T) {
496 const body = "Hello, world."
497 var ts *httptest.Server
498 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
499 if strings.Contains(r.URL.Path, "/other") {
500 io.WriteString(w, "wrong body")
502 w.Header().Set("Location", ts.URL+"/other")
503 w.WriteHeader(StatusFound)
504 io.WriteString(w, body)
510 c.CheckRedirect = func(req *Request, via []*Request) error {
511 if req.Response == nil {
512 t.Error("expected non-nil Request.Response")
514 return ErrUseLastResponse
516 res, err := c.Get(ts.URL)
520 if res.StatusCode != StatusFound {
521 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
523 defer res.Body.Close()
524 slurp, err := io.ReadAll(res.Body)
528 if string(slurp) != body {
529 t.Errorf("body = %q; want %q", slurp, body)
533 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
534 // have a Location header.
535 func TestClientRedirect308NoLocation(t *testing.T) {
538 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
539 w.Header().Set("Foo", "Bar")
544 res, err := c.Get(ts.URL)
549 if res.StatusCode != 308 {
550 t.Errorf("status = %d; want %d", res.StatusCode, 308)
552 if got := res.Header.Get("Foo"); got != "Bar" {
553 t.Errorf("Foo header = %q; want Bar", got)
557 // Don't follow a 307/308 if we can't resent the request body.
558 func TestClientRedirect308NoGetBody(t *testing.T) {
561 const fakeURL = "https://localhost:1234/" // won't be hit
562 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
563 w.Header().Set("Location", fakeURL)
567 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
572 req.GetBody = nil // so it can't rewind.
573 res, err := c.Do(req)
578 if res.StatusCode != 308 {
579 t.Errorf("status = %d; want %d", res.StatusCode, 308)
581 if got := res.Header.Get("Location"); got != fakeURL {
582 t.Errorf("Location header = %q; want %q", got, fakeURL)
586 var expectedCookies = []*Cookie{
587 {Name: "ChocolateChip", Value: "tasty"},
588 {Name: "First", Value: "Hit"},
589 {Name: "Second", Value: "Hit"},
592 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
593 for _, cookie := range r.Cookies() {
596 if r.URL.Path == "/" {
597 SetCookie(w, expectedCookies[1])
598 Redirect(w, r, "/second", StatusMovedPermanently)
600 SetCookie(w, expectedCookies[2])
601 w.Write([]byte("hello"))
605 func TestClientSendsCookieFromJar(t *testing.T) {
607 tr := &recordingTransport{}
608 client := &Client{Transport: tr}
609 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
610 us := "http://dummy.faketld/"
611 u, _ := url.Parse(us)
612 client.Jar.SetCookies(u, expectedCookies)
614 client.Get(us) // Note: doesn't hit network
615 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
617 client.Head(us) // Note: doesn't hit network
618 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
620 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
621 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
623 client.PostForm(us, url.Values{}) // Note: doesn't hit network
624 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
626 req, _ := NewRequest("GET", us, nil)
627 client.Do(req) // Note: doesn't hit network
628 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
630 req, _ = NewRequest("POST", us, nil)
631 client.Do(req) // Note: doesn't hit network
632 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
635 // Just enough correctness for our redirect tests. Uses the URL.Host as the
636 // scope of all cookies.
637 type TestJar struct {
639 perURL map[string][]*Cookie
642 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
646 j.perURL = make(map[string][]*Cookie)
648 j.perURL[u.Host] = cookies
651 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
654 return j.perURL[u.Host]
657 func TestRedirectCookiesJar(t *testing.T) {
660 var ts *httptest.Server
661 ts = httptest.NewServer(echoCookiesRedirectHandler)
665 u, _ := url.Parse(ts.URL)
666 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
667 resp, err := c.Get(ts.URL)
669 t.Fatalf("Get: %v", err)
672 matchReturnedCookies(t, expectedCookies, resp.Cookies())
675 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
676 if len(given) != len(expected) {
677 t.Logf("Received cookies: %v", given)
678 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
680 for _, ec := range expected {
682 for _, c := range given {
683 if ec.Name == c.Name && ec.Value == c.Value {
689 t.Errorf("Missing cookie %v", ec)
694 func TestJarCalls(t *testing.T) {
696 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
697 pathSuffix := r.RequestURI[1:]
698 if r.RequestURI == "/nosetcookie" {
699 return // don't set cookies for this path
701 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
702 if r.RequestURI == "/" {
703 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
707 jar := new(RecordingJar)
710 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
711 return net.Dial("tcp", ts.Listener.Addr().String())
713 _, err := c.Get("http://firsthost.fake/")
717 _, err = c.Get("http://firsthost.fake/nosetcookie")
721 got := jar.log.String()
722 want := `Cookies("http://firsthost.fake/")
723 SetCookie("http://firsthost.fake/", [name=val])
724 Cookies("http://secondhost.fake/secondpath")
725 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
726 Cookies("http://firsthost.fake/nosetcookie")
729 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
733 // RecordingJar keeps a log of calls made to it, without
734 // tracking any cookies.
735 type RecordingJar struct {
740 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
741 j.logf("SetCookie(%q, %v)\n", u, cookies)
744 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
745 j.logf("Cookies(%q)\n", u)
749 func (j *RecordingJar) logf(format string, args ...interface{}) {
752 fmt.Fprintf(&j.log, format, args...)
755 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
756 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
758 func testStreamingGet(t *testing.T, h2 bool) {
760 say := make(chan string)
761 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
763 for str := range say {
771 res, err := c.Get(cst.ts.URL)
776 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
778 n, err := io.ReadFull(res.Body, buf[0:len(str)])
780 t.Fatalf("ReadFull on %q: %v", str, err)
783 t.Fatalf("Receiving %q, only read %d bytes", str, n)
785 got := string(buf[0:n])
787 t.Fatalf("Expected %q, got %q", str, got)
791 _, err = io.ReadFull(res.Body, buf[0:1])
793 t.Fatalf("at end expected EOF, got %v", err)
797 type writeCountingConn struct {
802 func (c *writeCountingConn) Write(p []byte) (int, error) {
804 return c.Conn.Write(p)
807 // TestClientWrites verifies that client requests are buffered and we
808 // don't send a TCP packet per line of the http request + body.
809 func TestClientWrites(t *testing.T) {
811 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
816 dialer := func(netz string, addr string) (net.Conn, error) {
817 c, err := net.Dial(netz, addr)
819 c = &writeCountingConn{c, &writes}
824 c.Transport.(*Transport).Dial = dialer
826 _, err := c.Get(ts.URL)
831 t.Errorf("Get request did %d Write calls, want 1", writes)
835 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
840 t.Errorf("Post request did %d Write calls, want 1", writes)
844 func TestClientInsecureTransport(t *testing.T) {
847 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
848 w.Write([]byte("Hello"))
850 errc := make(chanWriter, 10) // but only expecting 1
851 ts.Config.ErrorLog = log.New(errc, "", 0)
854 // TODO(bradfitz): add tests for skipping hostname checks too?
855 // would require a new cert for testing, and probably
856 // redundant with these tests.
858 for _, insecure := range []bool{true, false} {
859 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
860 InsecureSkipVerify: insecure,
862 res, err := c.Get(ts.URL)
863 if (err == nil) != insecure {
864 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
873 if !strings.Contains(v, "TLS handshake error") {
874 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
876 case <-time.After(5 * time.Second):
877 t.Errorf("timeout waiting for logged error")
882 func TestClientErrorWithRequestURI(t *testing.T) {
884 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
885 req.RequestURI = "/this/field/is/illegal/and/should/error/"
886 _, err := DefaultClient.Do(req)
888 t.Fatalf("expected an error")
890 if !strings.Contains(err.Error(), "RequestURI") {
891 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
895 func TestClientWithCorrectTLSServerName(t *testing.T) {
898 const serverName = "example.com"
899 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
900 if r.TLS.ServerName != serverName {
901 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
907 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
908 if _, err := c.Get(ts.URL); err != nil {
909 t.Fatalf("expected successful TLS connection, got error: %v", err)
913 func TestClientWithIncorrectTLSServerName(t *testing.T) {
915 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
917 errc := make(chanWriter, 10) // but only expecting 1
918 ts.Config.ErrorLog = log.New(errc, "", 0)
921 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
922 _, err := c.Get(ts.URL)
924 t.Fatalf("expected an error")
926 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
927 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
931 if !strings.Contains(v, "TLS handshake error") {
932 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
934 case <-time.After(5 * time.Second):
935 t.Errorf("timeout waiting for logged error")
939 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
942 // tls.Config.ServerName (non-empty, set to "example.com") takes
943 // precedence over "some-other-host.tld" which previously incorrectly
944 // took precedence. We don't actually connect to (or even resolve)
945 // "some-other-host.tld", though, because of the Transport.Dial hook.
947 // The httptest.Server has a cert with "example.com" as its name.
948 func TestTransportUsesTLSConfigServerName(t *testing.T) {
950 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
951 w.Write([]byte("Hello"))
956 tr := c.Transport.(*Transport)
957 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
958 tr.Dial = func(netw, addr string) (net.Conn, error) {
959 return net.Dial(netw, ts.Listener.Addr().String())
961 res, err := c.Get("https://some-other-host.tld/")
968 func TestResponseSetsTLSConnectionState(t *testing.T) {
970 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
971 w.Write([]byte("Hello"))
976 tr := c.Transport.(*Transport)
977 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
978 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
979 tr.Dial = func(netw, addr string) (net.Conn, error) {
980 return net.Dial(netw, ts.Listener.Addr().String())
982 res, err := c.Get("https://example.com/")
986 defer res.Body.Close()
988 t.Fatal("Response didn't set TLS Connection State.")
990 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
991 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
995 // Check that an HTTPS client can interpret a particular TLS error
996 // to determine that the server is speaking HTTP.
997 // See golang.org/issue/11111.
998 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1000 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1001 ts.Config.ErrorLog = quietLog
1004 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1005 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1006 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1010 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1011 func TestClientHeadContentLength_h1(t *testing.T) {
1012 testClientHeadContentLength(t, h1Mode)
1015 func TestClientHeadContentLength_h2(t *testing.T) {
1016 testClientHeadContentLength(t, h2Mode)
1019 func testClientHeadContentLength(t *testing.T, h2 bool) {
1021 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1022 if v := r.FormValue("cl"); v != "" {
1023 w.Header().Set("Content-Length", v)
1031 {"/?cl=1234", 1234},
1035 for _, tt := range tests {
1036 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1037 res, err := cst.c.Do(req)
1041 if res.ContentLength != tt.want {
1042 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1044 bs, err := io.ReadAll(res.Body)
1049 t.Errorf("Unexpected content: %q", bs)
1054 func TestEmptyPasswordAuth(t *testing.T) {
1058 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1059 auth := r.Header.Get("Authorization")
1060 if strings.HasPrefix(auth, "Basic ") {
1062 decoded, err := base64.StdEncoding.DecodeString(encoded)
1066 expected := gopher + ":"
1067 s := string(decoded)
1069 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1072 t.Errorf("Invalid auth %q", auth)
1076 req, err := NewRequest("GET", ts.URL, nil)
1080 req.URL.User = url.User(gopher)
1082 resp, err := c.Do(req)
1086 defer resp.Body.Close()
1089 func TestBasicAuth(t *testing.T) {
1091 tr := &recordingTransport{}
1092 client := &Client{Transport: tr}
1094 url := "http://My%20User:My%20Pass@dummy.faketld/"
1095 expected := "My User:My Pass"
1098 if tr.req.Method != "GET" {
1099 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1101 if tr.req.URL.String() != url {
1102 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1104 if tr.req.Header == nil {
1105 t.Fatalf("expected non-nil request Header")
1107 auth := tr.req.Header.Get("Authorization")
1108 if strings.HasPrefix(auth, "Basic ") {
1110 decoded, err := base64.StdEncoding.DecodeString(encoded)
1114 s := string(decoded)
1116 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1119 t.Errorf("Invalid auth %q", auth)
1123 func TestBasicAuthHeadersPreserved(t *testing.T) {
1125 tr := &recordingTransport{}
1126 client := &Client{Transport: tr}
1128 // If Authorization header is provided, username in URL should not override it
1129 url := "http://My%20User@dummy.faketld/"
1130 req, err := NewRequest("GET", url, nil)
1134 req.SetBasicAuth("My User", "My Pass")
1135 expected := "My User:My Pass"
1138 if tr.req.Method != "GET" {
1139 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1141 if tr.req.URL.String() != url {
1142 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1144 if tr.req.Header == nil {
1145 t.Fatalf("expected non-nil request Header")
1147 auth := tr.req.Header.Get("Authorization")
1148 if strings.HasPrefix(auth, "Basic ") {
1150 decoded, err := base64.StdEncoding.DecodeString(encoded)
1154 s := string(decoded)
1156 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1159 t.Errorf("Invalid auth %q", auth)
1164 func TestStripPasswordFromError(t *testing.T) {
1165 client := &Client{Transport: &recordingTransport{}}
1166 testCases := []struct {
1172 desc: "Strip password from error message",
1173 in: "http://user:password@dummy.faketld/",
1174 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1177 desc: "Don't Strip password from domain name",
1178 in: "http://user:password@password.faketld/",
1179 out: `Get "http://user:***@password.faketld/": dummy impl`,
1182 desc: "Don't Strip password from path",
1183 in: "http://user:password@dummy.faketld/password",
1184 out: `Get "http://user:***@dummy.faketld/password": dummy impl`,
1187 desc: "Strip escaped password",
1188 in: "http://user:pa%2Fssword@dummy.faketld/",
1189 out: `Get "http://user:***@dummy.faketld/": dummy impl`,
1192 for _, tC := range testCases {
1193 t.Run(tC.desc, func(t *testing.T) {
1194 _, err := client.Get(tC.in)
1195 if err.Error() != tC.out {
1196 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1197 tC.in, tC.out, err.Error())
1203 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1204 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1206 func testClientTimeout(t *testing.T, h2 bool) {
1209 testDone := make(chan struct{}) // closed in defer below
1211 sawRoot := make(chan bool, 1)
1212 sawSlow := make(chan bool, 1)
1213 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1214 if r.URL.Path == "/" {
1216 Redirect(w, r, "/slow", StatusFound)
1219 if r.URL.Path == "/slow" {
1221 w.Write([]byte("Hello"))
1228 defer close(testDone) // before cst.close, to unblock /slow handler
1230 // 200ms should be long enough to get a normal request (the /
1231 // handler), but not so long that it makes the test slow.
1232 const timeout = 200 * time.Millisecond
1233 cst.c.Timeout = timeout
1235 res, err := cst.c.Get(cst.ts.URL)
1237 if strings.Contains(err.Error(), "Client.Timeout") {
1238 t.Skipf("host too slow to get fast resource in %v", timeout)
1247 t.Fatal("handler never got / request")
1254 t.Fatal("handler never got /slow request")
1257 errc := make(chan error, 1)
1259 _, err := io.ReadAll(res.Body)
1264 const failTime = 5 * time.Second
1268 t.Fatal("expected error from ReadAll")
1270 ne, ok := err.(net.Error)
1272 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1273 } else if !ne.Timeout() {
1274 t.Errorf("net.Error.Timeout = false; want true")
1276 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1277 t.Errorf("error string = %q; missing timeout substring", got)
1279 case <-time.After(failTime):
1280 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1284 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1285 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1287 // Client.Timeout firing before getting to the body
1288 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1291 donec := make(chan bool, 1)
1292 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1296 // Note that we use a channel send here and not a close.
1297 // The race detector doesn't know that we're waiting for a timeout
1298 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1299 // with us closing it. If we timed out immediately, we could close the testserver
1300 // before we entered the handler. We're not timing out immediately and there's
1301 // no way we would be done before we entered the handler, but the race detector
1302 // doesn't know this, so synchronize explicitly.
1303 defer func() { donec <- true }()
1305 cst.c.Timeout = 5 * time.Millisecond
1306 res, err := cst.c.Get(cst.ts.URL)
1309 t.Fatal("got response from Get; expected error")
1311 if _, ok := err.(*url.Error); !ok {
1312 t.Fatalf("Got error of type %T; want *url.Error", err)
1314 ne, ok := err.(net.Error)
1316 t.Fatalf("Got error of type %T; want some net.Error", err)
1319 t.Error("net.Error.Timeout = false; want true")
1321 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1322 t.Errorf("error string = %q; missing timeout substring", got)
1326 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1328 func TestClientTimeoutCancel(t *testing.T) {
1332 testDone := make(chan struct{})
1333 ctx, cancel := context.WithCancel(context.Background())
1335 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1340 defer close(testDone)
1342 cst.c.Timeout = 1 * time.Hour
1343 req, _ := NewRequest("GET", cst.ts.URL, nil)
1344 req.Cancel = ctx.Done()
1345 res, err := cst.c.Do(req)
1350 _, err = io.Copy(io.Discard, res.Body)
1351 if err != ExportErrRequestCanceled {
1352 t.Fatalf("error = %v; want errRequestCanceled", err)
1356 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1357 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1358 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1361 saw := make(chan string, 2)
1362 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1364 if r.URL.Path == "/" {
1365 Redirect(w, r, "/foo", StatusFound) // which includes a body
1370 res, err := cst.c.Get(cst.ts.URL)
1374 _, err = io.ReadAll(res.Body)
1384 t.Fatal("server didn't see a request")
1389 case second = <-saw:
1391 t.Fatal("server didn't see a second request")
1394 if first != second {
1395 t.Fatal("server saw different client ports before & after the redirect")
1399 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1400 type eofReaderFunc func()
1402 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1407 func TestReferer(t *testing.T) {
1409 lastReq, newReq string // from -> to URLs
1413 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1414 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1416 // don't send a user and password:
1417 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1418 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1421 {"http://test.com", "http://link.com", "http://test.com"},
1422 {"https://test.com", "https://link.com", "https://test.com"},
1424 // https to http doesn't send a referer:
1425 {"https://test.com", "http://link.com", ""},
1426 {"https://gopher:go@test.com", "http://link.com", ""},
1428 for _, tt := range tests {
1429 l, err := url.Parse(tt.lastReq)
1433 n, err := url.Parse(tt.newReq)
1437 r := ExportRefererForURL(l, n)
1439 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1444 // issue15577Tripper returns a Response with a redirect response
1445 // header and doesn't populate its Response.Request field.
1446 type issue15577Tripper struct{}
1448 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1451 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1452 Body: io.NopCloser(strings.NewReader("")),
1457 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1458 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1460 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1461 Transport: issue15577Tripper{},
1463 // Check that this doesn't crash:
1464 c.Get("http://dummy.tld")
1467 // Issue 4800: copy (some) headers when Client follows a redirect.
1468 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1470 ua = "some-agent/1.2"
1474 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1476 "User-Agent": []string{ua},
1477 "X-Foo": []string{xfoo},
1478 "Referer": []string{ts2URL},
1479 "Accept-Encoding": []string{"gzip"},
1481 if !reflect.DeepEqual(r.Header, want) {
1482 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1485 w.Header().Set("Result", "got errors")
1487 w.Header().Set("Result", "ok")
1491 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1492 Redirect(w, r, ts1.URL, StatusFound)
1498 c.CheckRedirect = func(r *Request, via []*Request) error {
1500 "User-Agent": []string{ua},
1501 "X-Foo": []string{xfoo},
1502 "Referer": []string{ts2URL},
1504 if !reflect.DeepEqual(r.Header, want) {
1505 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1510 req, _ := NewRequest("GET", ts2.URL, nil)
1511 req.Header.Add("User-Agent", ua)
1512 req.Header.Add("X-Foo", xfoo)
1513 req.Header.Add("Cookie", "foo=bar")
1514 req.Header.Add("Authorization", "secretpassword")
1515 res, err := c.Do(req)
1519 defer res.Body.Close()
1520 if res.StatusCode != 200 {
1523 if got := res.Header.Get("Result"); got != "ok" {
1524 t.Errorf("result = %q; want ok", got)
1528 // Issue 22233: copy host when Client follows a relative redirect.
1529 func TestClientCopyHostOnRedirect(t *testing.T) {
1530 // Virtual hostname: should not receive any request.
1531 virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1532 t.Errorf("Virtual host received request %v", r.URL)
1534 io.WriteString(w, "should not see this response")
1536 defer virtual.Close()
1537 virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1538 t.Logf("Virtual host is %v", virtualHost)
1540 // Actual hostname: should not receive any request.
1541 const wantBody = "response body"
1544 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1547 // Relative redirect.
1548 if r.Host != virtualHost {
1549 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1553 w.Header().Set("Location", "/hop")
1556 // Absolute redirect.
1557 if r.Host != virtualHost {
1558 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1562 w.Header().Set("Location", tsURL+"/final")
1565 if r.Host != tsHost {
1566 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1571 io.WriteString(w, wantBody)
1573 t.Errorf("Serving unexpected path %q", r.URL.Path)
1579 tsHost = strings.TrimPrefix(ts.URL, "http://")
1580 t.Logf("Server host is %v", tsHost)
1583 req, _ := NewRequest("GET", ts.URL, nil)
1584 req.Host = virtualHost
1585 resp, err := c.Do(req)
1589 defer resp.Body.Close()
1590 if resp.StatusCode != 200 {
1591 t.Fatal(resp.Status)
1593 if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1594 t.Errorf("body = %q; want %q", got, wantBody)
1598 // Issue 17494: cookies should be altered when Client follows redirects.
1599 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1600 cookieMap := func(cs []*Cookie) map[string][]string {
1601 m := make(map[string][]string)
1602 for _, c := range cs {
1603 m[c.Name] = append(m[c.Name], c.Value)
1608 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1609 var want map[string][]string
1610 got := cookieMap(r.Cookies())
1612 c, _ := r.Cookie("Cycle")
1615 want = map[string][]string{
1616 "Cookie1": {"OldValue1a", "OldValue1b"},
1617 "Cookie2": {"OldValue2"},
1618 "Cookie3": {"OldValue3a", "OldValue3b"},
1619 "Cookie4": {"OldValue4"},
1622 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1623 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1624 Redirect(w, r, "/", StatusFound)
1626 want = map[string][]string{
1627 "Cookie1": {"OldValue1a", "OldValue1b"},
1628 "Cookie3": {"OldValue3a", "OldValue3b"},
1629 "Cookie4": {"OldValue4"},
1632 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1633 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1634 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1635 Redirect(w, r, "/", StatusFound)
1637 want = map[string][]string{
1638 "Cookie1": {"OldValue1a", "OldValue1b"},
1639 "Cookie3": {"NewValue3"},
1640 "Cookie4": {"NewValue4"},
1643 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1644 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1645 Redirect(w, r, "/", StatusFound)
1647 want = map[string][]string{
1648 "Cookie1": {"OldValue1a", "OldValue1b"},
1649 "Cookie3": {"NewValue3"},
1650 "Cookie4": {"NewValue4"},
1651 "Cookie5": {"NewValue5"},
1654 // Don't redirect to ensure the loop ends.
1656 t.Errorf("unexpected redirect cycle")
1660 if !reflect.DeepEqual(got, want) {
1661 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1666 jar, _ := cookiejar.New(nil)
1670 u, _ := url.Parse(ts.URL)
1671 req, _ := NewRequest("GET", ts.URL, nil)
1672 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1673 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1674 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1675 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1676 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1677 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1678 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1679 res, err := c.Do(req)
1683 defer res.Body.Close()
1684 if res.StatusCode != 200 {
1689 // Part of Issue 4800
1690 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1697 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1698 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1700 // Sensitive headers:
1701 {"cookie", "http://foo.com/", "http://bar.com/", false},
1702 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1703 {"authorization", "http://foo.com/", "http://bar.com/", false},
1704 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1706 // But subdomains should work:
1707 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1708 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1709 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1710 {"www-authenticate", "http://foo.com/", "https://foo.com/", false},
1711 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1712 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1713 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1714 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1715 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false},
1717 for i, tt := range tests {
1718 u0, err := url.Parse(tt.initialURL)
1720 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1723 u1, err := url.Parse(tt.destURL)
1725 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1728 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1730 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1731 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1736 func TestClientRedirectTypes(t *testing.T) {
1740 tests := [...]struct {
1743 wantMethod string // desired subsequent client method
1745 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1746 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1747 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1748 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1749 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1751 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1752 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1753 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1754 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1755 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1757 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1758 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1759 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1760 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1761 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1763 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1764 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1765 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1766 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1767 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1769 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1770 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1771 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1772 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1773 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1775 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1776 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1777 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1778 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1779 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1782 handlerc := make(chan HandlerFunc, 1)
1784 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1791 for i, tt := range tests {
1792 handlerc <- func(w ResponseWriter, r *Request) {
1793 w.Header().Set("Location", ts.URL)
1794 w.WriteHeader(tt.serverStatus)
1797 req, err := NewRequest(tt.method, ts.URL, nil)
1799 t.Errorf("#%d: NewRequest: %v", i, err)
1803 c.CheckRedirect = func(req *Request, via []*Request) error {
1804 if got, want := req.Method, tt.wantMethod; got != want {
1805 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1807 handlerc <- func(rw ResponseWriter, req *Request) {
1808 // TODO: Check that the body is valid when we do 307 and 308 support
1813 res, err := c.Do(req)
1815 t.Errorf("#%d: Response: %v", i, err)
1823 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1824 // Its Read returns readErr and increments *readCalls atomically.
1825 // Its Close returns nil and increments *closeCalls atomically.
1826 type issue18239Body struct {
1832 func (b issue18239Body) Read([]byte) (int, error) {
1833 atomic.AddInt32(b.readCalls, 1)
1837 func (b issue18239Body) Close() error {
1838 atomic.AddInt32(b.closeCalls, 1)
1842 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1843 // if Request.GetBody is not defined.
1844 func TestTransportBodyReadError(t *testing.T) {
1847 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1848 if r.URL.Path == "/ping" {
1851 buf := make([]byte, 1)
1852 n, err := r.Body.Read(buf)
1853 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1857 tr := c.Transport.(*Transport)
1859 // Do one initial successful request to create an idle TCP connection
1860 // for the subsequent request to reuse. (The Transport only retries
1861 // requests on reused connections.)
1862 res, err := c.Get(ts.URL + "/ping")
1868 var readCallsAtomic int32
1869 var closeCallsAtomic int32 // atomic
1870 someErr := errors.New("some body read error")
1871 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1873 req, err := NewRequest("POST", ts.URL, body)
1878 _, err = tr.RoundTrip(req)
1880 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1883 // And verify that our Body wasn't used multiple times, which
1884 // would indicate retries. (as it buggily was during part of
1885 // Go 1.8's dev cycle)
1886 readCalls := atomic.LoadInt32(&readCallsAtomic)
1887 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1889 t.Errorf("read calls = %d; want 1", readCalls)
1891 if closeCalls != 1 {
1892 t.Errorf("close calls = %d; want 1", closeCalls)
1896 type roundTripperWithoutCloseIdle struct{}
1898 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1900 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1902 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1903 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() }
1905 func TestClientCloseIdleConnections(t *testing.T) {
1906 c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1907 c.CloseIdleConnections() // verify we don't crash at least
1910 var tr RoundTripper = roundTripperWithCloseIdle(func() {
1913 c = &Client{Transport: tr}
1914 c.CloseIdleConnections()
1916 t.Error("not closed")
1920 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1921 errDial := errors.New("not actually dialing")
1923 Timeout: 5 * time.Second,
1924 Transport: &Transport{
1925 DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1926 deadline, ok := ctx.Deadline()
1928 t.Error("no deadline")
1930 t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1936 c.Get("https://example.tld/")
1939 func TestClientDoCanceledVsTimeout_h1(t *testing.T) {
1940 testClientDoCanceledVsTimeout(t, h1Mode)
1943 func TestClientDoCanceledVsTimeout_h2(t *testing.T) {
1944 testClientDoCanceledVsTimeout(t, h2Mode)
1947 // Issue 33545: lock-in the behavior promised by Client.Do's
1948 // docs about request cancellation vs timing out.
1949 func testClientDoCanceledVsTimeout(t *testing.T, h2 bool) {
1951 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1952 w.Write([]byte("Hello, World!"))
1956 cases := []string{"timeout", "canceled"}
1958 for _, name := range cases {
1959 t.Run(name, func(t *testing.T) {
1960 var ctx context.Context
1962 if name == "timeout" {
1963 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
1965 ctx, cancel = context.WithCancel(context.Background())
1970 req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
1971 _, err := cst.c.Do(req)
1973 t.Fatal("Unexpectedly got a nil error")
1976 ue := err.(*url.Error)
1978 var wantIsTimeout bool
1979 var wantErr error = context.Canceled
1980 if name == "timeout" {
1981 wantErr = context.DeadlineExceeded
1982 wantIsTimeout = true
1984 if g, w := ue.Timeout(), wantIsTimeout; g != w {
1985 t.Fatalf("url.Timeout() = %t, want %t", g, w)
1987 if g, w := ue.Err, wantErr; g != w {
1988 t.Errorf("url.Error.Err = %v; want %v", g, w)
1994 type nilBodyRoundTripper struct{}
1996 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
1998 StatusCode: StatusOK,
1999 Status: StatusText(StatusOK),
2005 func TestClientPopulatesNilResponseBody(t *testing.T) {
2006 c := &Client{Transport: nilBodyRoundTripper{}}
2008 resp, err := c.Get("http://localhost/anything")
2010 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2013 if resp.Body == nil {
2014 t.Fatalf("Client failed to provide a non-nil Body as documented")
2017 if err := resp.Body.Close(); err != nil {
2018 t.Fatalf("error from Close on substitute Response.Body: %v", err)
2022 if b, err := io.ReadAll(resp.Body); err != nil {
2023 t.Errorf("read error from substitute Response.Body: %v", err)
2024 } else if len(b) != 0 {
2025 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2029 // Issue 40382: Client calls Close multiple times on Request.Body.
2030 func TestClientCallsCloseOnlyOnce(t *testing.T) {
2033 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2034 w.WriteHeader(StatusNoContent)
2038 // Issue occurred non-deterministically: needed to occur after a successful
2039 // write (into TCP buffer) but before end of body.
2040 for i := 0; i < 50 && !t.Failed(); i++ {
2041 body := &issue40382Body{t: t, n: 300000}
2042 req, err := NewRequest(MethodPost, cst.ts.URL, body)
2046 resp, err := cst.tr.RoundTrip(req)
2054 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2055 // Its Read reads n bytes before returning io.EOF.
2056 // Its Close returns nil but fails the test if called more than once.
2057 type issue40382Body struct {
2060 closeCallsAtomic int32
2063 func (b *issue40382Body) Read(p []byte) (int, error) {
2079 func (b *issue40382Body) Close() error {
2080 if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2081 b.t.Error("Body closed more than once")
2086 func TestProbeZeroLengthBody(t *testing.T) {
2089 reqc := make(chan struct{})
2090 cst := newClientServerTest(t, false, HandlerFunc(func(w ResponseWriter, r *Request) {
2092 if _, err := io.Copy(w, r.Body); err != nil {
2093 t.Errorf("error copying request body: %v", err)
2098 bodyr, bodyw := io.Pipe()
2100 var wg sync.WaitGroup
2104 req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2105 res, err := cst.c.Do(req)
2106 b, err := io.ReadAll(res.Body)
2115 // Request should be sent after trying to probe the request body for 200ms.
2116 case <-time.After(60 * time.Second):
2117 t.Errorf("request not sent after 60s")
2120 // Write the request body and wait for the request to complete.
2121 const content = "body"
2122 bodyw.Write([]byte(content))
2125 if gotBody != content {
2126 t.Fatalf("server got body %q, want %q", gotBody, content)