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"`,
365 `POST /?code=302&next=302 "c302"`,
368 `POST /?code=303&next=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 ""`,
376 `GET /?code=302 "c307"`,
378 `POST /?code=308&next=302,301 "c308"`,
379 `POST /?code=302&next=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 ""`,
405 `DELETE /?code=302&next=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 ""`,
413 `GET /?code=303&next=302,304 "c307"`,
414 `GET /?code=302&next=304 ""`,
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", r.Method, r.RequestURI, slurp)
436 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
437 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
441 urlQuery := r.URL.Query()
442 if v := urlQuery.Get("code"); v != "" {
444 if final := urlQuery.Get("next"); final != "" {
445 splits := strings.Split(final, ",")
446 first, rest := splits[0], splits[1:]
447 location = fmt.Sprintf("%s?code=%s", location, first)
449 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
452 code, _ := strconv.Atoi(v)
454 w.Header().Set("Location", location)
461 for _, tt := range table {
462 content := tt.redirectBody
463 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
464 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
465 res, err := DefaultClient.Do(req)
470 if res.StatusCode != tt.want {
471 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
478 got = strings.TrimSpace(got)
479 want = strings.TrimSpace(want)
482 got, want, lines := removeCommonLines(got, want)
483 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
487 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
489 nl := strings.IndexByte(a, '\n')
491 return a, b, commonLines
494 if !strings.HasPrefix(b, line) {
495 return a, b, commonLines
503 func TestClientRedirectUseResponse(t *testing.T) {
506 const body = "Hello, world."
507 var ts *httptest.Server
508 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
509 if strings.Contains(r.URL.Path, "/other") {
510 io.WriteString(w, "wrong body")
512 w.Header().Set("Location", ts.URL+"/other")
513 w.WriteHeader(StatusFound)
514 io.WriteString(w, body)
520 defer tr.CloseIdleConnections()
524 CheckRedirect: func(req *Request, via []*Request) error {
525 if req.Response == nil {
526 t.Error("expected non-nil Request.Response")
528 return ErrUseLastResponse
531 res, err := c.Get(ts.URL)
535 if res.StatusCode != StatusFound {
536 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
538 defer res.Body.Close()
539 slurp, err := ioutil.ReadAll(res.Body)
543 if string(slurp) != body {
544 t.Errorf("body = %q; want %q", slurp, body)
548 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
549 // have a Location header.
550 func TestClientRedirect308NoLocation(t *testing.T) {
553 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
554 w.Header().Set("Foo", "Bar")
558 res, err := Get(ts.URL)
563 if res.StatusCode != 308 {
564 t.Errorf("status = %d; want %d", res.StatusCode, 308)
566 if got := res.Header.Get("Foo"); got != "Bar" {
567 t.Errorf("Foo header = %q; want Bar", got)
571 // Don't follow a 307/308 if we can't resent the request body.
572 func TestClientRedirect308NoGetBody(t *testing.T) {
575 const fakeURL = "https://localhost:1234/" // won't be hit
576 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
577 w.Header().Set("Location", fakeURL)
581 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
585 req.GetBody = nil // so it can't rewind.
586 res, err := DefaultClient.Do(req)
591 if res.StatusCode != 308 {
592 t.Errorf("status = %d; want %d", res.StatusCode, 308)
594 if got := res.Header.Get("Location"); got != fakeURL {
595 t.Errorf("Location header = %q; want %q", got, fakeURL)
599 var expectedCookies = []*Cookie{
600 {Name: "ChocolateChip", Value: "tasty"},
601 {Name: "First", Value: "Hit"},
602 {Name: "Second", Value: "Hit"},
605 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
606 for _, cookie := range r.Cookies() {
609 if r.URL.Path == "/" {
610 SetCookie(w, expectedCookies[1])
611 Redirect(w, r, "/second", StatusMovedPermanently)
613 SetCookie(w, expectedCookies[2])
614 w.Write([]byte("hello"))
618 func TestClientSendsCookieFromJar(t *testing.T) {
620 tr := &recordingTransport{}
621 client := &Client{Transport: tr}
622 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
623 us := "http://dummy.faketld/"
624 u, _ := url.Parse(us)
625 client.Jar.SetCookies(u, expectedCookies)
627 client.Get(us) // Note: doesn't hit network
628 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
630 client.Head(us) // Note: doesn't hit network
631 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
633 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
634 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
636 client.PostForm(us, url.Values{}) // Note: doesn't hit network
637 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
639 req, _ := NewRequest("GET", us, nil)
640 client.Do(req) // Note: doesn't hit network
641 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
643 req, _ = NewRequest("POST", us, nil)
644 client.Do(req) // Note: doesn't hit network
645 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
648 // Just enough correctness for our redirect tests. Uses the URL.Host as the
649 // scope of all cookies.
650 type TestJar struct {
652 perURL map[string][]*Cookie
655 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
659 j.perURL = make(map[string][]*Cookie)
661 j.perURL[u.Host] = cookies
664 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
667 return j.perURL[u.Host]
670 func TestRedirectCookiesJar(t *testing.T) {
673 var ts *httptest.Server
674 ts = httptest.NewServer(echoCookiesRedirectHandler)
677 defer tr.CloseIdleConnections()
682 u, _ := url.Parse(ts.URL)
683 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
684 resp, err := c.Get(ts.URL)
686 t.Fatalf("Get: %v", err)
689 matchReturnedCookies(t, expectedCookies, resp.Cookies())
692 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
693 if len(given) != len(expected) {
694 t.Logf("Received cookies: %v", given)
695 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
697 for _, ec := range expected {
699 for _, c := range given {
700 if ec.Name == c.Name && ec.Value == c.Value {
706 t.Errorf("Missing cookie %v", ec)
711 func TestJarCalls(t *testing.T) {
713 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
714 pathSuffix := r.RequestURI[1:]
715 if r.RequestURI == "/nosetcookie" {
716 return // don't set cookies for this path
718 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
719 if r.RequestURI == "/" {
720 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
724 jar := new(RecordingJar)
727 Transport: &Transport{
728 Dial: func(_ string, _ string) (net.Conn, error) {
729 return net.Dial("tcp", ts.Listener.Addr().String())
733 _, err := c.Get("http://firsthost.fake/")
737 _, err = c.Get("http://firsthost.fake/nosetcookie")
741 got := jar.log.String()
742 want := `Cookies("http://firsthost.fake/")
743 SetCookie("http://firsthost.fake/", [name=val])
744 Cookies("http://secondhost.fake/secondpath")
745 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
746 Cookies("http://firsthost.fake/nosetcookie")
749 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
753 // RecordingJar keeps a log of calls made to it, without
754 // tracking any cookies.
755 type RecordingJar struct {
760 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
761 j.logf("SetCookie(%q, %v)\n", u, cookies)
764 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
765 j.logf("Cookies(%q)\n", u)
769 func (j *RecordingJar) logf(format string, args ...interface{}) {
772 fmt.Fprintf(&j.log, format, args...)
775 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
776 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
778 func testStreamingGet(t *testing.T, h2 bool) {
780 say := make(chan string)
781 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
783 for str := range say {
791 res, err := c.Get(cst.ts.URL)
796 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
798 n, err := io.ReadFull(res.Body, buf[0:len(str)])
800 t.Fatalf("ReadFull on %q: %v", str, err)
803 t.Fatalf("Receiving %q, only read %d bytes", str, n)
805 got := string(buf[0:n])
807 t.Fatalf("Expected %q, got %q", str, got)
811 _, err = io.ReadFull(res.Body, buf[0:1])
813 t.Fatalf("at end expected EOF, got %v", err)
817 type writeCountingConn struct {
822 func (c *writeCountingConn) Write(p []byte) (int, error) {
824 return c.Conn.Write(p)
827 // TestClientWrites verifies that client requests are buffered and we
828 // don't send a TCP packet per line of the http request + body.
829 func TestClientWrites(t *testing.T) {
831 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
836 dialer := func(netz string, addr string) (net.Conn, error) {
837 c, err := net.Dial(netz, addr)
839 c = &writeCountingConn{c, &writes}
843 c := &Client{Transport: &Transport{Dial: dialer}}
845 _, err := c.Get(ts.URL)
850 t.Errorf("Get request did %d Write calls, want 1", writes)
854 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
859 t.Errorf("Post request did %d Write calls, want 1", writes)
863 func TestClientInsecureTransport(t *testing.T) {
866 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
867 w.Write([]byte("Hello"))
869 errc := make(chanWriter, 10) // but only expecting 1
870 ts.Config.ErrorLog = log.New(errc, "", 0)
873 // TODO(bradfitz): add tests for skipping hostname checks too?
874 // would require a new cert for testing, and probably
875 // redundant with these tests.
876 for _, insecure := range []bool{true, false} {
878 TLSClientConfig: &tls.Config{
879 InsecureSkipVerify: insecure,
882 defer tr.CloseIdleConnections()
883 c := &Client{Transport: tr}
884 res, err := c.Get(ts.URL)
885 if (err == nil) != insecure {
886 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
895 if !strings.Contains(v, "TLS handshake error") {
896 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
898 case <-time.After(5 * time.Second):
899 t.Errorf("timeout waiting for logged error")
904 func TestClientErrorWithRequestURI(t *testing.T) {
906 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
907 req.RequestURI = "/this/field/is/illegal/and/should/error/"
908 _, err := DefaultClient.Do(req)
910 t.Fatalf("expected an error")
912 if !strings.Contains(err.Error(), "RequestURI") {
913 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
917 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
918 certs := x509.NewCertPool()
919 for _, c := range ts.TLS.Certificates {
920 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
922 t.Fatalf("error parsing server's root cert: %v", err)
924 for _, root := range roots {
929 TLSClientConfig: &tls.Config{RootCAs: certs},
933 func TestClientWithCorrectTLSServerName(t *testing.T) {
936 const serverName = "example.com"
937 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
938 if r.TLS.ServerName != serverName {
939 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
944 trans := newTLSTransport(t, ts)
945 trans.TLSClientConfig.ServerName = serverName
946 c := &Client{Transport: trans}
947 if _, err := c.Get(ts.URL); err != nil {
948 t.Fatalf("expected successful TLS connection, got error: %v", err)
952 func TestClientWithIncorrectTLSServerName(t *testing.T) {
954 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
956 errc := make(chanWriter, 10) // but only expecting 1
957 ts.Config.ErrorLog = log.New(errc, "", 0)
959 trans := newTLSTransport(t, ts)
960 trans.TLSClientConfig.ServerName = "badserver"
961 c := &Client{Transport: trans}
962 _, err := c.Get(ts.URL)
964 t.Fatalf("expected an error")
966 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
967 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
971 if !strings.Contains(v, "TLS handshake error") {
972 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
974 case <-time.After(5 * time.Second):
975 t.Errorf("timeout waiting for logged error")
979 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
982 // tls.Config.ServerName (non-empty, set to "example.com") takes
983 // precedence over "some-other-host.tld" which previously incorrectly
984 // took precedence. We don't actually connect to (or even resolve)
985 // "some-other-host.tld", though, because of the Transport.Dial hook.
987 // The httptest.Server has a cert with "example.com" as its name.
988 func TestTransportUsesTLSConfigServerName(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.ServerName = "example.com" // one of httptest's Server cert names
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://some-other-host.tld/")
1009 func TestResponseSetsTLSConnectionState(t *testing.T) {
1011 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1012 w.Write([]byte("Hello"))
1016 tr := newTLSTransport(t, ts)
1017 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
1018 tr.Dial = func(netw, addr string) (net.Conn, error) {
1019 return net.Dial(netw, ts.Listener.Addr().String())
1021 defer tr.CloseIdleConnections()
1022 c := &Client{Transport: tr}
1023 res, err := c.Get("https://example.com/")
1027 defer res.Body.Close()
1029 t.Fatal("Response didn't set TLS Connection State.")
1031 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
1032 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
1036 // Check that an HTTPS client can interpret a particular TLS error
1037 // to determine that the server is speaking HTTP.
1038 // See golang.org/issue/11111.
1039 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1041 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1042 ts.Config.ErrorLog = quietLog
1045 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1046 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1047 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1051 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1052 func TestClientHeadContentLength_h1(t *testing.T) {
1053 testClientHeadContentLength(t, h1Mode)
1056 func TestClientHeadContentLength_h2(t *testing.T) {
1057 testClientHeadContentLength(t, h2Mode)
1060 func testClientHeadContentLength(t *testing.T, h2 bool) {
1062 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1063 if v := r.FormValue("cl"); v != "" {
1064 w.Header().Set("Content-Length", v)
1072 {"/?cl=1234", 1234},
1076 for _, tt := range tests {
1077 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1078 res, err := cst.c.Do(req)
1082 if res.ContentLength != tt.want {
1083 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1085 bs, err := ioutil.ReadAll(res.Body)
1090 t.Errorf("Unexpected content: %q", bs)
1095 func TestEmptyPasswordAuth(t *testing.T) {
1099 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1100 auth := r.Header.Get("Authorization")
1101 if strings.HasPrefix(auth, "Basic ") {
1103 decoded, err := base64.StdEncoding.DecodeString(encoded)
1107 expected := gopher + ":"
1108 s := string(decoded)
1110 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1113 t.Errorf("Invalid auth %q", auth)
1118 defer tr.CloseIdleConnections()
1119 c := &Client{Transport: tr}
1120 req, err := NewRequest("GET", ts.URL, nil)
1124 req.URL.User = url.User(gopher)
1125 resp, err := c.Do(req)
1129 defer resp.Body.Close()
1132 func TestBasicAuth(t *testing.T) {
1134 tr := &recordingTransport{}
1135 client := &Client{Transport: tr}
1137 url := "http://My%20User:My%20Pass@dummy.faketld/"
1138 expected := "My User:My Pass"
1141 if tr.req.Method != "GET" {
1142 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1144 if tr.req.URL.String() != url {
1145 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1147 if tr.req.Header == nil {
1148 t.Fatalf("expected non-nil request Header")
1150 auth := tr.req.Header.Get("Authorization")
1151 if strings.HasPrefix(auth, "Basic ") {
1153 decoded, err := base64.StdEncoding.DecodeString(encoded)
1157 s := string(decoded)
1159 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1162 t.Errorf("Invalid auth %q", auth)
1166 func TestBasicAuthHeadersPreserved(t *testing.T) {
1168 tr := &recordingTransport{}
1169 client := &Client{Transport: tr}
1171 // If Authorization header is provided, username in URL should not override it
1172 url := "http://My%20User@dummy.faketld/"
1173 req, err := NewRequest("GET", url, nil)
1177 req.SetBasicAuth("My User", "My Pass")
1178 expected := "My User:My Pass"
1181 if tr.req.Method != "GET" {
1182 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1184 if tr.req.URL.String() != url {
1185 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1187 if tr.req.Header == nil {
1188 t.Fatalf("expected non-nil request Header")
1190 auth := tr.req.Header.Get("Authorization")
1191 if strings.HasPrefix(auth, "Basic ") {
1193 decoded, err := base64.StdEncoding.DecodeString(encoded)
1197 s := string(decoded)
1199 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1202 t.Errorf("Invalid auth %q", auth)
1207 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1208 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1210 func testClientTimeout(t *testing.T, h2 bool) {
1213 testDone := make(chan struct{}) // closed in defer below
1215 sawRoot := make(chan bool, 1)
1216 sawSlow := make(chan bool, 1)
1217 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1218 if r.URL.Path == "/" {
1220 Redirect(w, r, "/slow", StatusFound)
1223 if r.URL.Path == "/slow" {
1225 w.Write([]byte("Hello"))
1232 defer close(testDone) // before cst.close, to unblock /slow handler
1234 // 200ms should be long enough to get a normal request (the /
1235 // handler), but not so long that it makes the test slow.
1236 const timeout = 200 * time.Millisecond
1237 cst.c.Timeout = timeout
1239 res, err := cst.c.Get(cst.ts.URL)
1241 if strings.Contains(err.Error(), "Client.Timeout") {
1242 t.Skipf("host too slow to get fast resource in %v", timeout)
1251 t.Fatal("handler never got / request")
1258 t.Fatal("handler never got /slow request")
1261 errc := make(chan error, 1)
1263 _, err := ioutil.ReadAll(res.Body)
1268 const failTime = 5 * time.Second
1272 t.Fatal("expected error from ReadAll")
1274 ne, ok := err.(net.Error)
1276 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1277 } else if !ne.Timeout() {
1278 t.Errorf("net.Error.Timeout = false; want true")
1280 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1281 t.Errorf("error string = %q; missing timeout substring", got)
1283 case <-time.After(failTime):
1284 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1288 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1289 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1291 // Client.Timeout firing before getting to the body
1292 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1295 donec := make(chan bool, 1)
1296 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1300 // Note that we use a channel send here and not a close.
1301 // The race detector doesn't know that we're waiting for a timeout
1302 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1303 // with us closing it. If we timed out immediately, we could close the testserver
1304 // before we entered the handler. We're not timing out immediately and there's
1305 // no way we would be done before we entered the handler, but the race detector
1306 // doesn't know this, so synchronize explicitly.
1307 defer func() { donec <- true }()
1309 cst.c.Timeout = 5 * time.Millisecond
1310 res, err := cst.c.Get(cst.ts.URL)
1313 t.Fatal("got response from Get; expected error")
1315 if _, ok := err.(*url.Error); !ok {
1316 t.Fatalf("Got error of type %T; want *url.Error", err)
1318 ne, ok := err.(net.Error)
1320 t.Fatalf("Got error of type %T; want some net.Error", err)
1323 t.Error("net.Error.Timeout = false; want true")
1325 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1326 t.Errorf("error string = %q; missing timeout substring", got)
1330 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1332 func TestClientTimeoutCancel(t *testing.T) {
1336 testDone := make(chan struct{})
1337 ctx, cancel := context.WithCancel(context.Background())
1339 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1344 defer close(testDone)
1346 cst.c.Timeout = 1 * time.Hour
1347 req, _ := NewRequest("GET", cst.ts.URL, nil)
1348 req.Cancel = ctx.Done()
1349 res, err := cst.c.Do(req)
1354 _, err = io.Copy(ioutil.Discard, res.Body)
1355 if err != ExportErrRequestCanceled {
1356 t.Fatalf("error = %v; want errRequestCanceled", err)
1360 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1361 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1362 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1365 saw := make(chan string, 2)
1366 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1368 if r.URL.Path == "/" {
1369 Redirect(w, r, "/foo", StatusFound) // which includes a body
1374 res, err := cst.c.Get(cst.ts.URL)
1378 _, err = ioutil.ReadAll(res.Body)
1388 t.Fatal("server didn't see a request")
1393 case second = <-saw:
1395 t.Fatal("server didn't see a second request")
1398 if first != second {
1399 t.Fatal("server saw different client ports before & after the redirect")
1403 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1404 type eofReaderFunc func()
1406 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1411 func TestReferer(t *testing.T) {
1413 lastReq, newReq string // from -> to URLs
1417 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1418 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1420 // don't send a user and password:
1421 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1422 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1425 {"http://test.com", "http://link.com", "http://test.com"},
1426 {"https://test.com", "https://link.com", "https://test.com"},
1428 // https to http doesn't send a referer:
1429 {"https://test.com", "http://link.com", ""},
1430 {"https://gopher:go@test.com", "http://link.com", ""},
1432 for _, tt := range tests {
1433 l, err := url.Parse(tt.lastReq)
1437 n, err := url.Parse(tt.newReq)
1441 r := ExportRefererForURL(l, n)
1443 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1448 // issue15577Tripper returns a Response with a redirect response
1449 // header and doesn't populate its Response.Request field.
1450 type issue15577Tripper struct{}
1452 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1455 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1456 Body: ioutil.NopCloser(strings.NewReader("")),
1461 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1462 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1464 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1465 Transport: issue15577Tripper{},
1467 // Check that this doesn't crash:
1468 c.Get("http://dummy.tld")
1471 // Issue 4800: copy (some) headers when Client follows a redirect
1472 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1474 ua = "some-agent/1.2"
1478 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1480 "User-Agent": []string{ua},
1481 "X-Foo": []string{xfoo},
1482 "Referer": []string{ts2URL},
1483 "Accept-Encoding": []string{"gzip"},
1485 if !reflect.DeepEqual(r.Header, want) {
1486 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1489 w.Header().Set("Result", "got errors")
1491 w.Header().Set("Result", "ok")
1495 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1496 Redirect(w, r, ts1.URL, StatusFound)
1502 defer tr.CloseIdleConnections()
1505 CheckRedirect: func(r *Request, via []*Request) error {
1507 "User-Agent": []string{ua},
1508 "X-Foo": []string{xfoo},
1509 "Referer": []string{ts2URL},
1511 if !reflect.DeepEqual(r.Header, want) {
1512 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1518 req, _ := NewRequest("GET", ts2.URL, nil)
1519 req.Header.Add("User-Agent", ua)
1520 req.Header.Add("X-Foo", xfoo)
1521 req.Header.Add("Cookie", "foo=bar")
1522 req.Header.Add("Authorization", "secretpassword")
1523 res, err := c.Do(req)
1527 defer res.Body.Close()
1528 if res.StatusCode != 200 {
1531 if got := res.Header.Get("Result"); got != "ok" {
1532 t.Errorf("result = %q; want ok", got)
1536 // Issue 17494: cookies should be altered when Client follows redirects.
1537 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1538 cookieMap := func(cs []*Cookie) map[string][]string {
1539 m := make(map[string][]string)
1540 for _, c := range cs {
1541 m[c.Name] = append(m[c.Name], c.Value)
1546 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1547 var want map[string][]string
1548 got := cookieMap(r.Cookies())
1550 c, _ := r.Cookie("Cycle")
1553 want = map[string][]string{
1554 "Cookie1": {"OldValue1a", "OldValue1b"},
1555 "Cookie2": {"OldValue2"},
1556 "Cookie3": {"OldValue3a", "OldValue3b"},
1557 "Cookie4": {"OldValue4"},
1560 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1561 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1562 Redirect(w, r, "/", StatusFound)
1564 want = map[string][]string{
1565 "Cookie1": {"OldValue1a", "OldValue1b"},
1566 "Cookie3": {"OldValue3a", "OldValue3b"},
1567 "Cookie4": {"OldValue4"},
1570 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1571 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1572 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1573 Redirect(w, r, "/", StatusFound)
1575 want = map[string][]string{
1576 "Cookie1": {"OldValue1a", "OldValue1b"},
1577 "Cookie3": {"NewValue3"},
1578 "Cookie4": {"NewValue4"},
1581 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1582 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1583 Redirect(w, r, "/", StatusFound)
1585 want = map[string][]string{
1586 "Cookie1": {"OldValue1a", "OldValue1b"},
1587 "Cookie3": {"NewValue3"},
1588 "Cookie4": {"NewValue4"},
1589 "Cookie5": {"NewValue5"},
1592 // Don't redirect to ensure the loop ends.
1594 t.Errorf("unexpected redirect cycle")
1598 if !reflect.DeepEqual(got, want) {
1599 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1605 defer tr.CloseIdleConnections()
1606 jar, _ := cookiejar.New(nil)
1612 u, _ := url.Parse(ts.URL)
1613 req, _ := NewRequest("GET", ts.URL, nil)
1614 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1615 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1616 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1617 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1618 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1619 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1620 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1621 res, err := c.Do(req)
1625 defer res.Body.Close()
1626 if res.StatusCode != 200 {
1631 // Part of Issue 4800
1632 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1639 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1640 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1642 // Sensitive headers:
1643 {"cookie", "http://foo.com/", "http://bar.com/", false},
1644 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1645 {"authorization", "http://foo.com/", "http://bar.com/", false},
1646 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1648 // But subdomains should work:
1649 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1650 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1651 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1652 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1653 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1655 for i, tt := range tests {
1656 u0, err := url.Parse(tt.initialURL)
1658 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1661 u1, err := url.Parse(tt.destURL)
1663 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1666 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1668 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1669 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1674 func TestClientRedirectTypes(t *testing.T) {
1678 tests := [...]struct {
1681 wantMethod string // desired subsequent client method
1683 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1684 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1685 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1686 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1687 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1689 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1690 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1691 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1692 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1693 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1695 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1696 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1697 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1698 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1699 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1701 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1702 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1703 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1704 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1705 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1707 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1708 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1709 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1710 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1711 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1713 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1714 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1715 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1716 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1717 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1720 handlerc := make(chan HandlerFunc, 1)
1722 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1729 defer tr.CloseIdleConnections()
1731 for i, tt := range tests {
1732 handlerc <- func(w ResponseWriter, r *Request) {
1733 w.Header().Set("Location", ts.URL)
1734 w.WriteHeader(tt.serverStatus)
1737 req, err := NewRequest(tt.method, ts.URL, nil)
1739 t.Errorf("#%d: NewRequest: %v", i, err)
1743 c := &Client{Transport: tr}
1744 c.CheckRedirect = func(req *Request, via []*Request) error {
1745 if got, want := req.Method, tt.wantMethod; got != want {
1746 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1748 handlerc <- func(rw ResponseWriter, req *Request) {
1749 // TODO: Check that the body is valid when we do 307 and 308 support
1754 res, err := c.Do(req)
1756 t.Errorf("#%d: Response: %v", i, err)
1764 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1765 // Its Read returns readErr and increments *readCalls atomically.
1766 // Its Close returns nil and increments *closeCalls atomically.
1767 type issue18239Body struct {
1773 func (b issue18239Body) Read([]byte) (int, error) {
1774 atomic.AddInt32(b.readCalls, 1)
1778 func (b issue18239Body) Close() error {
1779 atomic.AddInt32(b.closeCalls, 1)
1783 // Issue 18239: make sure the Transport doesn't retry requests with bodies.
1784 // (Especially if Request.GetBody is not defined.)
1785 func TestTransportBodyReadError(t *testing.T) {
1788 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1789 if r.URL.Path == "/ping" {
1792 buf := make([]byte, 1)
1793 n, err := r.Body.Read(buf)
1794 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1798 defer tr.CloseIdleConnections()
1799 c := &Client{Transport: tr}
1801 // Do one initial successful request to create an idle TCP connection
1802 // for the subsequent request to reuse. (The Transport only retries
1803 // requests on reused connections.)
1804 res, err := c.Get(ts.URL + "/ping")
1810 var readCallsAtomic int32
1811 var closeCallsAtomic int32 // atomic
1812 someErr := errors.New("some body read error")
1813 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1815 req, err := NewRequest("POST", ts.URL, body)
1819 _, err = tr.RoundTrip(req)
1821 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1824 // And verify that our Body wasn't used multiple times, which
1825 // would indicate retries. (as it buggily was during part of
1826 // Go 1.8's dev cycle)
1827 readCalls := atomic.LoadInt32(&readCallsAtomic)
1828 closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1830 t.Errorf("read calls = %d; want 1", readCalls)
1832 if closeCalls != 1 {
1833 t.Errorf("close calls = %d; want 1", closeCalls)