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.
33 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
34 w.Header().Set("Last-Modified", "sometime")
35 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
38 // pedanticReadAll works like ioutil.ReadAll but additionally
39 // verifies that r obeys the documented io.Reader contract.
40 func pedanticReadAll(r io.Reader) (b []byte, err error) {
45 if n == 0 && err == nil {
46 return nil, fmt.Errorf("Read: n=0 with err=nil")
48 b = append(b, buf[:n]...)
51 if n != 0 || err != io.EOF {
52 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
62 type chanWriter chan string
64 func (w chanWriter) Write(p []byte) (n int, err error) {
69 func TestClient(t *testing.T) {
72 ts := httptest.NewServer(robotsTxtHandler)
75 c := &Client{Transport: &Transport{DisableKeepAlives: true}}
76 r, err := c.Get(ts.URL)
79 b, err = pedanticReadAll(r.Body)
84 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
85 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
89 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
90 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
92 func testClientHead(t *testing.T, h2 bool) {
94 cst := newClientServerTest(t, h2, robotsTxtHandler)
97 r, err := cst.c.Head(cst.ts.URL)
101 if _, ok := r.Header["Last-Modified"]; !ok {
102 t.Error("Last-Modified header not found.")
106 type recordingTransport struct {
110 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
112 return nil, errors.New("dummy impl")
115 func TestGetRequestFormat(t *testing.T) {
118 tr := &recordingTransport{}
119 client := &Client{Transport: tr}
120 url := "http://dummy.faketld/"
121 client.Get(url) // Note: doesn't hit network
122 if tr.req.Method != "GET" {
123 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
125 if tr.req.URL.String() != url {
126 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
128 if tr.req.Header == nil {
129 t.Errorf("expected non-nil request Header")
133 func TestPostRequestFormat(t *testing.T) {
135 tr := &recordingTransport{}
136 client := &Client{Transport: tr}
138 url := "http://dummy.faketld/"
139 json := `{"key":"value"}`
140 b := strings.NewReader(json)
141 client.Post(url, "application/json", b) // Note: doesn't hit network
143 if tr.req.Method != "POST" {
144 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
146 if tr.req.URL.String() != url {
147 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
149 if tr.req.Header == nil {
150 t.Fatalf("expected non-nil request Header")
153 t.Error("got Close true, want false")
155 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
156 t.Errorf("got ContentLength %d, want %d", g, e)
160 func TestPostFormRequestFormat(t *testing.T) {
162 tr := &recordingTransport{}
163 client := &Client{Transport: tr}
165 urlStr := "http://dummy.faketld/"
166 form := make(url.Values)
167 form.Set("foo", "bar")
168 form.Add("foo", "bar2")
169 form.Set("bar", "baz")
170 client.PostForm(urlStr, form) // Note: doesn't hit network
172 if tr.req.Method != "POST" {
173 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
175 if tr.req.URL.String() != urlStr {
176 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
178 if tr.req.Header == nil {
179 t.Fatalf("expected non-nil request Header")
181 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
182 t.Errorf("got Content-Type %q, want %q", g, e)
185 t.Error("got Close true, want false")
187 // Depending on map iteration, body can be either of these.
188 expectedBody := "foo=bar&foo=bar2&bar=baz"
189 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
190 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
191 t.Errorf("got ContentLength %d, want %d", g, e)
193 bodyb, err := ioutil.ReadAll(tr.req.Body)
195 t.Fatalf("ReadAll on req.Body: %v", err)
197 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
198 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
202 func TestClientRedirects(t *testing.T) {
205 var ts *httptest.Server
206 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
207 n, _ := strconv.Atoi(r.FormValue("n"))
208 // Test Referer header. (7 is arbitrary position to test at)
210 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
211 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
215 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
218 fmt.Fprintf(w, "n=%d", n)
223 defer tr.CloseIdleConnections()
225 c := &Client{Transport: tr}
226 _, err := c.Get(ts.URL)
227 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
228 t.Errorf("with default client Get, expected error %q, got %q", e, g)
231 // HEAD request should also have the ability to follow redirects.
232 _, err = c.Head(ts.URL)
233 if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
234 t.Errorf("with default client Head, expected error %q, got %q", e, g)
237 // Do should also follow redirects.
238 greq, _ := NewRequest("GET", ts.URL, nil)
240 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
241 t.Errorf("with default client Do, expected error %q, got %q", e, g)
244 // Requests with an empty Method should also redirect (Issue 12705)
247 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
248 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
252 var lastVia []*Request
256 CheckRedirect: func(req *Request, via []*Request) error {
262 res, err := c.Get(ts.URL)
264 t.Fatalf("Get error: %v", err)
267 finalUrl := res.Request.URL.String()
268 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
269 t.Errorf("with custom client, expected error %q, got %q", e, g)
271 if !strings.HasSuffix(finalUrl, "/?n=15") {
272 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
274 if e, g := 15, len(lastVia); e != g {
275 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
278 // Test that Request.Cancel is propagated between requests (Issue 14053)
279 creq, _ := NewRequest("HEAD", ts.URL, nil)
280 cancel := make(chan struct{})
282 if _, err := c.Do(creq); err != nil {
286 t.Fatal("didn't see redirect")
288 if lastReq.Cancel != cancel {
289 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
292 checkErr = errors.New("no redirects allowed")
293 res, err = c.Get(ts.URL)
294 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
295 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
298 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
301 if res.Header.Get("Location") == "" {
302 t.Errorf("no Location header in Response")
306 func TestClientRedirectContext(t *testing.T) {
309 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
310 Redirect(w, r, "/", StatusTemporaryRedirect)
315 defer tr.CloseIdleConnections()
317 ctx, cancel := context.WithCancel(context.Background())
320 CheckRedirect: func(req *Request, via []*Request) error {
323 return errors.New("too many redirects")
328 req, _ := NewRequest("GET", ts.URL, nil)
329 req = req.WithContext(ctx)
331 ue, ok := err.(*url.Error)
333 t.Fatalf("got error %T; want *url.Error", err)
335 if ue.Err != context.Canceled {
336 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
340 type redirectTest struct {
342 want int // response code
346 func TestPostRedirects(t *testing.T) {
347 postRedirectTests := []redirectTest{
349 {"/?code=301&next=302", 200, "c301"},
350 {"/?code=302&next=302", 200, "c302"},
351 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
352 {"/?code=304", 304, "c304"},
353 {"/?code=305", 305, "c305"},
354 {"/?code=307&next=303,308,302", 200, "c307"},
355 {"/?code=308&next=302,301", 200, "c308"},
356 {"/?code=404", 404, "c404"},
359 wantSegments := []string{
361 `POST /?code=301&next=302 "c301"`,
362 `GET /?code=302 "c301"`,
364 `POST /?code=302&next=302 "c302"`,
365 `GET /?code=302 "c302"`,
367 `POST /?code=303&next=301 "c303wc301"`,
368 `GET /?code=301 "c303wc301"`,
370 `POST /?code=304 "c304"`,
371 `POST /?code=305 "c305"`,
372 `POST /?code=307&next=303,308,302 "c307"`,
373 `POST /?code=303&next=308,302 "c307"`,
374 `GET /?code=308&next=302 "c307"`,
375 `GET /?code=302 "c307"`,
377 `POST /?code=308&next=302,301 "c308"`,
378 `POST /?code=302&next=301 "c308"`,
379 `GET /?code=301 "c308"`,
381 `POST /?code=404 "c404"`,
383 want := strings.Join(wantSegments, "\n")
384 testRedirectsByMethod(t, "POST", postRedirectTests, want)
387 func TestDeleteRedirects(t *testing.T) {
388 deleteRedirectTests := []redirectTest{
390 {"/?code=301&next=302,308", 200, "c301"},
391 {"/?code=302&next=302", 200, "c302"},
392 {"/?code=303", 200, "c303"},
393 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
394 {"/?code=308&next=307", 200, "c308"},
395 {"/?code=404", 404, "c404"},
398 wantSegments := []string{
400 `DELETE /?code=301&next=302,308 "c301"`,
401 `GET /?code=302&next=308 "c301"`,
402 `GET /?code=308 "c301"`,
404 `DELETE /?code=302&next=302 "c302"`,
405 `GET /?code=302 "c302"`,
407 `DELETE /?code=303 "c303"`,
409 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
410 `DELETE /?code=301&next=308,303,302,304 "c307"`,
411 `GET /?code=308&next=303,302,304 "c307"`,
412 `GET /?code=303&next=302,304 "c307"`,
413 `GET /?code=302&next=304 "c307"`,
414 `GET /?code=304 "c307"`,
415 `DELETE /?code=308&next=307 "c308"`,
416 `DELETE /?code=307 "c308"`,
418 `DELETE /?code=404 "c404"`,
420 want := strings.Join(wantSegments, "\n")
421 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
424 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
430 var ts *httptest.Server
431 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
433 slurp, _ := ioutil.ReadAll(r.Body)
434 fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp)
436 urlQuery := r.URL.Query()
437 if v := urlQuery.Get("code"); v != "" {
439 if final := urlQuery.Get("next"); final != "" {
440 splits := strings.Split(final, ",")
441 first, rest := splits[0], splits[1:]
442 location = fmt.Sprintf("%s?code=%s", location, first)
444 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
447 code, _ := strconv.Atoi(v)
449 w.Header().Set("Location", location)
456 for _, tt := range table {
457 content := tt.redirectBody
458 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
459 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
460 res, err := DefaultClient.Do(req)
465 if res.StatusCode != tt.want {
466 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
473 got = strings.TrimSpace(got)
474 want = strings.TrimSpace(want)
477 t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want)
481 func TestClientRedirectUseResponse(t *testing.T) {
484 const body = "Hello, world."
485 var ts *httptest.Server
486 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
487 if strings.Contains(r.URL.Path, "/other") {
488 io.WriteString(w, "wrong body")
490 w.Header().Set("Location", ts.URL+"/other")
491 w.WriteHeader(StatusFound)
492 io.WriteString(w, body)
498 defer tr.CloseIdleConnections()
502 CheckRedirect: func(req *Request, via []*Request) error {
503 if req.Response == nil {
504 t.Error("expected non-nil Request.Response")
506 return ErrUseLastResponse
509 res, err := c.Get(ts.URL)
513 if res.StatusCode != StatusFound {
514 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
516 defer res.Body.Close()
517 slurp, err := ioutil.ReadAll(res.Body)
521 if string(slurp) != body {
522 t.Errorf("body = %q; want %q", slurp, body)
526 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
527 // have a Location header.
528 func TestClientRedirect308NoLocation(t *testing.T) {
531 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
532 w.Header().Set("Foo", "Bar")
536 res, err := Get(ts.URL)
541 if res.StatusCode != 308 {
542 t.Errorf("status = %d; want %d", res.StatusCode, 308)
544 if got := res.Header.Get("Foo"); got != "Bar" {
545 t.Errorf("Foo header = %q; want Bar", got)
549 // Don't follow a 307/308 if we can't resent the request body.
550 func TestClientRedirect308NoGetBody(t *testing.T) {
553 const fakeURL = "https://localhost:1234/" // won't be hit
554 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
555 w.Header().Set("Location", fakeURL)
559 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
563 req.GetBody = nil // so it can't rewind.
564 res, err := DefaultClient.Do(req)
569 if res.StatusCode != 308 {
570 t.Errorf("status = %d; want %d", res.StatusCode, 308)
572 if got := res.Header.Get("Location"); got != fakeURL {
573 t.Errorf("Location header = %q; want %q", got, fakeURL)
577 var expectedCookies = []*Cookie{
578 {Name: "ChocolateChip", Value: "tasty"},
579 {Name: "First", Value: "Hit"},
580 {Name: "Second", Value: "Hit"},
583 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
584 for _, cookie := range r.Cookies() {
587 if r.URL.Path == "/" {
588 SetCookie(w, expectedCookies[1])
589 Redirect(w, r, "/second", StatusMovedPermanently)
591 SetCookie(w, expectedCookies[2])
592 w.Write([]byte("hello"))
596 func TestClientSendsCookieFromJar(t *testing.T) {
598 tr := &recordingTransport{}
599 client := &Client{Transport: tr}
600 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
601 us := "http://dummy.faketld/"
602 u, _ := url.Parse(us)
603 client.Jar.SetCookies(u, expectedCookies)
605 client.Get(us) // Note: doesn't hit network
606 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
608 client.Head(us) // Note: doesn't hit network
609 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
611 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
612 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
614 client.PostForm(us, url.Values{}) // Note: doesn't hit network
615 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
617 req, _ := NewRequest("GET", us, nil)
618 client.Do(req) // Note: doesn't hit network
619 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
621 req, _ = NewRequest("POST", us, nil)
622 client.Do(req) // Note: doesn't hit network
623 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
626 // Just enough correctness for our redirect tests. Uses the URL.Host as the
627 // scope of all cookies.
628 type TestJar struct {
630 perURL map[string][]*Cookie
633 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
637 j.perURL = make(map[string][]*Cookie)
639 j.perURL[u.Host] = cookies
642 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
645 return j.perURL[u.Host]
648 func TestRedirectCookiesJar(t *testing.T) {
651 var ts *httptest.Server
652 ts = httptest.NewServer(echoCookiesRedirectHandler)
655 defer tr.CloseIdleConnections()
660 u, _ := url.Parse(ts.URL)
661 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
662 resp, err := c.Get(ts.URL)
664 t.Fatalf("Get: %v", err)
667 matchReturnedCookies(t, expectedCookies, resp.Cookies())
670 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
671 if len(given) != len(expected) {
672 t.Logf("Received cookies: %v", given)
673 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
675 for _, ec := range expected {
677 for _, c := range given {
678 if ec.Name == c.Name && ec.Value == c.Value {
684 t.Errorf("Missing cookie %v", ec)
689 func TestJarCalls(t *testing.T) {
691 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
692 pathSuffix := r.RequestURI[1:]
693 if r.RequestURI == "/nosetcookie" {
694 return // don't set cookies for this path
696 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
697 if r.RequestURI == "/" {
698 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
702 jar := new(RecordingJar)
705 Transport: &Transport{
706 Dial: func(_ string, _ string) (net.Conn, error) {
707 return net.Dial("tcp", ts.Listener.Addr().String())
711 _, err := c.Get("http://firsthost.fake/")
715 _, err = c.Get("http://firsthost.fake/nosetcookie")
719 got := jar.log.String()
720 want := `Cookies("http://firsthost.fake/")
721 SetCookie("http://firsthost.fake/", [name=val])
722 Cookies("http://secondhost.fake/secondpath")
723 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
724 Cookies("http://firsthost.fake/nosetcookie")
727 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
731 // RecordingJar keeps a log of calls made to it, without
732 // tracking any cookies.
733 type RecordingJar struct {
738 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
739 j.logf("SetCookie(%q, %v)\n", u, cookies)
742 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
743 j.logf("Cookies(%q)\n", u)
747 func (j *RecordingJar) logf(format string, args ...interface{}) {
750 fmt.Fprintf(&j.log, format, args...)
753 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
754 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
756 func testStreamingGet(t *testing.T, h2 bool) {
758 say := make(chan string)
759 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
761 for str := range say {
769 res, err := c.Get(cst.ts.URL)
774 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
776 n, err := io.ReadFull(res.Body, buf[0:len(str)])
778 t.Fatalf("ReadFull on %q: %v", str, err)
781 t.Fatalf("Receiving %q, only read %d bytes", str, n)
783 got := string(buf[0:n])
785 t.Fatalf("Expected %q, got %q", str, got)
789 _, err = io.ReadFull(res.Body, buf[0:1])
791 t.Fatalf("at end expected EOF, got %v", err)
795 type writeCountingConn struct {
800 func (c *writeCountingConn) Write(p []byte) (int, error) {
802 return c.Conn.Write(p)
805 // TestClientWrites verifies that client requests are buffered and we
806 // don't send a TCP packet per line of the http request + body.
807 func TestClientWrites(t *testing.T) {
809 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
814 dialer := func(netz string, addr string) (net.Conn, error) {
815 c, err := net.Dial(netz, addr)
817 c = &writeCountingConn{c, &writes}
821 c := &Client{Transport: &Transport{Dial: dialer}}
823 _, err := c.Get(ts.URL)
828 t.Errorf("Get request did %d Write calls, want 1", writes)
832 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
837 t.Errorf("Post request did %d Write calls, want 1", writes)
841 func TestClientInsecureTransport(t *testing.T) {
844 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
845 w.Write([]byte("Hello"))
847 errc := make(chanWriter, 10) // but only expecting 1
848 ts.Config.ErrorLog = log.New(errc, "", 0)
851 // TODO(bradfitz): add tests for skipping hostname checks too?
852 // would require a new cert for testing, and probably
853 // redundant with these tests.
854 for _, insecure := range []bool{true, false} {
856 TLSClientConfig: &tls.Config{
857 InsecureSkipVerify: insecure,
860 defer tr.CloseIdleConnections()
861 c := &Client{Transport: tr}
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 newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
896 certs := x509.NewCertPool()
897 for _, c := range ts.TLS.Certificates {
898 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
900 t.Fatalf("error parsing server's root cert: %v", err)
902 for _, root := range roots {
907 TLSClientConfig: &tls.Config{RootCAs: certs},
911 func TestClientWithCorrectTLSServerName(t *testing.T) {
914 const serverName = "example.com"
915 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
916 if r.TLS.ServerName != serverName {
917 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
922 trans := newTLSTransport(t, ts)
923 trans.TLSClientConfig.ServerName = serverName
924 c := &Client{Transport: trans}
925 if _, err := c.Get(ts.URL); err != nil {
926 t.Fatalf("expected successful TLS connection, got error: %v", err)
930 func TestClientWithIncorrectTLSServerName(t *testing.T) {
932 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
934 errc := make(chanWriter, 10) // but only expecting 1
935 ts.Config.ErrorLog = log.New(errc, "", 0)
937 trans := newTLSTransport(t, ts)
938 trans.TLSClientConfig.ServerName = "badserver"
939 c := &Client{Transport: trans}
940 _, err := c.Get(ts.URL)
942 t.Fatalf("expected an error")
944 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
945 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
949 if !strings.Contains(v, "TLS handshake error") {
950 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
952 case <-time.After(5 * time.Second):
953 t.Errorf("timeout waiting for logged error")
957 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
960 // tls.Config.ServerName (non-empty, set to "example.com") takes
961 // precedence over "some-other-host.tld" which previously incorrectly
962 // took precedence. We don't actually connect to (or even resolve)
963 // "some-other-host.tld", though, because of the Transport.Dial hook.
965 // The httptest.Server has a cert with "example.com" as its name.
966 func TestTransportUsesTLSConfigServerName(t *testing.T) {
968 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
969 w.Write([]byte("Hello"))
973 tr := newTLSTransport(t, ts)
974 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
975 tr.Dial = func(netw, addr string) (net.Conn, error) {
976 return net.Dial(netw, ts.Listener.Addr().String())
978 defer tr.CloseIdleConnections()
979 c := &Client{Transport: tr}
980 res, err := c.Get("https://some-other-host.tld/")
987 func TestResponseSetsTLSConnectionState(t *testing.T) {
989 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
990 w.Write([]byte("Hello"))
994 tr := newTLSTransport(t, ts)
995 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
996 tr.Dial = func(netw, addr string) (net.Conn, error) {
997 return net.Dial(netw, ts.Listener.Addr().String())
999 defer tr.CloseIdleConnections()
1000 c := &Client{Transport: tr}
1001 res, err := c.Get("https://example.com/")
1005 defer res.Body.Close()
1007 t.Fatal("Response didn't set TLS Connection State.")
1009 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
1010 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
1014 // Check that an HTTPS client can interpret a particular TLS error
1015 // to determine that the server is speaking HTTP.
1016 // See golang.org/issue/11111.
1017 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1019 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1022 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1023 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1024 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1028 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1029 func TestClientHeadContentLength_h1(t *testing.T) {
1030 testClientHeadContentLength(t, h1Mode)
1033 func TestClientHeadContentLength_h2(t *testing.T) {
1034 testClientHeadContentLength(t, h2Mode)
1037 func testClientHeadContentLength(t *testing.T, h2 bool) {
1039 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1040 if v := r.FormValue("cl"); v != "" {
1041 w.Header().Set("Content-Length", v)
1049 {"/?cl=1234", 1234},
1053 for _, tt := range tests {
1054 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1055 res, err := cst.c.Do(req)
1059 if res.ContentLength != tt.want {
1060 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1062 bs, err := ioutil.ReadAll(res.Body)
1067 t.Errorf("Unexpected content: %q", bs)
1072 func TestEmptyPasswordAuth(t *testing.T) {
1076 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1077 auth := r.Header.Get("Authorization")
1078 if strings.HasPrefix(auth, "Basic ") {
1080 decoded, err := base64.StdEncoding.DecodeString(encoded)
1084 expected := gopher + ":"
1085 s := string(decoded)
1087 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1090 t.Errorf("Invalid auth %q", auth)
1095 defer tr.CloseIdleConnections()
1096 c := &Client{Transport: tr}
1097 req, err := NewRequest("GET", ts.URL, nil)
1101 req.URL.User = url.User(gopher)
1102 resp, err := c.Do(req)
1106 defer resp.Body.Close()
1109 func TestBasicAuth(t *testing.T) {
1111 tr := &recordingTransport{}
1112 client := &Client{Transport: tr}
1114 url := "http://My%20User:My%20Pass@dummy.faketld/"
1115 expected := "My User:My Pass"
1118 if tr.req.Method != "GET" {
1119 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1121 if tr.req.URL.String() != url {
1122 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1124 if tr.req.Header == nil {
1125 t.Fatalf("expected non-nil request Header")
1127 auth := tr.req.Header.Get("Authorization")
1128 if strings.HasPrefix(auth, "Basic ") {
1130 decoded, err := base64.StdEncoding.DecodeString(encoded)
1134 s := string(decoded)
1136 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1139 t.Errorf("Invalid auth %q", auth)
1143 func TestBasicAuthHeadersPreserved(t *testing.T) {
1145 tr := &recordingTransport{}
1146 client := &Client{Transport: tr}
1148 // If Authorization header is provided, username in URL should not override it
1149 url := "http://My%20User@dummy.faketld/"
1150 req, err := NewRequest("GET", url, nil)
1154 req.SetBasicAuth("My User", "My Pass")
1155 expected := "My User:My Pass"
1158 if tr.req.Method != "GET" {
1159 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1161 if tr.req.URL.String() != url {
1162 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1164 if tr.req.Header == nil {
1165 t.Fatalf("expected non-nil request Header")
1167 auth := tr.req.Header.Get("Authorization")
1168 if strings.HasPrefix(auth, "Basic ") {
1170 decoded, err := base64.StdEncoding.DecodeString(encoded)
1174 s := string(decoded)
1176 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1179 t.Errorf("Invalid auth %q", auth)
1184 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1185 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1187 func testClientTimeout(t *testing.T, h2 bool) {
1190 testDone := make(chan struct{})
1192 const timeout = 100 * time.Millisecond
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"))
1208 case <-time.After(timeout * 10):
1214 defer close(testDone)
1215 cst.c.Timeout = timeout
1217 res, err := cst.c.Get(cst.ts.URL)
1219 if strings.Contains(err.Error(), "Client.Timeout") {
1220 t.Skip("host too slow to get fast resource in 100ms")
1229 t.Fatal("handler never got / request")
1236 t.Fatal("handler never got /slow request")
1239 errc := make(chan error, 1)
1241 _, err := ioutil.ReadAll(res.Body)
1246 const failTime = timeout * 2
1250 t.Fatal("expected error from ReadAll")
1252 ne, ok := err.(net.Error)
1254 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1255 } else if !ne.Timeout() {
1256 t.Errorf("net.Error.Timeout = false; want true")
1258 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1259 t.Errorf("error string = %q; missing timeout substring", got)
1261 case <-time.After(failTime):
1262 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1266 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1267 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1269 // Client.Timeout firing before getting to the body
1270 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1273 donec := make(chan bool, 1)
1274 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1278 // Note that we use a channel send here and not a close.
1279 // The race detector doesn't know that we're waiting for a timeout
1280 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1281 // with us closing it. If we timed out immediately, we could close the testserver
1282 // before we entered the handler. We're not timing out immediately and there's
1283 // no way we would be done before we entered the handler, but the race detector
1284 // doesn't know this, so synchronize explicitly.
1285 defer func() { donec <- true }()
1287 cst.c.Timeout = 5 * time.Millisecond
1288 res, err := cst.c.Get(cst.ts.URL)
1291 t.Fatal("got response from Get; expected error")
1293 if _, ok := err.(*url.Error); !ok {
1294 t.Fatalf("Got error of type %T; want *url.Error", err)
1296 ne, ok := err.(net.Error)
1298 t.Fatalf("Got error of type %T; want some net.Error", err)
1301 t.Error("net.Error.Timeout = false; want true")
1303 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1304 t.Errorf("error string = %q; missing timeout substring", got)
1308 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1310 func TestClientTimeoutCancel(t *testing.T) {
1314 testDone := make(chan struct{})
1315 ctx, cancel := context.WithCancel(context.Background())
1317 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1322 defer close(testDone)
1324 cst.c.Timeout = 1 * time.Hour
1325 req, _ := NewRequest("GET", cst.ts.URL, nil)
1326 req.Cancel = ctx.Done()
1327 res, err := cst.c.Do(req)
1332 _, err = io.Copy(ioutil.Discard, res.Body)
1333 if err != ExportErrRequestCanceled {
1334 t.Fatal("error = %v; want errRequestCanceled")
1338 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1339 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1340 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1343 saw := make(chan string, 2)
1344 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1346 if r.URL.Path == "/" {
1347 Redirect(w, r, "/foo", StatusFound) // which includes a body
1352 res, err := cst.c.Get(cst.ts.URL)
1356 _, err = ioutil.ReadAll(res.Body)
1366 t.Fatal("server didn't see a request")
1371 case second = <-saw:
1373 t.Fatal("server didn't see a second request")
1376 if first != second {
1377 t.Fatal("server saw different client ports before & after the redirect")
1381 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1382 type eofReaderFunc func()
1384 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1389 func TestReferer(t *testing.T) {
1391 lastReq, newReq string // from -> to URLs
1395 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1396 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1398 // don't send a user and password:
1399 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1400 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1403 {"http://test.com", "http://link.com", "http://test.com"},
1404 {"https://test.com", "https://link.com", "https://test.com"},
1406 // https to http doesn't send a referer:
1407 {"https://test.com", "http://link.com", ""},
1408 {"https://gopher:go@test.com", "http://link.com", ""},
1410 for _, tt := range tests {
1411 l, err := url.Parse(tt.lastReq)
1415 n, err := url.Parse(tt.newReq)
1419 r := ExportRefererForURL(l, n)
1421 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1426 // issue15577Tripper returns a Response with a redirect response
1427 // header and doesn't populate its Response.Request field.
1428 type issue15577Tripper struct{}
1430 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1433 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1434 Body: ioutil.NopCloser(strings.NewReader("")),
1439 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1440 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1442 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1443 Transport: issue15577Tripper{},
1445 // Check that this doesn't crash:
1446 c.Get("http://dummy.tld")
1449 // Issue 4800: copy (some) headers when Client follows a redirect
1450 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1452 ua = "some-agent/1.2"
1456 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1458 "User-Agent": []string{ua},
1459 "X-Foo": []string{xfoo},
1460 "Referer": []string{ts2URL},
1461 "Accept-Encoding": []string{"gzip"},
1463 if !reflect.DeepEqual(r.Header, want) {
1464 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1467 w.Header().Set("Result", "got errors")
1469 w.Header().Set("Result", "ok")
1473 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1474 Redirect(w, r, ts1.URL, StatusFound)
1480 defer tr.CloseIdleConnections()
1483 CheckRedirect: func(r *Request, via []*Request) error {
1485 "User-Agent": []string{ua},
1486 "X-Foo": []string{xfoo},
1487 "Referer": []string{ts2URL},
1489 if !reflect.DeepEqual(r.Header, want) {
1490 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1496 req, _ := NewRequest("GET", ts2.URL, nil)
1497 req.Header.Add("User-Agent", ua)
1498 req.Header.Add("X-Foo", xfoo)
1499 req.Header.Add("Cookie", "foo=bar")
1500 req.Header.Add("Authorization", "secretpassword")
1501 res, err := c.Do(req)
1505 defer res.Body.Close()
1506 if res.StatusCode != 200 {
1509 if got := res.Header.Get("Result"); got != "ok" {
1510 t.Errorf("result = %q; want ok", got)
1514 // Issue 17494: cookies should be altered when Client follows redirects.
1515 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1516 cookieMap := func(cs []*Cookie) map[string][]string {
1517 m := make(map[string][]string)
1518 for _, c := range cs {
1519 m[c.Name] = append(m[c.Name], c.Value)
1524 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1525 var want map[string][]string
1526 got := cookieMap(r.Cookies())
1528 c, _ := r.Cookie("Cycle")
1531 want = map[string][]string{
1532 "Cookie1": {"OldValue1a", "OldValue1b"},
1533 "Cookie2": {"OldValue2"},
1534 "Cookie3": {"OldValue3a", "OldValue3b"},
1535 "Cookie4": {"OldValue4"},
1538 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1539 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1540 Redirect(w, r, "/", StatusFound)
1542 want = map[string][]string{
1543 "Cookie1": {"OldValue1a", "OldValue1b"},
1544 "Cookie3": {"OldValue3a", "OldValue3b"},
1545 "Cookie4": {"OldValue4"},
1548 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1549 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1550 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1551 Redirect(w, r, "/", StatusFound)
1553 want = map[string][]string{
1554 "Cookie1": {"OldValue1a", "OldValue1b"},
1555 "Cookie3": {"NewValue3"},
1556 "Cookie4": {"NewValue4"},
1559 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1560 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1561 Redirect(w, r, "/", StatusFound)
1563 want = map[string][]string{
1564 "Cookie1": {"OldValue1a", "OldValue1b"},
1565 "Cookie3": {"NewValue3"},
1566 "Cookie4": {"NewValue4"},
1567 "Cookie5": {"NewValue5"},
1570 // Don't redirect to ensure the loop ends.
1572 t.Errorf("unexpected redirect cycle")
1576 if !reflect.DeepEqual(got, want) {
1577 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1583 defer tr.CloseIdleConnections()
1584 jar, _ := cookiejar.New(nil)
1590 u, _ := url.Parse(ts.URL)
1591 req, _ := NewRequest("GET", ts.URL, nil)
1592 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1593 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1594 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1595 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1596 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1597 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1598 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1599 res, err := c.Do(req)
1603 defer res.Body.Close()
1604 if res.StatusCode != 200 {
1609 // Part of Issue 4800
1610 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1617 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1618 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1620 // Sensitive headers:
1621 {"cookie", "http://foo.com/", "http://bar.com/", false},
1622 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1623 {"authorization", "http://foo.com/", "http://bar.com/", false},
1624 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1626 // But subdomains should work:
1627 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1628 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1629 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1630 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1631 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1633 for i, tt := range tests {
1634 u0, err := url.Parse(tt.initialURL)
1636 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1639 u1, err := url.Parse(tt.destURL)
1641 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1644 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1646 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1647 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1652 func TestClientRedirectTypes(t *testing.T) {
1656 tests := [...]struct {
1659 wantMethod string // desired subsequent client method
1661 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1662 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1663 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1664 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1665 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1667 5: {method: "HEAD", serverStatus: 301, wantMethod: "GET"},
1668 6: {method: "HEAD", serverStatus: 302, wantMethod: "GET"},
1669 7: {method: "HEAD", serverStatus: 303, wantMethod: "GET"},
1670 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1671 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1673 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1674 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1675 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1676 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1677 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1679 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1680 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1681 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1682 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1683 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1685 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1686 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1687 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1688 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1689 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1691 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1692 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1693 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1694 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1695 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1698 handlerc := make(chan HandlerFunc, 1)
1700 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1707 defer tr.CloseIdleConnections()
1709 for i, tt := range tests {
1710 handlerc <- func(w ResponseWriter, r *Request) {
1711 w.Header().Set("Location", ts.URL)
1712 w.WriteHeader(tt.serverStatus)
1715 req, err := NewRequest(tt.method, ts.URL, nil)
1717 t.Errorf("#%d: NewRequest: %v", i, err)
1721 c := &Client{Transport: tr}
1722 c.CheckRedirect = func(req *Request, via []*Request) error {
1723 if got, want := req.Method, tt.wantMethod; got != want {
1724 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1726 handlerc <- func(rw ResponseWriter, req *Request) {
1727 // TODO: Check that the body is valid when we do 307 and 308 support
1732 res, err := c.Do(req)
1734 t.Errorf("#%d: Response: %v", i, err)