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 ioutil.ReadAll but additionally
40 // verifies that r obeys the documented io.Reader contract.
41 func pedanticReadAll(r io.Reader) (b []byte, err error) {
46 if n == 0 && err == nil {
47 return nil, fmt.Errorf("Read: n=0 with err=nil")
49 b = append(b, buf[:n]...)
52 if n != 0 || err != io.EOF {
53 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
63 type chanWriter chan string
65 func (w chanWriter) Write(p []byte) (n int, err error) {
70 func TestClient(t *testing.T) {
73 ts := httptest.NewServer(robotsTxtHandler)
76 c := &Client{Transport: &Transport{DisableKeepAlives: true}}
77 r, err := c.Get(ts.URL)
80 b, err = pedanticReadAll(r.Body)
85 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
86 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
90 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
91 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
93 func testClientHead(t *testing.T, h2 bool) {
95 cst := newClientServerTest(t, h2, robotsTxtHandler)
98 r, err := cst.c.Head(cst.ts.URL)
102 if _, ok := r.Header["Last-Modified"]; !ok {
103 t.Error("Last-Modified header not found.")
107 type recordingTransport struct {
111 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
113 return nil, errors.New("dummy impl")
116 func TestGetRequestFormat(t *testing.T) {
119 tr := &recordingTransport{}
120 client := &Client{Transport: tr}
121 url := "http://dummy.faketld/"
122 client.Get(url) // Note: doesn't hit network
123 if tr.req.Method != "GET" {
124 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
126 if tr.req.URL.String() != url {
127 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
129 if tr.req.Header == nil {
130 t.Errorf("expected non-nil request Header")
134 func TestPostRequestFormat(t *testing.T) {
136 tr := &recordingTransport{}
137 client := &Client{Transport: tr}
139 url := "http://dummy.faketld/"
140 json := `{"key":"value"}`
141 b := strings.NewReader(json)
142 client.Post(url, "application/json", b) // Note: doesn't hit network
144 if tr.req.Method != "POST" {
145 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
147 if tr.req.URL.String() != url {
148 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
150 if tr.req.Header == nil {
151 t.Fatalf("expected non-nil request Header")
154 t.Error("got Close true, want false")
156 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
157 t.Errorf("got ContentLength %d, want %d", g, e)
161 func TestPostFormRequestFormat(t *testing.T) {
163 tr := &recordingTransport{}
164 client := &Client{Transport: tr}
166 urlStr := "http://dummy.faketld/"
167 form := make(url.Values)
168 form.Set("foo", "bar")
169 form.Add("foo", "bar2")
170 form.Set("bar", "baz")
171 client.PostForm(urlStr, form) // Note: doesn't hit network
173 if tr.req.Method != "POST" {
174 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
176 if tr.req.URL.String() != urlStr {
177 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
179 if tr.req.Header == nil {
180 t.Fatalf("expected non-nil request Header")
182 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
183 t.Errorf("got Content-Type %q, want %q", g, e)
186 t.Error("got Close true, want false")
188 // Depending on map iteration, body can be either of these.
189 expectedBody := "foo=bar&foo=bar2&bar=baz"
190 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
191 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
192 t.Errorf("got ContentLength %d, want %d", g, e)
194 bodyb, err := ioutil.ReadAll(tr.req.Body)
196 t.Fatalf("ReadAll on req.Body: %v", err)
198 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
199 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
203 func TestClientRedirects(t *testing.T) {
206 var ts *httptest.Server
207 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
208 n, _ := strconv.Atoi(r.FormValue("n"))
209 // Test Referer header. (7 is arbitrary position to test at)
211 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
212 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
216 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
219 fmt.Fprintf(w, "n=%d", n)
224 defer tr.CloseIdleConnections()
226 c := &Client{Transport: tr}
227 _, err := c.Get(ts.URL)
228 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
229 t.Errorf("with default client Get, expected error %q, got %q", e, g)
232 // HEAD request should also have the ability to follow redirects.
233 _, err = c.Head(ts.URL)
234 if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
235 t.Errorf("with default client Head, expected error %q, got %q", e, g)
238 // Do should also follow redirects.
239 greq, _ := NewRequest("GET", ts.URL, nil)
241 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
242 t.Errorf("with default client Do, expected error %q, got %q", e, g)
245 // Requests with an empty Method should also redirect (Issue 12705)
248 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
249 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
253 var lastVia []*Request
257 CheckRedirect: func(req *Request, via []*Request) error {
263 res, err := c.Get(ts.URL)
265 t.Fatalf("Get error: %v", err)
268 finalUrl := res.Request.URL.String()
269 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
270 t.Errorf("with custom client, expected error %q, got %q", e, g)
272 if !strings.HasSuffix(finalUrl, "/?n=15") {
273 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
275 if e, g := 15, len(lastVia); e != g {
276 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
279 // Test that Request.Cancel is propagated between requests (Issue 14053)
280 creq, _ := NewRequest("HEAD", ts.URL, nil)
281 cancel := make(chan struct{})
283 if _, err := c.Do(creq); err != nil {
287 t.Fatal("didn't see redirect")
289 if lastReq.Cancel != cancel {
290 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
293 checkErr = errors.New("no redirects allowed")
294 res, err = c.Get(ts.URL)
295 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
296 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
299 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
302 if res.Header.Get("Location") == "" {
303 t.Errorf("no Location header in Response")
307 func TestClientRedirectContext(t *testing.T) {
310 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
311 Redirect(w, r, "/", StatusTemporaryRedirect)
316 defer tr.CloseIdleConnections()
318 ctx, cancel := context.WithCancel(context.Background())
321 CheckRedirect: func(req *Request, via []*Request) error {
324 return errors.New("too many redirects")
329 req, _ := NewRequest("GET", ts.URL, nil)
330 req = req.WithContext(ctx)
332 ue, ok := err.(*url.Error)
334 t.Fatalf("got error %T; want *url.Error", err)
336 if ue.Err != context.Canceled {
337 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
341 type redirectTest struct {
343 want int // response code
347 func TestPostRedirects(t *testing.T) {
348 postRedirectTests := []redirectTest{
350 {"/?code=301&next=302", 200, "c301"},
351 {"/?code=302&next=302", 200, "c302"},
352 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
353 {"/?code=304", 304, "c304"},
354 {"/?code=305", 305, "c305"},
355 {"/?code=307&next=303,308,302", 200, "c307"},
356 {"/?code=308&next=302,301", 200, "c308"},
357 {"/?code=404", 404, "c404"},
360 wantSegments := []string{
362 `POST /?code=301&next=302 "c301"`,
363 `GET /?code=302 "c301"`,
365 `POST /?code=302&next=302 "c302"`,
366 `GET /?code=302 "c302"`,
368 `POST /?code=303&next=301 "c303wc301"`,
369 `GET /?code=301 "c303wc301"`,
371 `POST /?code=304 "c304"`,
372 `POST /?code=305 "c305"`,
373 `POST /?code=307&next=303,308,302 "c307"`,
374 `POST /?code=303&next=308,302 "c307"`,
375 `GET /?code=308&next=302 "c307"`,
376 `GET /?code=302 "c307"`,
378 `POST /?code=308&next=302,301 "c308"`,
379 `POST /?code=302&next=301 "c308"`,
380 `GET /?code=301 "c308"`,
382 `POST /?code=404 "c404"`,
384 want := strings.Join(wantSegments, "\n")
385 testRedirectsByMethod(t, "POST", postRedirectTests, want)
388 func TestDeleteRedirects(t *testing.T) {
389 deleteRedirectTests := []redirectTest{
391 {"/?code=301&next=302,308", 200, "c301"},
392 {"/?code=302&next=302", 200, "c302"},
393 {"/?code=303", 200, "c303"},
394 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
395 {"/?code=308&next=307", 200, "c308"},
396 {"/?code=404", 404, "c404"},
399 wantSegments := []string{
401 `DELETE /?code=301&next=302,308 "c301"`,
402 `GET /?code=302&next=308 "c301"`,
403 `GET /?code=308 "c301"`,
405 `DELETE /?code=302&next=302 "c302"`,
406 `GET /?code=302 "c302"`,
408 `DELETE /?code=303 "c303"`,
410 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
411 `DELETE /?code=301&next=308,303,302,304 "c307"`,
412 `GET /?code=308&next=303,302,304 "c307"`,
413 `GET /?code=303&next=302,304 "c307"`,
414 `GET /?code=302&next=304 "c307"`,
415 `GET /?code=304 "c307"`,
416 `DELETE /?code=308&next=307 "c308"`,
417 `DELETE /?code=307 "c308"`,
419 `DELETE /?code=404 "c404"`,
421 want := strings.Join(wantSegments, "\n")
422 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
425 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
431 var ts *httptest.Server
432 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
434 slurp, _ := ioutil.ReadAll(r.Body)
435 fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp)
437 urlQuery := r.URL.Query()
438 if v := urlQuery.Get("code"); v != "" {
440 if final := urlQuery.Get("next"); final != "" {
441 splits := strings.Split(final, ",")
442 first, rest := splits[0], splits[1:]
443 location = fmt.Sprintf("%s?code=%s", location, first)
445 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
448 code, _ := strconv.Atoi(v)
450 w.Header().Set("Location", location)
457 for _, tt := range table {
458 content := tt.redirectBody
459 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
460 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
461 res, err := DefaultClient.Do(req)
466 if res.StatusCode != tt.want {
467 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
474 got = strings.TrimSpace(got)
475 want = strings.TrimSpace(want)
478 t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want)
482 func TestClientRedirectUseResponse(t *testing.T) {
485 const body = "Hello, world."
486 var ts *httptest.Server
487 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
488 if strings.Contains(r.URL.Path, "/other") {
489 io.WriteString(w, "wrong body")
491 w.Header().Set("Location", ts.URL+"/other")
492 w.WriteHeader(StatusFound)
493 io.WriteString(w, body)
499 defer tr.CloseIdleConnections()
503 CheckRedirect: func(req *Request, via []*Request) error {
504 if req.Response == nil {
505 t.Error("expected non-nil Request.Response")
507 return ErrUseLastResponse
510 res, err := c.Get(ts.URL)
514 if res.StatusCode != StatusFound {
515 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
517 defer res.Body.Close()
518 slurp, err := ioutil.ReadAll(res.Body)
522 if string(slurp) != body {
523 t.Errorf("body = %q; want %q", slurp, body)
527 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
528 // have a Location header.
529 func TestClientRedirect308NoLocation(t *testing.T) {
532 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
533 w.Header().Set("Foo", "Bar")
537 res, err := Get(ts.URL)
542 if res.StatusCode != 308 {
543 t.Errorf("status = %d; want %d", res.StatusCode, 308)
545 if got := res.Header.Get("Foo"); got != "Bar" {
546 t.Errorf("Foo header = %q; want Bar", got)
550 // Don't follow a 307/308 if we can't resent the request body.
551 func TestClientRedirect308NoGetBody(t *testing.T) {
554 const fakeURL = "https://localhost:1234/" // won't be hit
555 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
556 w.Header().Set("Location", fakeURL)
560 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
564 req.GetBody = nil // so it can't rewind.
565 res, err := DefaultClient.Do(req)
570 if res.StatusCode != 308 {
571 t.Errorf("status = %d; want %d", res.StatusCode, 308)
573 if got := res.Header.Get("Location"); got != fakeURL {
574 t.Errorf("Location header = %q; want %q", got, fakeURL)
578 var expectedCookies = []*Cookie{
579 {Name: "ChocolateChip", Value: "tasty"},
580 {Name: "First", Value: "Hit"},
581 {Name: "Second", Value: "Hit"},
584 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
585 for _, cookie := range r.Cookies() {
588 if r.URL.Path == "/" {
589 SetCookie(w, expectedCookies[1])
590 Redirect(w, r, "/second", StatusMovedPermanently)
592 SetCookie(w, expectedCookies[2])
593 w.Write([]byte("hello"))
597 func TestClientSendsCookieFromJar(t *testing.T) {
599 tr := &recordingTransport{}
600 client := &Client{Transport: tr}
601 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
602 us := "http://dummy.faketld/"
603 u, _ := url.Parse(us)
604 client.Jar.SetCookies(u, expectedCookies)
606 client.Get(us) // Note: doesn't hit network
607 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
609 client.Head(us) // Note: doesn't hit network
610 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
612 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
613 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
615 client.PostForm(us, url.Values{}) // Note: doesn't hit network
616 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
618 req, _ := NewRequest("GET", us, nil)
619 client.Do(req) // Note: doesn't hit network
620 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
622 req, _ = NewRequest("POST", us, nil)
623 client.Do(req) // Note: doesn't hit network
624 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
627 // Just enough correctness for our redirect tests. Uses the URL.Host as the
628 // scope of all cookies.
629 type TestJar struct {
631 perURL map[string][]*Cookie
634 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
638 j.perURL = make(map[string][]*Cookie)
640 j.perURL[u.Host] = cookies
643 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
646 return j.perURL[u.Host]
649 func TestRedirectCookiesJar(t *testing.T) {
652 var ts *httptest.Server
653 ts = httptest.NewServer(echoCookiesRedirectHandler)
656 defer tr.CloseIdleConnections()
661 u, _ := url.Parse(ts.URL)
662 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
663 resp, err := c.Get(ts.URL)
665 t.Fatalf("Get: %v", err)
668 matchReturnedCookies(t, expectedCookies, resp.Cookies())
671 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
672 if len(given) != len(expected) {
673 t.Logf("Received cookies: %v", given)
674 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
676 for _, ec := range expected {
678 for _, c := range given {
679 if ec.Name == c.Name && ec.Value == c.Value {
685 t.Errorf("Missing cookie %v", ec)
690 func TestJarCalls(t *testing.T) {
692 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
693 pathSuffix := r.RequestURI[1:]
694 if r.RequestURI == "/nosetcookie" {
695 return // don't set cookies for this path
697 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
698 if r.RequestURI == "/" {
699 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
703 jar := new(RecordingJar)
706 Transport: &Transport{
707 Dial: func(_ string, _ string) (net.Conn, error) {
708 return net.Dial("tcp", ts.Listener.Addr().String())
712 _, err := c.Get("http://firsthost.fake/")
716 _, err = c.Get("http://firsthost.fake/nosetcookie")
720 got := jar.log.String()
721 want := `Cookies("http://firsthost.fake/")
722 SetCookie("http://firsthost.fake/", [name=val])
723 Cookies("http://secondhost.fake/secondpath")
724 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
725 Cookies("http://firsthost.fake/nosetcookie")
728 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
732 // RecordingJar keeps a log of calls made to it, without
733 // tracking any cookies.
734 type RecordingJar struct {
739 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
740 j.logf("SetCookie(%q, %v)\n", u, cookies)
743 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
744 j.logf("Cookies(%q)\n", u)
748 func (j *RecordingJar) logf(format string, args ...interface{}) {
751 fmt.Fprintf(&j.log, format, args...)
754 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
755 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
757 func testStreamingGet(t *testing.T, h2 bool) {
759 say := make(chan string)
760 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
762 for str := range say {
770 res, err := c.Get(cst.ts.URL)
775 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
777 n, err := io.ReadFull(res.Body, buf[0:len(str)])
779 t.Fatalf("ReadFull on %q: %v", str, err)
782 t.Fatalf("Receiving %q, only read %d bytes", str, n)
784 got := string(buf[0:n])
786 t.Fatalf("Expected %q, got %q", str, got)
790 _, err = io.ReadFull(res.Body, buf[0:1])
792 t.Fatalf("at end expected EOF, got %v", err)
796 type writeCountingConn struct {
801 func (c *writeCountingConn) Write(p []byte) (int, error) {
803 return c.Conn.Write(p)
806 // TestClientWrites verifies that client requests are buffered and we
807 // don't send a TCP packet per line of the http request + body.
808 func TestClientWrites(t *testing.T) {
810 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
815 dialer := func(netz string, addr string) (net.Conn, error) {
816 c, err := net.Dial(netz, addr)
818 c = &writeCountingConn{c, &writes}
822 c := &Client{Transport: &Transport{Dial: dialer}}
824 _, err := c.Get(ts.URL)
829 t.Errorf("Get request did %d Write calls, want 1", writes)
833 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
838 t.Errorf("Post request did %d Write calls, want 1", writes)
842 func TestClientInsecureTransport(t *testing.T) {
845 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
846 w.Write([]byte("Hello"))
848 errc := make(chanWriter, 10) // but only expecting 1
849 ts.Config.ErrorLog = log.New(errc, "", 0)
852 // TODO(bradfitz): add tests for skipping hostname checks too?
853 // would require a new cert for testing, and probably
854 // redundant with these tests.
855 for _, insecure := range []bool{true, false} {
857 TLSClientConfig: &tls.Config{
858 InsecureSkipVerify: insecure,
861 defer tr.CloseIdleConnections()
862 c := &Client{Transport: tr}
863 res, err := c.Get(ts.URL)
864 if (err == nil) != insecure {
865 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
874 if !strings.Contains(v, "TLS handshake error") {
875 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
877 case <-time.After(5 * time.Second):
878 t.Errorf("timeout waiting for logged error")
883 func TestClientErrorWithRequestURI(t *testing.T) {
885 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
886 req.RequestURI = "/this/field/is/illegal/and/should/error/"
887 _, err := DefaultClient.Do(req)
889 t.Fatalf("expected an error")
891 if !strings.Contains(err.Error(), "RequestURI") {
892 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
896 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
897 certs := x509.NewCertPool()
898 for _, c := range ts.TLS.Certificates {
899 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
901 t.Fatalf("error parsing server's root cert: %v", err)
903 for _, root := range roots {
908 TLSClientConfig: &tls.Config{RootCAs: certs},
912 func TestClientWithCorrectTLSServerName(t *testing.T) {
915 const serverName = "example.com"
916 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
917 if r.TLS.ServerName != serverName {
918 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
923 trans := newTLSTransport(t, ts)
924 trans.TLSClientConfig.ServerName = serverName
925 c := &Client{Transport: trans}
926 if _, err := c.Get(ts.URL); err != nil {
927 t.Fatalf("expected successful TLS connection, got error: %v", err)
931 func TestClientWithIncorrectTLSServerName(t *testing.T) {
933 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
935 errc := make(chanWriter, 10) // but only expecting 1
936 ts.Config.ErrorLog = log.New(errc, "", 0)
938 trans := newTLSTransport(t, ts)
939 trans.TLSClientConfig.ServerName = "badserver"
940 c := &Client{Transport: trans}
941 _, err := c.Get(ts.URL)
943 t.Fatalf("expected an error")
945 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
946 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
950 if !strings.Contains(v, "TLS handshake error") {
951 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
953 case <-time.After(5 * time.Second):
954 t.Errorf("timeout waiting for logged error")
958 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
961 // tls.Config.ServerName (non-empty, set to "example.com") takes
962 // precedence over "some-other-host.tld" which previously incorrectly
963 // took precedence. We don't actually connect to (or even resolve)
964 // "some-other-host.tld", though, because of the Transport.Dial hook.
966 // The httptest.Server has a cert with "example.com" as its name.
967 func TestTransportUsesTLSConfigServerName(t *testing.T) {
969 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
970 w.Write([]byte("Hello"))
974 tr := newTLSTransport(t, ts)
975 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
976 tr.Dial = func(netw, addr string) (net.Conn, error) {
977 return net.Dial(netw, ts.Listener.Addr().String())
979 defer tr.CloseIdleConnections()
980 c := &Client{Transport: tr}
981 res, err := c.Get("https://some-other-host.tld/")
988 func TestResponseSetsTLSConnectionState(t *testing.T) {
990 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
991 w.Write([]byte("Hello"))
995 tr := newTLSTransport(t, ts)
996 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
997 tr.Dial = func(netw, addr string) (net.Conn, error) {
998 return net.Dial(netw, ts.Listener.Addr().String())
1000 defer tr.CloseIdleConnections()
1001 c := &Client{Transport: tr}
1002 res, err := c.Get("https://example.com/")
1006 defer res.Body.Close()
1008 t.Fatal("Response didn't set TLS Connection State.")
1010 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
1011 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
1015 // Check that an HTTPS client can interpret a particular TLS error
1016 // to determine that the server is speaking HTTP.
1017 // See golang.org/issue/11111.
1018 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1020 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1021 ts.Config.ErrorLog = quietLog
1024 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1025 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1026 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1030 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1031 func TestClientHeadContentLength_h1(t *testing.T) {
1032 testClientHeadContentLength(t, h1Mode)
1035 func TestClientHeadContentLength_h2(t *testing.T) {
1036 testClientHeadContentLength(t, h2Mode)
1039 func testClientHeadContentLength(t *testing.T, h2 bool) {
1041 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1042 if v := r.FormValue("cl"); v != "" {
1043 w.Header().Set("Content-Length", v)
1051 {"/?cl=1234", 1234},
1055 for _, tt := range tests {
1056 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1057 res, err := cst.c.Do(req)
1061 if res.ContentLength != tt.want {
1062 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1064 bs, err := ioutil.ReadAll(res.Body)
1069 t.Errorf("Unexpected content: %q", bs)
1074 func TestEmptyPasswordAuth(t *testing.T) {
1078 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1079 auth := r.Header.Get("Authorization")
1080 if strings.HasPrefix(auth, "Basic ") {
1082 decoded, err := base64.StdEncoding.DecodeString(encoded)
1086 expected := gopher + ":"
1087 s := string(decoded)
1089 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1092 t.Errorf("Invalid auth %q", auth)
1097 defer tr.CloseIdleConnections()
1098 c := &Client{Transport: tr}
1099 req, err := NewRequest("GET", ts.URL, nil)
1103 req.URL.User = url.User(gopher)
1104 resp, err := c.Do(req)
1108 defer resp.Body.Close()
1111 func TestBasicAuth(t *testing.T) {
1113 tr := &recordingTransport{}
1114 client := &Client{Transport: tr}
1116 url := "http://My%20User:My%20Pass@dummy.faketld/"
1117 expected := "My User:My Pass"
1120 if tr.req.Method != "GET" {
1121 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1123 if tr.req.URL.String() != url {
1124 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1126 if tr.req.Header == nil {
1127 t.Fatalf("expected non-nil request Header")
1129 auth := tr.req.Header.Get("Authorization")
1130 if strings.HasPrefix(auth, "Basic ") {
1132 decoded, err := base64.StdEncoding.DecodeString(encoded)
1136 s := string(decoded)
1138 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1141 t.Errorf("Invalid auth %q", auth)
1145 func TestBasicAuthHeadersPreserved(t *testing.T) {
1147 tr := &recordingTransport{}
1148 client := &Client{Transport: tr}
1150 // If Authorization header is provided, username in URL should not override it
1151 url := "http://My%20User@dummy.faketld/"
1152 req, err := NewRequest("GET", url, nil)
1156 req.SetBasicAuth("My User", "My Pass")
1157 expected := "My User:My Pass"
1160 if tr.req.Method != "GET" {
1161 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1163 if tr.req.URL.String() != url {
1164 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1166 if tr.req.Header == nil {
1167 t.Fatalf("expected non-nil request Header")
1169 auth := tr.req.Header.Get("Authorization")
1170 if strings.HasPrefix(auth, "Basic ") {
1172 decoded, err := base64.StdEncoding.DecodeString(encoded)
1176 s := string(decoded)
1178 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1181 t.Errorf("Invalid auth %q", auth)
1186 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1187 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1189 func testClientTimeout(t *testing.T, h2 bool) {
1192 testDone := make(chan struct{}) // closed in defer below
1194 sawRoot := make(chan bool, 1)
1195 sawSlow := make(chan bool, 1)
1196 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1197 if r.URL.Path == "/" {
1199 Redirect(w, r, "/slow", StatusFound)
1202 if r.URL.Path == "/slow" {
1204 w.Write([]byte("Hello"))
1211 defer close(testDone) // before cst.close, to unblock /slow handler
1213 // 200ms should be long enough to get a normal request (the /
1214 // handler), but not so long that it makes the test slow.
1215 const timeout = 200 * time.Millisecond
1216 cst.c.Timeout = timeout
1218 res, err := cst.c.Get(cst.ts.URL)
1220 if strings.Contains(err.Error(), "Client.Timeout") {
1221 t.Skipf("host too slow to get fast resource in %v", timeout)
1230 t.Fatal("handler never got / request")
1237 t.Fatal("handler never got /slow request")
1240 errc := make(chan error, 1)
1242 _, err := ioutil.ReadAll(res.Body)
1247 const failTime = 5 * time.Second
1251 t.Fatal("expected error from ReadAll")
1253 ne, ok := err.(net.Error)
1255 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1256 } else if !ne.Timeout() {
1257 t.Errorf("net.Error.Timeout = false; want true")
1259 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1260 t.Errorf("error string = %q; missing timeout substring", got)
1262 case <-time.After(failTime):
1263 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1267 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1268 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1270 // Client.Timeout firing before getting to the body
1271 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1274 donec := make(chan bool, 1)
1275 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1279 // Note that we use a channel send here and not a close.
1280 // The race detector doesn't know that we're waiting for a timeout
1281 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1282 // with us closing it. If we timed out immediately, we could close the testserver
1283 // before we entered the handler. We're not timing out immediately and there's
1284 // no way we would be done before we entered the handler, but the race detector
1285 // doesn't know this, so synchronize explicitly.
1286 defer func() { donec <- true }()
1288 cst.c.Timeout = 5 * time.Millisecond
1289 res, err := cst.c.Get(cst.ts.URL)
1292 t.Fatal("got response from Get; expected error")
1294 if _, ok := err.(*url.Error); !ok {
1295 t.Fatalf("Got error of type %T; want *url.Error", err)
1297 ne, ok := err.(net.Error)
1299 t.Fatalf("Got error of type %T; want some net.Error", err)
1302 t.Error("net.Error.Timeout = false; want true")
1304 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1305 t.Errorf("error string = %q; missing timeout substring", got)
1309 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1311 func TestClientTimeoutCancel(t *testing.T) {
1315 testDone := make(chan struct{})
1316 ctx, cancel := context.WithCancel(context.Background())
1318 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1323 defer close(testDone)
1325 cst.c.Timeout = 1 * time.Hour
1326 req, _ := NewRequest("GET", cst.ts.URL, nil)
1327 req.Cancel = ctx.Done()
1328 res, err := cst.c.Do(req)
1333 _, err = io.Copy(ioutil.Discard, res.Body)
1334 if err != ExportErrRequestCanceled {
1335 t.Fatalf("error = %v; want errRequestCanceled", err)
1339 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1340 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1341 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1344 saw := make(chan string, 2)
1345 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1347 if r.URL.Path == "/" {
1348 Redirect(w, r, "/foo", StatusFound) // which includes a body
1353 res, err := cst.c.Get(cst.ts.URL)
1357 _, err = ioutil.ReadAll(res.Body)
1367 t.Fatal("server didn't see a request")
1372 case second = <-saw:
1374 t.Fatal("server didn't see a second request")
1377 if first != second {
1378 t.Fatal("server saw different client ports before & after the redirect")
1382 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1383 type eofReaderFunc func()
1385 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1390 func TestReferer(t *testing.T) {
1392 lastReq, newReq string // from -> to URLs
1396 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1397 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1399 // don't send a user and password:
1400 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1401 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1404 {"http://test.com", "http://link.com", "http://test.com"},
1405 {"https://test.com", "https://link.com", "https://test.com"},
1407 // https to http doesn't send a referer:
1408 {"https://test.com", "http://link.com", ""},
1409 {"https://gopher:go@test.com", "http://link.com", ""},
1411 for _, tt := range tests {
1412 l, err := url.Parse(tt.lastReq)
1416 n, err := url.Parse(tt.newReq)
1420 r := ExportRefererForURL(l, n)
1422 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1427 // issue15577Tripper returns a Response with a redirect response
1428 // header and doesn't populate its Response.Request field.
1429 type issue15577Tripper struct{}
1431 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1434 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1435 Body: ioutil.NopCloser(strings.NewReader("")),
1440 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1441 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1443 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1444 Transport: issue15577Tripper{},
1446 // Check that this doesn't crash:
1447 c.Get("http://dummy.tld")
1450 // Issue 4800: copy (some) headers when Client follows a redirect
1451 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1453 ua = "some-agent/1.2"
1457 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1459 "User-Agent": []string{ua},
1460 "X-Foo": []string{xfoo},
1461 "Referer": []string{ts2URL},
1462 "Accept-Encoding": []string{"gzip"},
1464 if !reflect.DeepEqual(r.Header, want) {
1465 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1468 w.Header().Set("Result", "got errors")
1470 w.Header().Set("Result", "ok")
1474 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1475 Redirect(w, r, ts1.URL, StatusFound)
1481 defer tr.CloseIdleConnections()
1484 CheckRedirect: func(r *Request, via []*Request) error {
1486 "User-Agent": []string{ua},
1487 "X-Foo": []string{xfoo},
1488 "Referer": []string{ts2URL},
1490 if !reflect.DeepEqual(r.Header, want) {
1491 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1497 req, _ := NewRequest("GET", ts2.URL, nil)
1498 req.Header.Add("User-Agent", ua)
1499 req.Header.Add("X-Foo", xfoo)
1500 req.Header.Add("Cookie", "foo=bar")
1501 req.Header.Add("Authorization", "secretpassword")
1502 res, err := c.Do(req)
1506 defer res.Body.Close()
1507 if res.StatusCode != 200 {
1510 if got := res.Header.Get("Result"); got != "ok" {
1511 t.Errorf("result = %q; want ok", got)
1515 // Issue 17494: cookies should be altered when Client follows redirects.
1516 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1517 cookieMap := func(cs []*Cookie) map[string][]string {
1518 m := make(map[string][]string)
1519 for _, c := range cs {
1520 m[c.Name] = append(m[c.Name], c.Value)
1525 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1526 var want map[string][]string
1527 got := cookieMap(r.Cookies())
1529 c, _ := r.Cookie("Cycle")
1532 want = map[string][]string{
1533 "Cookie1": {"OldValue1a", "OldValue1b"},
1534 "Cookie2": {"OldValue2"},
1535 "Cookie3": {"OldValue3a", "OldValue3b"},
1536 "Cookie4": {"OldValue4"},
1539 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1540 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1541 Redirect(w, r, "/", StatusFound)
1543 want = map[string][]string{
1544 "Cookie1": {"OldValue1a", "OldValue1b"},
1545 "Cookie3": {"OldValue3a", "OldValue3b"},
1546 "Cookie4": {"OldValue4"},
1549 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1550 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1551 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1552 Redirect(w, r, "/", StatusFound)
1554 want = map[string][]string{
1555 "Cookie1": {"OldValue1a", "OldValue1b"},
1556 "Cookie3": {"NewValue3"},
1557 "Cookie4": {"NewValue4"},
1560 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1561 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1562 Redirect(w, r, "/", StatusFound)
1564 want = map[string][]string{
1565 "Cookie1": {"OldValue1a", "OldValue1b"},
1566 "Cookie3": {"NewValue3"},
1567 "Cookie4": {"NewValue4"},
1568 "Cookie5": {"NewValue5"},
1571 // Don't redirect to ensure the loop ends.
1573 t.Errorf("unexpected redirect cycle")
1577 if !reflect.DeepEqual(got, want) {
1578 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1584 defer tr.CloseIdleConnections()
1585 jar, _ := cookiejar.New(nil)
1591 u, _ := url.Parse(ts.URL)
1592 req, _ := NewRequest("GET", ts.URL, nil)
1593 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1594 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1595 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1596 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1597 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1598 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1599 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1600 res, err := c.Do(req)
1604 defer res.Body.Close()
1605 if res.StatusCode != 200 {
1610 // Part of Issue 4800
1611 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1618 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1619 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1621 // Sensitive headers:
1622 {"cookie", "http://foo.com/", "http://bar.com/", false},
1623 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1624 {"authorization", "http://foo.com/", "http://bar.com/", false},
1625 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1627 // But subdomains should work:
1628 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1629 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1630 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1631 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1632 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1634 for i, tt := range tests {
1635 u0, err := url.Parse(tt.initialURL)
1637 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1640 u1, err := url.Parse(tt.destURL)
1642 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1645 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1647 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1648 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1653 func TestClientRedirectTypes(t *testing.T) {
1657 tests := [...]struct {
1660 wantMethod string // desired subsequent client method
1662 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1663 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1664 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1665 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1666 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1668 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1669 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1670 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1671 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1672 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1674 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1675 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1676 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1677 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1678 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1680 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1681 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1682 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1683 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1684 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1686 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1687 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1688 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1689 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1690 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1692 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1693 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1694 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1695 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1696 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1699 handlerc := make(chan HandlerFunc, 1)
1701 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1708 defer tr.CloseIdleConnections()
1710 for i, tt := range tests {
1711 handlerc <- func(w ResponseWriter, r *Request) {
1712 w.Header().Set("Location", ts.URL)
1713 w.WriteHeader(tt.serverStatus)
1716 req, err := NewRequest(tt.method, ts.URL, nil)
1718 t.Errorf("#%d: NewRequest: %v", i, err)
1722 c := &Client{Transport: tr}
1723 c.CheckRedirect = func(req *Request, via []*Request) error {
1724 if got, want := req.Method, tt.wantMethod; got != want {
1725 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1727 handlerc <- func(rw ResponseWriter, req *Request) {
1728 // TODO: Check that the body is valid when we do 307 and 308 support
1733 res, err := c.Do(req)
1735 t.Errorf("#%d: Response: %v", i, err)
1743 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1744 // Its Read returns readErr and increments *readCalls atomically.
1745 // Its Close returns nil and increments *closeCalls atomically.
1746 type issue18239Body struct {
1752 func (b issue18239Body) Read([]byte) (int, error) {
1753 atomic.AddInt32(b.readCalls, 1)
1757 func (b issue18239Body) Close() error {
1758 atomic.AddInt32(b.closeCalls, 1)
1762 // Issue 18239: make sure the Transport doesn't retry requests with bodies.
1763 // (Especially if Request.GetBody is not defined.)
1764 func TestTransportBodyReadError(t *testing.T) {
1767 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1768 if r.URL.Path == "/ping" {
1771 buf := make([]byte, 1)
1772 n, err := r.Body.Read(buf)
1773 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1777 defer tr.CloseIdleConnections()
1778 c := &Client{Transport: tr}
1780 // Do one initial successful request to create an idle TCP connection
1781 // for the subsequent request to reuse. (The Transport only retries
1782 // requests on reused connections.)
1783 res, err := c.Get(ts.URL + "/ping")
1789 var readCallsAtomic int32
1790 var closeCallsAtomic int32 // atomic
1791 someErr := errors.New("some body read error")
1792 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1794 req, err := NewRequest("POST", ts.URL, body)
1798 _, err = tr.RoundTrip(req)
1800 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1803 // And verify that our Body wasn't used multiple times, which
1804 // would indicate retries. (as it buggily was during part of
1805 // Go 1.8's dev cycle)
1806 readCalls := atomic.LoadInt32(&readCallsAtomic)
1807 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1809 t.Errorf("read calls = %d; want 1", readCalls)
1811 if closeCalls != 1 {
1812 t.Errorf("close calls = %d; want 1", closeCalls)