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) {
71 ts := httptest.NewServer(robotsTxtHandler)
77 b, err = pedanticReadAll(r.Body)
82 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
83 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
87 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
88 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
90 func testClientHead(t *testing.T, h2 bool) {
92 cst := newClientServerTest(t, h2, robotsTxtHandler)
95 r, err := cst.c.Head(cst.ts.URL)
99 if _, ok := r.Header["Last-Modified"]; !ok {
100 t.Error("Last-Modified header not found.")
104 type recordingTransport struct {
108 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
110 return nil, errors.New("dummy impl")
113 func TestGetRequestFormat(t *testing.T) {
115 tr := &recordingTransport{}
116 client := &Client{Transport: tr}
117 url := "http://dummy.faketld/"
118 client.Get(url) // Note: doesn't hit network
119 if tr.req.Method != "GET" {
120 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
122 if tr.req.URL.String() != url {
123 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
125 if tr.req.Header == nil {
126 t.Errorf("expected non-nil request Header")
130 func TestPostRequestFormat(t *testing.T) {
132 tr := &recordingTransport{}
133 client := &Client{Transport: tr}
135 url := "http://dummy.faketld/"
136 json := `{"key":"value"}`
137 b := strings.NewReader(json)
138 client.Post(url, "application/json", b) // Note: doesn't hit network
140 if tr.req.Method != "POST" {
141 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
143 if tr.req.URL.String() != url {
144 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
146 if tr.req.Header == nil {
147 t.Fatalf("expected non-nil request Header")
150 t.Error("got Close true, want false")
152 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
153 t.Errorf("got ContentLength %d, want %d", g, e)
157 func TestPostFormRequestFormat(t *testing.T) {
159 tr := &recordingTransport{}
160 client := &Client{Transport: tr}
162 urlStr := "http://dummy.faketld/"
163 form := make(url.Values)
164 form.Set("foo", "bar")
165 form.Add("foo", "bar2")
166 form.Set("bar", "baz")
167 client.PostForm(urlStr, form) // Note: doesn't hit network
169 if tr.req.Method != "POST" {
170 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
172 if tr.req.URL.String() != urlStr {
173 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
175 if tr.req.Header == nil {
176 t.Fatalf("expected non-nil request Header")
178 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
179 t.Errorf("got Content-Type %q, want %q", g, e)
182 t.Error("got Close true, want false")
184 // Depending on map iteration, body can be either of these.
185 expectedBody := "foo=bar&foo=bar2&bar=baz"
186 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
187 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
188 t.Errorf("got ContentLength %d, want %d", g, e)
190 bodyb, err := ioutil.ReadAll(tr.req.Body)
192 t.Fatalf("ReadAll on req.Body: %v", err)
194 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
195 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
199 func TestClientRedirects(t *testing.T) {
202 var ts *httptest.Server
203 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
204 n, _ := strconv.Atoi(r.FormValue("n"))
205 // Test Referer header. (7 is arbitrary position to test at)
207 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
208 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
212 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
215 fmt.Fprintf(w, "n=%d", n)
220 _, err := c.Get(ts.URL)
221 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
222 t.Errorf("with default client Get, expected error %q, got %q", e, g)
225 // HEAD request should also have the ability to follow redirects.
226 _, err = c.Head(ts.URL)
227 if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
228 t.Errorf("with default client Head, expected error %q, got %q", e, g)
231 // Do should also follow redirects.
232 greq, _ := NewRequest("GET", ts.URL, nil)
234 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
235 t.Errorf("with default client Do, expected error %q, got %q", e, g)
238 // Requests with an empty Method should also redirect (Issue 12705)
241 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
242 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
246 var lastVia []*Request
248 c = &Client{CheckRedirect: func(req *Request, via []*Request) error {
253 res, err := c.Get(ts.URL)
255 t.Fatalf("Get error: %v", err)
258 finalUrl := res.Request.URL.String()
259 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
260 t.Errorf("with custom client, expected error %q, got %q", e, g)
262 if !strings.HasSuffix(finalUrl, "/?n=15") {
263 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
265 if e, g := 15, len(lastVia); e != g {
266 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
269 // Test that Request.Cancel is propagated between requests (Issue 14053)
270 creq, _ := NewRequest("HEAD", ts.URL, nil)
271 cancel := make(chan struct{})
273 if _, err := c.Do(creq); err != nil {
277 t.Fatal("didn't see redirect")
279 if lastReq.Cancel != cancel {
280 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
283 checkErr = errors.New("no redirects allowed")
284 res, err = c.Get(ts.URL)
285 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
286 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
289 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
292 if res.Header.Get("Location") == "" {
293 t.Errorf("no Location header in Response")
297 func TestClientRedirectContext(t *testing.T) {
300 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
301 Redirect(w, r, "/", StatusTemporaryRedirect)
305 ctx, cancel := context.WithCancel(context.Background())
306 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
309 return errors.New("too many redirects")
313 req, _ := NewRequest("GET", ts.URL, nil)
314 req = req.WithContext(ctx)
316 ue, ok := err.(*url.Error)
318 t.Fatalf("got error %T; want *url.Error", err)
320 if ue.Err != context.Canceled {
321 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
325 type redirectTest struct {
327 want int // response code
331 func TestPostRedirects(t *testing.T) {
332 postRedirectTests := []redirectTest{
334 {"/?code=301&next=302", 200, "c301"},
335 {"/?code=302&next=302", 200, "c302"},
336 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
337 {"/?code=304", 304, "c304"},
338 {"/?code=305", 305, "c305"},
339 {"/?code=307&next=303,308,302", 200, "c307"},
340 {"/?code=308&next=302,301", 200, "c308"},
341 {"/?code=404", 404, "c404"},
344 wantSegments := []string{
346 `POST /?code=301&next=302 "c301"`,
347 `GET /?code=302 "c301"`,
349 `POST /?code=302&next=302 "c302"`,
350 `GET /?code=302 "c302"`,
352 `POST /?code=303&next=301 "c303wc301"`,
353 `GET /?code=301 "c303wc301"`,
355 `POST /?code=304 "c304"`,
356 `POST /?code=305 "c305"`,
357 `POST /?code=307&next=303,308,302 "c307"`,
358 `POST /?code=303&next=308,302 "c307"`,
359 `GET /?code=308&next=302 "c307"`,
360 `GET /?code=302 "c307"`,
362 `POST /?code=308&next=302,301 "c308"`,
363 `POST /?code=302&next=301 "c308"`,
364 `GET /?code=301 "c308"`,
366 `POST /?code=404 "c404"`,
368 want := strings.Join(wantSegments, "\n")
369 testRedirectsByMethod(t, "POST", postRedirectTests, want)
372 func TestDeleteRedirects(t *testing.T) {
373 deleteRedirectTests := []redirectTest{
375 {"/?code=301&next=302,308", 200, "c301"},
376 {"/?code=302&next=302", 200, "c302"},
377 {"/?code=303", 200, "c303"},
378 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
379 {"/?code=308&next=307", 200, "c308"},
380 {"/?code=404", 404, "c404"},
383 wantSegments := []string{
385 `DELETE /?code=301&next=302,308 "c301"`,
386 `GET /?code=302&next=308 "c301"`,
387 `GET /?code=308 "c301"`,
389 `DELETE /?code=302&next=302 "c302"`,
390 `GET /?code=302 "c302"`,
392 `DELETE /?code=303 "c303"`,
394 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
395 `DELETE /?code=301&next=308,303,302,304 "c307"`,
396 `GET /?code=308&next=303,302,304 "c307"`,
397 `GET /?code=303&next=302,304 "c307"`,
398 `GET /?code=302&next=304 "c307"`,
399 `GET /?code=304 "c307"`,
400 `DELETE /?code=308&next=307 "c308"`,
401 `DELETE /?code=307 "c308"`,
403 `DELETE /?code=404 "c404"`,
405 want := strings.Join(wantSegments, "\n")
406 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
409 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
415 var ts *httptest.Server
416 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
418 slurp, _ := ioutil.ReadAll(r.Body)
419 fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp)
421 urlQuery := r.URL.Query()
422 if v := urlQuery.Get("code"); v != "" {
424 if final := urlQuery.Get("next"); final != "" {
425 splits := strings.Split(final, ",")
426 first, rest := splits[0], splits[1:]
427 location = fmt.Sprintf("%s?code=%s", location, first)
429 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
432 code, _ := strconv.Atoi(v)
434 w.Header().Set("Location", location)
441 for _, tt := range table {
442 content := tt.redirectBody
443 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
444 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
445 res, err := DefaultClient.Do(req)
450 if res.StatusCode != tt.want {
451 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
458 got = strings.TrimSpace(got)
459 want = strings.TrimSpace(want)
462 t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want)
466 func TestClientRedirectUseResponse(t *testing.T) {
469 const body = "Hello, world."
470 var ts *httptest.Server
471 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
472 if strings.Contains(r.URL.Path, "/other") {
473 io.WriteString(w, "wrong body")
475 w.Header().Set("Location", ts.URL+"/other")
476 w.WriteHeader(StatusFound)
477 io.WriteString(w, body)
482 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
483 if req.Response == nil {
484 t.Error("expected non-nil Request.Response")
486 return ErrUseLastResponse
488 res, err := c.Get(ts.URL)
492 if res.StatusCode != StatusFound {
493 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
495 defer res.Body.Close()
496 slurp, err := ioutil.ReadAll(res.Body)
500 if string(slurp) != body {
501 t.Errorf("body = %q; want %q", slurp, body)
505 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
506 // have a Location header.
507 func TestClientRedirect308NoLocation(t *testing.T) {
510 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
511 w.Header().Set("Foo", "Bar")
515 res, err := Get(ts.URL)
520 if res.StatusCode != 308 {
521 t.Errorf("status = %d; want %d", res.StatusCode, 308)
523 if got := res.Header.Get("Foo"); got != "Bar" {
524 t.Errorf("Foo header = %q; want Bar", got)
528 // Don't follow a 307/308 if we can't resent the request body.
529 func TestClientRedirect308NoGetBody(t *testing.T) {
532 const fakeURL = "https://localhost:1234/" // won't be hit
533 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
534 w.Header().Set("Location", fakeURL)
538 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
542 req.GetBody = nil // so it can't rewind.
543 res, err := DefaultClient.Do(req)
548 if res.StatusCode != 308 {
549 t.Errorf("status = %d; want %d", res.StatusCode, 308)
551 if got := res.Header.Get("Location"); got != fakeURL {
552 t.Errorf("Location header = %q; want %q", got, fakeURL)
556 var expectedCookies = []*Cookie{
557 {Name: "ChocolateChip", Value: "tasty"},
558 {Name: "First", Value: "Hit"},
559 {Name: "Second", Value: "Hit"},
562 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
563 for _, cookie := range r.Cookies() {
566 if r.URL.Path == "/" {
567 SetCookie(w, expectedCookies[1])
568 Redirect(w, r, "/second", StatusMovedPermanently)
570 SetCookie(w, expectedCookies[2])
571 w.Write([]byte("hello"))
575 func TestClientSendsCookieFromJar(t *testing.T) {
577 tr := &recordingTransport{}
578 client := &Client{Transport: tr}
579 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
580 us := "http://dummy.faketld/"
581 u, _ := url.Parse(us)
582 client.Jar.SetCookies(u, expectedCookies)
584 client.Get(us) // Note: doesn't hit network
585 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
587 client.Head(us) // Note: doesn't hit network
588 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
590 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
591 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
593 client.PostForm(us, url.Values{}) // Note: doesn't hit network
594 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
596 req, _ := NewRequest("GET", us, nil)
597 client.Do(req) // Note: doesn't hit network
598 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
600 req, _ = NewRequest("POST", us, nil)
601 client.Do(req) // Note: doesn't hit network
602 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
605 // Just enough correctness for our redirect tests. Uses the URL.Host as the
606 // scope of all cookies.
607 type TestJar struct {
609 perURL map[string][]*Cookie
612 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
616 j.perURL = make(map[string][]*Cookie)
618 j.perURL[u.Host] = cookies
621 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
624 return j.perURL[u.Host]
627 func TestRedirectCookiesJar(t *testing.T) {
629 var ts *httptest.Server
630 ts = httptest.NewServer(echoCookiesRedirectHandler)
635 u, _ := url.Parse(ts.URL)
636 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
637 resp, err := c.Get(ts.URL)
639 t.Fatalf("Get: %v", err)
642 matchReturnedCookies(t, expectedCookies, resp.Cookies())
645 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
646 if len(given) != len(expected) {
647 t.Logf("Received cookies: %v", given)
648 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
650 for _, ec := range expected {
652 for _, c := range given {
653 if ec.Name == c.Name && ec.Value == c.Value {
659 t.Errorf("Missing cookie %v", ec)
664 func TestJarCalls(t *testing.T) {
666 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
667 pathSuffix := r.RequestURI[1:]
668 if r.RequestURI == "/nosetcookie" {
669 return // don't set cookies for this path
671 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
672 if r.RequestURI == "/" {
673 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
677 jar := new(RecordingJar)
680 Transport: &Transport{
681 Dial: func(_ string, _ string) (net.Conn, error) {
682 return net.Dial("tcp", ts.Listener.Addr().String())
686 _, err := c.Get("http://firsthost.fake/")
690 _, err = c.Get("http://firsthost.fake/nosetcookie")
694 got := jar.log.String()
695 want := `Cookies("http://firsthost.fake/")
696 SetCookie("http://firsthost.fake/", [name=val])
697 Cookies("http://secondhost.fake/secondpath")
698 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
699 Cookies("http://firsthost.fake/nosetcookie")
702 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
706 // RecordingJar keeps a log of calls made to it, without
707 // tracking any cookies.
708 type RecordingJar struct {
713 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
714 j.logf("SetCookie(%q, %v)\n", u, cookies)
717 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
718 j.logf("Cookies(%q)\n", u)
722 func (j *RecordingJar) logf(format string, args ...interface{}) {
725 fmt.Fprintf(&j.log, format, args...)
728 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
729 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
731 func testStreamingGet(t *testing.T, h2 bool) {
733 say := make(chan string)
734 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
736 for str := range say {
744 res, err := c.Get(cst.ts.URL)
749 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
751 n, err := io.ReadFull(res.Body, buf[0:len(str)])
753 t.Fatalf("ReadFull on %q: %v", str, err)
756 t.Fatalf("Receiving %q, only read %d bytes", str, n)
758 got := string(buf[0:n])
760 t.Fatalf("Expected %q, got %q", str, got)
764 _, err = io.ReadFull(res.Body, buf[0:1])
766 t.Fatalf("at end expected EOF, got %v", err)
770 type writeCountingConn struct {
775 func (c *writeCountingConn) Write(p []byte) (int, error) {
777 return c.Conn.Write(p)
780 // TestClientWrites verifies that client requests are buffered and we
781 // don't send a TCP packet per line of the http request + body.
782 func TestClientWrites(t *testing.T) {
784 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
789 dialer := func(netz string, addr string) (net.Conn, error) {
790 c, err := net.Dial(netz, addr)
792 c = &writeCountingConn{c, &writes}
796 c := &Client{Transport: &Transport{Dial: dialer}}
798 _, err := c.Get(ts.URL)
803 t.Errorf("Get request did %d Write calls, want 1", writes)
807 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
812 t.Errorf("Post request did %d Write calls, want 1", writes)
816 func TestClientInsecureTransport(t *testing.T) {
819 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
820 w.Write([]byte("Hello"))
822 errc := make(chanWriter, 10) // but only expecting 1
823 ts.Config.ErrorLog = log.New(errc, "", 0)
826 // TODO(bradfitz): add tests for skipping hostname checks too?
827 // would require a new cert for testing, and probably
828 // redundant with these tests.
829 for _, insecure := range []bool{true, false} {
831 TLSClientConfig: &tls.Config{
832 InsecureSkipVerify: insecure,
835 defer tr.CloseIdleConnections()
836 c := &Client{Transport: tr}
837 res, err := c.Get(ts.URL)
838 if (err == nil) != insecure {
839 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
848 if !strings.Contains(v, "TLS handshake error") {
849 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
851 case <-time.After(5 * time.Second):
852 t.Errorf("timeout waiting for logged error")
857 func TestClientErrorWithRequestURI(t *testing.T) {
859 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
860 req.RequestURI = "/this/field/is/illegal/and/should/error/"
861 _, err := DefaultClient.Do(req)
863 t.Fatalf("expected an error")
865 if !strings.Contains(err.Error(), "RequestURI") {
866 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
870 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
871 certs := x509.NewCertPool()
872 for _, c := range ts.TLS.Certificates {
873 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
875 t.Fatalf("error parsing server's root cert: %v", err)
877 for _, root := range roots {
882 TLSClientConfig: &tls.Config{RootCAs: certs},
886 func TestClientWithCorrectTLSServerName(t *testing.T) {
889 const serverName = "example.com"
890 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
891 if r.TLS.ServerName != serverName {
892 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
897 trans := newTLSTransport(t, ts)
898 trans.TLSClientConfig.ServerName = serverName
899 c := &Client{Transport: trans}
900 if _, err := c.Get(ts.URL); err != nil {
901 t.Fatalf("expected successful TLS connection, got error: %v", err)
905 func TestClientWithIncorrectTLSServerName(t *testing.T) {
907 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
909 errc := make(chanWriter, 10) // but only expecting 1
910 ts.Config.ErrorLog = log.New(errc, "", 0)
912 trans := newTLSTransport(t, ts)
913 trans.TLSClientConfig.ServerName = "badserver"
914 c := &Client{Transport: trans}
915 _, err := c.Get(ts.URL)
917 t.Fatalf("expected an error")
919 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
920 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
924 if !strings.Contains(v, "TLS handshake error") {
925 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
927 case <-time.After(5 * time.Second):
928 t.Errorf("timeout waiting for logged error")
932 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
935 // tls.Config.ServerName (non-empty, set to "example.com") takes
936 // precedence over "some-other-host.tld" which previously incorrectly
937 // took precedence. We don't actually connect to (or even resolve)
938 // "some-other-host.tld", though, because of the Transport.Dial hook.
940 // The httptest.Server has a cert with "example.com" as its name.
941 func TestTransportUsesTLSConfigServerName(t *testing.T) {
943 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
944 w.Write([]byte("Hello"))
948 tr := newTLSTransport(t, ts)
949 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
950 tr.Dial = func(netw, addr string) (net.Conn, error) {
951 return net.Dial(netw, ts.Listener.Addr().String())
953 defer tr.CloseIdleConnections()
954 c := &Client{Transport: tr}
955 res, err := c.Get("https://some-other-host.tld/")
962 func TestResponseSetsTLSConnectionState(t *testing.T) {
964 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
965 w.Write([]byte("Hello"))
969 tr := newTLSTransport(t, ts)
970 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
971 tr.Dial = func(netw, addr string) (net.Conn, error) {
972 return net.Dial(netw, ts.Listener.Addr().String())
974 defer tr.CloseIdleConnections()
975 c := &Client{Transport: tr}
976 res, err := c.Get("https://example.com/")
980 defer res.Body.Close()
982 t.Fatal("Response didn't set TLS Connection State.")
984 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
985 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
989 // Check that an HTTPS client can interpret a particular TLS error
990 // to determine that the server is speaking HTTP.
991 // See golang.org/issue/11111.
992 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
994 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
997 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
998 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
999 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1003 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1004 func TestClientHeadContentLength_h1(t *testing.T) {
1005 testClientHeadContentLength(t, h1Mode)
1008 func TestClientHeadContentLength_h2(t *testing.T) {
1009 testClientHeadContentLength(t, h2Mode)
1012 func testClientHeadContentLength(t *testing.T, h2 bool) {
1014 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1015 if v := r.FormValue("cl"); v != "" {
1016 w.Header().Set("Content-Length", v)
1024 {"/?cl=1234", 1234},
1028 for _, tt := range tests {
1029 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1030 res, err := cst.c.Do(req)
1034 if res.ContentLength != tt.want {
1035 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1037 bs, err := ioutil.ReadAll(res.Body)
1042 t.Errorf("Unexpected content: %q", bs)
1047 func TestEmptyPasswordAuth(t *testing.T) {
1050 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1051 auth := r.Header.Get("Authorization")
1052 if strings.HasPrefix(auth, "Basic ") {
1054 decoded, err := base64.StdEncoding.DecodeString(encoded)
1058 expected := gopher + ":"
1059 s := string(decoded)
1061 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1064 t.Errorf("Invalid auth %q", auth)
1069 req, err := NewRequest("GET", ts.URL, nil)
1073 req.URL.User = url.User(gopher)
1074 resp, err := c.Do(req)
1078 defer resp.Body.Close()
1081 func TestBasicAuth(t *testing.T) {
1083 tr := &recordingTransport{}
1084 client := &Client{Transport: tr}
1086 url := "http://My%20User:My%20Pass@dummy.faketld/"
1087 expected := "My User:My Pass"
1090 if tr.req.Method != "GET" {
1091 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1093 if tr.req.URL.String() != url {
1094 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1096 if tr.req.Header == nil {
1097 t.Fatalf("expected non-nil request Header")
1099 auth := tr.req.Header.Get("Authorization")
1100 if strings.HasPrefix(auth, "Basic ") {
1102 decoded, err := base64.StdEncoding.DecodeString(encoded)
1106 s := string(decoded)
1108 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1111 t.Errorf("Invalid auth %q", auth)
1115 func TestBasicAuthHeadersPreserved(t *testing.T) {
1117 tr := &recordingTransport{}
1118 client := &Client{Transport: tr}
1120 // If Authorization header is provided, username in URL should not override it
1121 url := "http://My%20User@dummy.faketld/"
1122 req, err := NewRequest("GET", url, nil)
1126 req.SetBasicAuth("My User", "My Pass")
1127 expected := "My User:My Pass"
1130 if tr.req.Method != "GET" {
1131 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1133 if tr.req.URL.String() != url {
1134 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1136 if tr.req.Header == nil {
1137 t.Fatalf("expected non-nil request Header")
1139 auth := tr.req.Header.Get("Authorization")
1140 if strings.HasPrefix(auth, "Basic ") {
1142 decoded, err := base64.StdEncoding.DecodeString(encoded)
1146 s := string(decoded)
1148 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1151 t.Errorf("Invalid auth %q", auth)
1156 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1157 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1159 func testClientTimeout(t *testing.T, h2 bool) {
1160 if testing.Short() {
1161 t.Skip("skipping in short mode")
1164 sawRoot := make(chan bool, 1)
1165 sawSlow := make(chan bool, 1)
1166 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1167 if r.URL.Path == "/" {
1169 Redirect(w, r, "/slow", StatusFound)
1172 if r.URL.Path == "/slow" {
1173 w.Write([]byte("Hello"))
1176 time.Sleep(2 * time.Second)
1181 const timeout = 500 * time.Millisecond
1182 cst.c.Timeout = timeout
1184 res, err := cst.c.Get(cst.ts.URL)
1193 t.Fatal("handler never got / request")
1200 t.Fatal("handler never got /slow request")
1203 errc := make(chan error, 1)
1205 _, err := ioutil.ReadAll(res.Body)
1210 const failTime = timeout * 2
1214 t.Fatal("expected error from ReadAll")
1216 ne, ok := err.(net.Error)
1218 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1219 } else if !ne.Timeout() {
1220 t.Errorf("net.Error.Timeout = false; want true")
1222 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1223 t.Errorf("error string = %q; missing timeout substring", got)
1225 case <-time.After(failTime):
1226 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1230 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1231 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1233 // Client.Timeout firing before getting to the body
1234 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1235 if testing.Short() {
1236 t.Skip("skipping in short mode")
1239 donec := make(chan bool)
1240 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1244 // Note that we use a channel send here and not a close.
1245 // The race detector doesn't know that we're waiting for a timeout
1246 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1247 // with us closing it. If we timed out immediately, we could close the testserver
1248 // before we entered the handler. We're not timing out immediately and there's
1249 // no way we would be done before we entered the handler, but the race detector
1250 // doesn't know this, so synchronize explicitly.
1251 defer func() { donec <- true }()
1253 cst.c.Timeout = 500 * time.Millisecond
1254 _, err := cst.c.Get(cst.ts.URL)
1256 t.Fatal("got response from Get; expected error")
1258 if _, ok := err.(*url.Error); !ok {
1259 t.Fatalf("Got error of type %T; want *url.Error", err)
1261 ne, ok := err.(net.Error)
1263 t.Fatalf("Got error of type %T; want some net.Error", err)
1266 t.Error("net.Error.Timeout = false; want true")
1268 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1269 t.Errorf("error string = %q; missing timeout substring", got)
1273 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1274 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1275 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1278 saw := make(chan string, 2)
1279 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1281 if r.URL.Path == "/" {
1282 Redirect(w, r, "/foo", StatusFound) // which includes a body
1287 res, err := cst.c.Get(cst.ts.URL)
1291 _, err = ioutil.ReadAll(res.Body)
1301 t.Fatal("server didn't see a request")
1306 case second = <-saw:
1308 t.Fatal("server didn't see a second request")
1311 if first != second {
1312 t.Fatal("server saw different client ports before & after the redirect")
1316 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1317 type eofReaderFunc func()
1319 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1324 func TestReferer(t *testing.T) {
1326 lastReq, newReq string // from -> to URLs
1330 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1331 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1333 // don't send a user and password:
1334 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1335 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1338 {"http://test.com", "http://link.com", "http://test.com"},
1339 {"https://test.com", "https://link.com", "https://test.com"},
1341 // https to http doesn't send a referer:
1342 {"https://test.com", "http://link.com", ""},
1343 {"https://gopher:go@test.com", "http://link.com", ""},
1345 for _, tt := range tests {
1346 l, err := url.Parse(tt.lastReq)
1350 n, err := url.Parse(tt.newReq)
1354 r := ExportRefererForURL(l, n)
1356 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1361 // issue15577Tripper returns a Response with a redirect response
1362 // header and doesn't populate its Response.Request field.
1363 type issue15577Tripper struct{}
1365 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1368 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1369 Body: ioutil.NopCloser(strings.NewReader("")),
1374 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1375 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1377 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1378 Transport: issue15577Tripper{},
1380 // Check that this doesn't crash:
1381 c.Get("http://dummy.tld")
1384 // Issue 4800: copy (some) headers when Client follows a redirect
1385 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1387 ua = "some-agent/1.2"
1391 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1393 "User-Agent": []string{ua},
1394 "X-Foo": []string{xfoo},
1395 "Referer": []string{ts2URL},
1396 "Accept-Encoding": []string{"gzip"},
1398 if !reflect.DeepEqual(r.Header, want) {
1399 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1402 w.Header().Set("Result", "got errors")
1404 w.Header().Set("Result", "ok")
1408 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1409 Redirect(w, r, ts1.URL, StatusFound)
1415 defer tr.CloseIdleConnections()
1418 CheckRedirect: func(r *Request, via []*Request) error {
1420 "User-Agent": []string{ua},
1421 "X-Foo": []string{xfoo},
1422 "Referer": []string{ts2URL},
1424 if !reflect.DeepEqual(r.Header, want) {
1425 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1431 req, _ := NewRequest("GET", ts2.URL, nil)
1432 req.Header.Add("User-Agent", ua)
1433 req.Header.Add("X-Foo", xfoo)
1434 req.Header.Add("Cookie", "foo=bar")
1435 req.Header.Add("Authorization", "secretpassword")
1436 res, err := c.Do(req)
1440 defer res.Body.Close()
1441 if res.StatusCode != 200 {
1444 if got := res.Header.Get("Result"); got != "ok" {
1445 t.Errorf("result = %q; want ok", got)
1449 // Issue 17494: cookies should be altered when Client follows redirects.
1450 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1451 cookieMap := func(cs []*Cookie) map[string][]string {
1452 m := make(map[string][]string)
1453 for _, c := range cs {
1454 m[c.Name] = append(m[c.Name], c.Value)
1459 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1460 var want map[string][]string
1461 got := cookieMap(r.Cookies())
1463 c, _ := r.Cookie("Cycle")
1466 want = map[string][]string{
1467 "Cookie1": {"OldValue1a", "OldValue1b"},
1468 "Cookie2": {"OldValue2"},
1469 "Cookie3": {"OldValue3a", "OldValue3b"},
1470 "Cookie4": {"OldValue4"},
1473 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1474 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1475 Redirect(w, r, "/", StatusFound)
1477 want = map[string][]string{
1478 "Cookie1": {"OldValue1a", "OldValue1b"},
1479 "Cookie3": {"OldValue3a", "OldValue3b"},
1480 "Cookie4": {"OldValue4"},
1483 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1484 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1485 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1486 Redirect(w, r, "/", StatusFound)
1488 want = map[string][]string{
1489 "Cookie1": {"OldValue1a", "OldValue1b"},
1490 "Cookie3": {"NewValue3"},
1491 "Cookie4": {"NewValue4"},
1494 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1495 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1496 Redirect(w, r, "/", StatusFound)
1498 want = map[string][]string{
1499 "Cookie1": {"OldValue1a", "OldValue1b"},
1500 "Cookie3": {"NewValue3"},
1501 "Cookie4": {"NewValue4"},
1502 "Cookie5": {"NewValue5"},
1505 // Don't redirect to ensure the loop ends.
1507 t.Errorf("unexpected redirect cycle")
1511 if !reflect.DeepEqual(got, want) {
1512 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1518 defer tr.CloseIdleConnections()
1519 jar, _ := cookiejar.New(nil)
1525 u, _ := url.Parse(ts.URL)
1526 req, _ := NewRequest("GET", ts.URL, nil)
1527 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1528 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1529 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1530 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1531 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1532 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1533 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1534 res, err := c.Do(req)
1538 defer res.Body.Close()
1539 if res.StatusCode != 200 {
1544 // Part of Issue 4800
1545 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1552 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1553 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1555 // Sensitive headers:
1556 {"cookie", "http://foo.com/", "http://bar.com/", false},
1557 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1558 {"authorization", "http://foo.com/", "http://bar.com/", false},
1559 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1561 // But subdomains should work:
1562 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1563 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1564 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1565 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1566 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1568 for i, tt := range tests {
1569 u0, err := url.Parse(tt.initialURL)
1571 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1574 u1, err := url.Parse(tt.destURL)
1576 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1579 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1581 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1582 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1587 func TestClientRedirectTypes(t *testing.T) {
1591 tests := [...]struct {
1594 wantMethod string // desired subsequent client method
1596 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1597 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1598 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1599 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1600 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1602 5: {method: "HEAD", serverStatus: 301, wantMethod: "GET"},
1603 6: {method: "HEAD", serverStatus: 302, wantMethod: "GET"},
1604 7: {method: "HEAD", serverStatus: 303, wantMethod: "GET"},
1605 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1606 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1608 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1609 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1610 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1611 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1612 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1614 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1615 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1616 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1617 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1618 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1620 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1621 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1622 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1623 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1624 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1626 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1627 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1628 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1629 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1630 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1633 handlerc := make(chan HandlerFunc, 1)
1635 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1641 for i, tt := range tests {
1642 handlerc <- func(w ResponseWriter, r *Request) {
1643 w.Header().Set("Location", ts.URL)
1644 w.WriteHeader(tt.serverStatus)
1647 req, err := NewRequest(tt.method, ts.URL, nil)
1649 t.Errorf("#%d: NewRequest: %v", i, err)
1654 c.CheckRedirect = func(req *Request, via []*Request) error {
1655 if got, want := req.Method, tt.wantMethod; got != want {
1656 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1658 handlerc <- func(rw ResponseWriter, req *Request) {
1659 // TODO: Check that the body is valid when we do 307 and 308 support
1664 res, err := c.Do(req)
1666 t.Errorf("#%d: Response: %v", i, err)