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) {
201 var ts *httptest.Server
202 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
203 n, _ := strconv.Atoi(r.FormValue("n"))
204 // Test Referer header. (7 is arbitrary position to test at)
206 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
207 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
211 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
214 fmt.Fprintf(w, "n=%d", n)
219 _, err := c.Get(ts.URL)
220 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
221 t.Errorf("with default client Get, expected error %q, got %q", e, g)
224 // HEAD request should also have the ability to follow redirects.
225 _, err = c.Head(ts.URL)
226 if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
227 t.Errorf("with default client Head, expected error %q, got %q", e, g)
230 // Do should also follow redirects.
231 greq, _ := NewRequest("GET", ts.URL, nil)
233 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
234 t.Errorf("with default client Do, expected error %q, got %q", e, g)
237 // Requests with an empty Method should also redirect (Issue 12705)
240 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
241 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
245 var lastVia []*Request
247 c = &Client{CheckRedirect: func(req *Request, via []*Request) error {
252 res, err := c.Get(ts.URL)
254 t.Fatalf("Get error: %v", err)
257 finalUrl := res.Request.URL.String()
258 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
259 t.Errorf("with custom client, expected error %q, got %q", e, g)
261 if !strings.HasSuffix(finalUrl, "/?n=15") {
262 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
264 if e, g := 15, len(lastVia); e != g {
265 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
268 // Test that Request.Cancel is propagated between requests (Issue 14053)
269 creq, _ := NewRequest("HEAD", ts.URL, nil)
270 cancel := make(chan struct{})
272 if _, err := c.Do(creq); err != nil {
276 t.Fatal("didn't see redirect")
278 if lastReq.Cancel != cancel {
279 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
282 checkErr = errors.New("no redirects allowed")
283 res, err = c.Get(ts.URL)
284 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
285 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
288 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
291 if res.Header.Get("Location") == "" {
292 t.Errorf("no Location header in Response")
296 func TestClientRedirectContext(t *testing.T) {
298 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
299 Redirect(w, r, "/", StatusTemporaryRedirect)
303 ctx, cancel := context.WithCancel(context.Background())
304 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
307 return errors.New("too many redirects")
311 req, _ := NewRequest("GET", ts.URL, nil)
312 req = req.WithContext(ctx)
314 ue, ok := err.(*url.Error)
316 t.Fatalf("got error %T; want *url.Error", err)
318 if ue.Err != context.Canceled {
319 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
323 type redirectTest struct {
325 want int // response code
329 func TestPostRedirects(t *testing.T) {
330 postRedirectTests := []redirectTest{
332 {"/?code=301&next=302", 200, "c301"},
333 {"/?code=302&next=302", 200, "c302"},
334 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
335 {"/?code=304", 304, "c304"},
336 {"/?code=305", 305, "c305"},
337 {"/?code=307&next=303,308,302", 200, "c307"},
338 {"/?code=308&next=302,301", 200, "c308"},
339 {"/?code=404", 404, "c404"},
342 wantSegments := []string{
344 `POST /?code=301&next=302 "c301"`,
345 `GET /?code=302 "c301"`,
347 `POST /?code=302&next=302 "c302"`,
348 `GET /?code=302 "c302"`,
350 `POST /?code=303&next=301 "c303wc301"`,
351 `GET /?code=301 "c303wc301"`,
353 `POST /?code=304 "c304"`,
354 `POST /?code=305 "c305"`,
355 `POST /?code=307&next=303,308,302 "c307"`,
356 `POST /?code=303&next=308,302 "c307"`,
357 `GET /?code=308&next=302 "c307"`,
358 `GET /?code=302 "c307"`,
360 `POST /?code=308&next=302,301 "c308"`,
361 `POST /?code=302&next=301 "c308"`,
362 `GET /?code=301 "c308"`,
364 `POST /?code=404 "c404"`,
366 want := strings.Join(wantSegments, "\n")
367 testRedirectsByMethod(t, "POST", postRedirectTests, want)
370 func TestDeleteRedirects(t *testing.T) {
371 deleteRedirectTests := []redirectTest{
373 {"/?code=301&next=302,308", 200, "c301"},
374 {"/?code=302&next=302", 200, "c302"},
375 {"/?code=303", 200, "c303"},
376 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
377 {"/?code=308&next=307", 200, "c308"},
378 {"/?code=404", 404, "c404"},
381 wantSegments := []string{
383 `DELETE /?code=301&next=302,308 "c301"`,
384 `GET /?code=302&next=308 "c301"`,
385 `GET /?code=308 "c301"`,
387 `DELETE /?code=302&next=302 "c302"`,
388 `GET /?code=302 "c302"`,
390 `DELETE /?code=303 "c303"`,
392 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
393 `DELETE /?code=301&next=308,303,302,304 "c307"`,
394 `GET /?code=308&next=303,302,304 "c307"`,
395 `GET /?code=303&next=302,304 "c307"`,
396 `GET /?code=302&next=304 "c307"`,
397 `GET /?code=304 "c307"`,
398 `DELETE /?code=308&next=307 "c308"`,
399 `DELETE /?code=307 "c308"`,
401 `DELETE /?code=404 "c404"`,
403 want := strings.Join(wantSegments, "\n")
404 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
407 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
413 var ts *httptest.Server
414 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
416 slurp, _ := ioutil.ReadAll(r.Body)
417 fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp)
419 urlQuery := r.URL.Query()
420 if v := urlQuery.Get("code"); v != "" {
422 if final := urlQuery.Get("next"); final != "" {
423 splits := strings.Split(final, ",")
424 first, rest := splits[0], splits[1:]
425 location = fmt.Sprintf("%s?code=%s", location, first)
427 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
430 code, _ := strconv.Atoi(v)
432 w.Header().Set("Location", location)
439 for _, tt := range table {
440 content := tt.redirectBody
441 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
442 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
443 res, err := DefaultClient.Do(req)
448 if res.StatusCode != tt.want {
449 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
456 got = strings.TrimSpace(got)
457 want = strings.TrimSpace(want)
460 t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want)
464 func TestClientRedirectUseResponse(t *testing.T) {
466 const body = "Hello, world."
467 var ts *httptest.Server
468 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
469 if strings.Contains(r.URL.Path, "/other") {
470 io.WriteString(w, "wrong body")
472 w.Header().Set("Location", ts.URL+"/other")
473 w.WriteHeader(StatusFound)
474 io.WriteString(w, body)
479 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
480 if req.Response == nil {
481 t.Error("expected non-nil Request.Response")
483 return ErrUseLastResponse
485 res, err := c.Get(ts.URL)
489 if res.StatusCode != StatusFound {
490 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
492 defer res.Body.Close()
493 slurp, err := ioutil.ReadAll(res.Body)
497 if string(slurp) != body {
498 t.Errorf("body = %q; want %q", slurp, body)
502 var expectedCookies = []*Cookie{
503 {Name: "ChocolateChip", Value: "tasty"},
504 {Name: "First", Value: "Hit"},
505 {Name: "Second", Value: "Hit"},
508 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
509 for _, cookie := range r.Cookies() {
512 if r.URL.Path == "/" {
513 SetCookie(w, expectedCookies[1])
514 Redirect(w, r, "/second", StatusMovedPermanently)
516 SetCookie(w, expectedCookies[2])
517 w.Write([]byte("hello"))
521 func TestClientSendsCookieFromJar(t *testing.T) {
523 tr := &recordingTransport{}
524 client := &Client{Transport: tr}
525 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
526 us := "http://dummy.faketld/"
527 u, _ := url.Parse(us)
528 client.Jar.SetCookies(u, expectedCookies)
530 client.Get(us) // Note: doesn't hit network
531 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
533 client.Head(us) // Note: doesn't hit network
534 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
536 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
537 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
539 client.PostForm(us, url.Values{}) // Note: doesn't hit network
540 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
542 req, _ := NewRequest("GET", us, nil)
543 client.Do(req) // Note: doesn't hit network
544 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
546 req, _ = NewRequest("POST", us, nil)
547 client.Do(req) // Note: doesn't hit network
548 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
551 // Just enough correctness for our redirect tests. Uses the URL.Host as the
552 // scope of all cookies.
553 type TestJar struct {
555 perURL map[string][]*Cookie
558 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
562 j.perURL = make(map[string][]*Cookie)
564 j.perURL[u.Host] = cookies
567 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
570 return j.perURL[u.Host]
573 func TestRedirectCookiesJar(t *testing.T) {
575 var ts *httptest.Server
576 ts = httptest.NewServer(echoCookiesRedirectHandler)
581 u, _ := url.Parse(ts.URL)
582 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
583 resp, err := c.Get(ts.URL)
585 t.Fatalf("Get: %v", err)
588 matchReturnedCookies(t, expectedCookies, resp.Cookies())
591 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
592 if len(given) != len(expected) {
593 t.Logf("Received cookies: %v", given)
594 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
596 for _, ec := range expected {
598 for _, c := range given {
599 if ec.Name == c.Name && ec.Value == c.Value {
605 t.Errorf("Missing cookie %v", ec)
610 func TestJarCalls(t *testing.T) {
612 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
613 pathSuffix := r.RequestURI[1:]
614 if r.RequestURI == "/nosetcookie" {
615 return // don't set cookies for this path
617 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
618 if r.RequestURI == "/" {
619 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
623 jar := new(RecordingJar)
626 Transport: &Transport{
627 Dial: func(_ string, _ string) (net.Conn, error) {
628 return net.Dial("tcp", ts.Listener.Addr().String())
632 _, err := c.Get("http://firsthost.fake/")
636 _, err = c.Get("http://firsthost.fake/nosetcookie")
640 got := jar.log.String()
641 want := `Cookies("http://firsthost.fake/")
642 SetCookie("http://firsthost.fake/", [name=val])
643 Cookies("http://secondhost.fake/secondpath")
644 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
645 Cookies("http://firsthost.fake/nosetcookie")
648 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
652 // RecordingJar keeps a log of calls made to it, without
653 // tracking any cookies.
654 type RecordingJar struct {
659 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
660 j.logf("SetCookie(%q, %v)\n", u, cookies)
663 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
664 j.logf("Cookies(%q)\n", u)
668 func (j *RecordingJar) logf(format string, args ...interface{}) {
671 fmt.Fprintf(&j.log, format, args...)
674 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
675 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
677 func testStreamingGet(t *testing.T, h2 bool) {
679 say := make(chan string)
680 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
682 for str := range say {
690 res, err := c.Get(cst.ts.URL)
695 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
697 n, err := io.ReadFull(res.Body, buf[0:len(str)])
699 t.Fatalf("ReadFull on %q: %v", str, err)
702 t.Fatalf("Receiving %q, only read %d bytes", str, n)
704 got := string(buf[0:n])
706 t.Fatalf("Expected %q, got %q", str, got)
710 _, err = io.ReadFull(res.Body, buf[0:1])
712 t.Fatalf("at end expected EOF, got %v", err)
716 type writeCountingConn struct {
721 func (c *writeCountingConn) Write(p []byte) (int, error) {
723 return c.Conn.Write(p)
726 // TestClientWrites verifies that client requests are buffered and we
727 // don't send a TCP packet per line of the http request + body.
728 func TestClientWrites(t *testing.T) {
730 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
735 dialer := func(netz string, addr string) (net.Conn, error) {
736 c, err := net.Dial(netz, addr)
738 c = &writeCountingConn{c, &writes}
742 c := &Client{Transport: &Transport{Dial: dialer}}
744 _, err := c.Get(ts.URL)
749 t.Errorf("Get request did %d Write calls, want 1", writes)
753 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
758 t.Errorf("Post request did %d Write calls, want 1", writes)
762 func TestClientInsecureTransport(t *testing.T) {
764 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
765 w.Write([]byte("Hello"))
767 errc := make(chanWriter, 10) // but only expecting 1
768 ts.Config.ErrorLog = log.New(errc, "", 0)
771 // TODO(bradfitz): add tests for skipping hostname checks too?
772 // would require a new cert for testing, and probably
773 // redundant with these tests.
774 for _, insecure := range []bool{true, false} {
776 TLSClientConfig: &tls.Config{
777 InsecureSkipVerify: insecure,
780 defer tr.CloseIdleConnections()
781 c := &Client{Transport: tr}
782 res, err := c.Get(ts.URL)
783 if (err == nil) != insecure {
784 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
793 if !strings.Contains(v, "TLS handshake error") {
794 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
796 case <-time.After(5 * time.Second):
797 t.Errorf("timeout waiting for logged error")
802 func TestClientErrorWithRequestURI(t *testing.T) {
804 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
805 req.RequestURI = "/this/field/is/illegal/and/should/error/"
806 _, err := DefaultClient.Do(req)
808 t.Fatalf("expected an error")
810 if !strings.Contains(err.Error(), "RequestURI") {
811 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
815 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
816 certs := x509.NewCertPool()
817 for _, c := range ts.TLS.Certificates {
818 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
820 t.Fatalf("error parsing server's root cert: %v", err)
822 for _, root := range roots {
827 TLSClientConfig: &tls.Config{RootCAs: certs},
831 func TestClientWithCorrectTLSServerName(t *testing.T) {
834 const serverName = "example.com"
835 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
836 if r.TLS.ServerName != serverName {
837 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
842 trans := newTLSTransport(t, ts)
843 trans.TLSClientConfig.ServerName = serverName
844 c := &Client{Transport: trans}
845 if _, err := c.Get(ts.URL); err != nil {
846 t.Fatalf("expected successful TLS connection, got error: %v", err)
850 func TestClientWithIncorrectTLSServerName(t *testing.T) {
852 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
854 errc := make(chanWriter, 10) // but only expecting 1
855 ts.Config.ErrorLog = log.New(errc, "", 0)
857 trans := newTLSTransport(t, ts)
858 trans.TLSClientConfig.ServerName = "badserver"
859 c := &Client{Transport: trans}
860 _, err := c.Get(ts.URL)
862 t.Fatalf("expected an error")
864 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
865 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
869 if !strings.Contains(v, "TLS handshake error") {
870 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
872 case <-time.After(5 * time.Second):
873 t.Errorf("timeout waiting for logged error")
877 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
880 // tls.Config.ServerName (non-empty, set to "example.com") takes
881 // precedence over "some-other-host.tld" which previously incorrectly
882 // took precedence. We don't actually connect to (or even resolve)
883 // "some-other-host.tld", though, because of the Transport.Dial hook.
885 // The httptest.Server has a cert with "example.com" as its name.
886 func TestTransportUsesTLSConfigServerName(t *testing.T) {
888 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
889 w.Write([]byte("Hello"))
893 tr := newTLSTransport(t, ts)
894 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
895 tr.Dial = func(netw, addr string) (net.Conn, error) {
896 return net.Dial(netw, ts.Listener.Addr().String())
898 defer tr.CloseIdleConnections()
899 c := &Client{Transport: tr}
900 res, err := c.Get("https://some-other-host.tld/")
907 func TestResponseSetsTLSConnectionState(t *testing.T) {
909 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
910 w.Write([]byte("Hello"))
914 tr := newTLSTransport(t, ts)
915 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
916 tr.Dial = func(netw, addr string) (net.Conn, error) {
917 return net.Dial(netw, ts.Listener.Addr().String())
919 defer tr.CloseIdleConnections()
920 c := &Client{Transport: tr}
921 res, err := c.Get("https://example.com/")
925 defer res.Body.Close()
927 t.Fatal("Response didn't set TLS Connection State.")
929 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
930 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
934 // Check that an HTTPS client can interpret a particular TLS error
935 // to determine that the server is speaking HTTP.
936 // See golang.org/issue/11111.
937 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
939 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
942 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
943 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
944 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
948 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
949 func TestClientHeadContentLength_h1(t *testing.T) {
950 testClientHeadContentLength(t, h1Mode)
953 func TestClientHeadContentLength_h2(t *testing.T) {
954 testClientHeadContentLength(t, h2Mode)
957 func testClientHeadContentLength(t *testing.T, h2 bool) {
959 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
960 if v := r.FormValue("cl"); v != "" {
961 w.Header().Set("Content-Length", v)
973 for _, tt := range tests {
974 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
975 res, err := cst.c.Do(req)
979 if res.ContentLength != tt.want {
980 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
982 bs, err := ioutil.ReadAll(res.Body)
987 t.Errorf("Unexpected content: %q", bs)
992 func TestEmptyPasswordAuth(t *testing.T) {
995 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
996 auth := r.Header.Get("Authorization")
997 if strings.HasPrefix(auth, "Basic ") {
999 decoded, err := base64.StdEncoding.DecodeString(encoded)
1003 expected := gopher + ":"
1004 s := string(decoded)
1006 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1009 t.Errorf("Invalid auth %q", auth)
1014 req, err := NewRequest("GET", ts.URL, nil)
1018 req.URL.User = url.User(gopher)
1019 resp, err := c.Do(req)
1023 defer resp.Body.Close()
1026 func TestBasicAuth(t *testing.T) {
1028 tr := &recordingTransport{}
1029 client := &Client{Transport: tr}
1031 url := "http://My%20User:My%20Pass@dummy.faketld/"
1032 expected := "My User:My Pass"
1035 if tr.req.Method != "GET" {
1036 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1038 if tr.req.URL.String() != url {
1039 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1041 if tr.req.Header == nil {
1042 t.Fatalf("expected non-nil request Header")
1044 auth := tr.req.Header.Get("Authorization")
1045 if strings.HasPrefix(auth, "Basic ") {
1047 decoded, err := base64.StdEncoding.DecodeString(encoded)
1051 s := string(decoded)
1053 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1056 t.Errorf("Invalid auth %q", auth)
1060 func TestBasicAuthHeadersPreserved(t *testing.T) {
1062 tr := &recordingTransport{}
1063 client := &Client{Transport: tr}
1065 // If Authorization header is provided, username in URL should not override it
1066 url := "http://My%20User@dummy.faketld/"
1067 req, err := NewRequest("GET", url, nil)
1071 req.SetBasicAuth("My User", "My Pass")
1072 expected := "My User:My Pass"
1075 if tr.req.Method != "GET" {
1076 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1078 if tr.req.URL.String() != url {
1079 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1081 if tr.req.Header == nil {
1082 t.Fatalf("expected non-nil request Header")
1084 auth := tr.req.Header.Get("Authorization")
1085 if strings.HasPrefix(auth, "Basic ") {
1087 decoded, err := base64.StdEncoding.DecodeString(encoded)
1091 s := string(decoded)
1093 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1096 t.Errorf("Invalid auth %q", auth)
1101 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1102 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1104 func testClientTimeout(t *testing.T, h2 bool) {
1105 if testing.Short() {
1106 t.Skip("skipping in short mode")
1109 sawRoot := make(chan bool, 1)
1110 sawSlow := make(chan bool, 1)
1111 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1112 if r.URL.Path == "/" {
1114 Redirect(w, r, "/slow", StatusFound)
1117 if r.URL.Path == "/slow" {
1118 w.Write([]byte("Hello"))
1121 time.Sleep(2 * time.Second)
1126 const timeout = 500 * time.Millisecond
1127 cst.c.Timeout = timeout
1129 res, err := cst.c.Get(cst.ts.URL)
1138 t.Fatal("handler never got / request")
1145 t.Fatal("handler never got /slow request")
1148 errc := make(chan error, 1)
1150 _, err := ioutil.ReadAll(res.Body)
1155 const failTime = timeout * 2
1159 t.Fatal("expected error from ReadAll")
1161 ne, ok := err.(net.Error)
1163 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1164 } else if !ne.Timeout() {
1165 t.Errorf("net.Error.Timeout = false; want true")
1167 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1168 t.Errorf("error string = %q; missing timeout substring", got)
1170 case <-time.After(failTime):
1171 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1175 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1176 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1178 // Client.Timeout firing before getting to the body
1179 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1180 if testing.Short() {
1181 t.Skip("skipping in short mode")
1184 donec := make(chan bool)
1185 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1189 // Note that we use a channel send here and not a close.
1190 // The race detector doesn't know that we're waiting for a timeout
1191 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1192 // with us closing it. If we timed out immediately, we could close the testserver
1193 // before we entered the handler. We're not timing out immediately and there's
1194 // no way we would be done before we entered the handler, but the race detector
1195 // doesn't know this, so synchronize explicitly.
1196 defer func() { donec <- true }()
1198 cst.c.Timeout = 500 * time.Millisecond
1199 _, err := cst.c.Get(cst.ts.URL)
1201 t.Fatal("got response from Get; expected error")
1203 if _, ok := err.(*url.Error); !ok {
1204 t.Fatalf("Got error of type %T; want *url.Error", err)
1206 ne, ok := err.(net.Error)
1208 t.Fatalf("Got error of type %T; want some net.Error", err)
1211 t.Error("net.Error.Timeout = false; want true")
1213 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1214 t.Errorf("error string = %q; missing timeout substring", got)
1218 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1219 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1220 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1222 saw := make(chan string, 2)
1223 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1225 if r.URL.Path == "/" {
1226 Redirect(w, r, "/foo", StatusFound) // which includes a body
1231 res, err := cst.c.Get(cst.ts.URL)
1235 _, err = ioutil.ReadAll(res.Body)
1245 t.Fatal("server didn't see a request")
1250 case second = <-saw:
1252 t.Fatal("server didn't see a second request")
1255 if first != second {
1256 t.Fatal("server saw different client ports before & after the redirect")
1260 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1261 type eofReaderFunc func()
1263 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1268 func TestReferer(t *testing.T) {
1270 lastReq, newReq string // from -> to URLs
1274 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1275 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1277 // don't send a user and password:
1278 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1279 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1282 {"http://test.com", "http://link.com", "http://test.com"},
1283 {"https://test.com", "https://link.com", "https://test.com"},
1285 // https to http doesn't send a referer:
1286 {"https://test.com", "http://link.com", ""},
1287 {"https://gopher:go@test.com", "http://link.com", ""},
1289 for _, tt := range tests {
1290 l, err := url.Parse(tt.lastReq)
1294 n, err := url.Parse(tt.newReq)
1298 r := ExportRefererForURL(l, n)
1300 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1305 // issue15577Tripper returns a Response with a redirect response
1306 // header and doesn't populate its Response.Request field.
1307 type issue15577Tripper struct{}
1309 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1312 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1313 Body: ioutil.NopCloser(strings.NewReader("")),
1318 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1319 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1321 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1322 Transport: issue15577Tripper{},
1324 // Check that this doesn't crash:
1325 c.Get("http://dummy.tld")
1328 // Issue 4800: copy (some) headers when Client follows a redirect
1329 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1331 ua = "some-agent/1.2"
1335 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1337 "User-Agent": []string{ua},
1338 "X-Foo": []string{xfoo},
1339 "Referer": []string{ts2URL},
1340 "Accept-Encoding": []string{"gzip"},
1342 if !reflect.DeepEqual(r.Header, want) {
1343 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1346 w.Header().Set("Result", "got errors")
1348 w.Header().Set("Result", "ok")
1352 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1353 Redirect(w, r, ts1.URL, StatusFound)
1359 defer tr.CloseIdleConnections()
1362 CheckRedirect: func(r *Request, via []*Request) error {
1364 "User-Agent": []string{ua},
1365 "X-Foo": []string{xfoo},
1366 "Referer": []string{ts2URL},
1368 if !reflect.DeepEqual(r.Header, want) {
1369 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1375 req, _ := NewRequest("GET", ts2.URL, nil)
1376 req.Header.Add("User-Agent", ua)
1377 req.Header.Add("X-Foo", xfoo)
1378 req.Header.Add("Cookie", "foo=bar")
1379 req.Header.Add("Authorization", "secretpassword")
1380 res, err := c.Do(req)
1384 defer res.Body.Close()
1385 if res.StatusCode != 200 {
1388 if got := res.Header.Get("Result"); got != "ok" {
1389 t.Errorf("result = %q; want ok", got)
1393 // Issue 17494: cookies should be altered when Client follows redirects.
1394 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1395 cookieMap := func(cs []*Cookie) map[string][]string {
1396 m := make(map[string][]string)
1397 for _, c := range cs {
1398 m[c.Name] = append(m[c.Name], c.Value)
1403 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1404 var want map[string][]string
1405 got := cookieMap(r.Cookies())
1407 c, _ := r.Cookie("Cycle")
1410 want = map[string][]string{
1411 "Cookie1": {"OldValue1a", "OldValue1b"},
1412 "Cookie2": {"OldValue2"},
1413 "Cookie3": {"OldValue3a", "OldValue3b"},
1414 "Cookie4": {"OldValue4"},
1417 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1418 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1419 Redirect(w, r, "/", StatusFound)
1421 want = map[string][]string{
1422 "Cookie1": {"OldValue1a", "OldValue1b"},
1423 "Cookie3": {"OldValue3a", "OldValue3b"},
1424 "Cookie4": {"OldValue4"},
1427 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1428 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1429 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1430 Redirect(w, r, "/", StatusFound)
1432 want = map[string][]string{
1433 "Cookie1": {"OldValue1a", "OldValue1b"},
1434 "Cookie3": {"NewValue3"},
1435 "Cookie4": {"NewValue4"},
1438 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1439 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1440 Redirect(w, r, "/", StatusFound)
1442 want = map[string][]string{
1443 "Cookie1": {"OldValue1a", "OldValue1b"},
1444 "Cookie3": {"NewValue3"},
1445 "Cookie4": {"NewValue4"},
1446 "Cookie5": {"NewValue5"},
1449 // Don't redirect to ensure the loop ends.
1451 t.Errorf("unexpected redirect cycle")
1455 if !reflect.DeepEqual(got, want) {
1456 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1462 defer tr.CloseIdleConnections()
1463 jar, _ := cookiejar.New(nil)
1469 u, _ := url.Parse(ts.URL)
1470 req, _ := NewRequest("GET", ts.URL, nil)
1471 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1472 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1473 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1474 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1475 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1476 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1477 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1478 res, err := c.Do(req)
1482 defer res.Body.Close()
1483 if res.StatusCode != 200 {
1488 // Part of Issue 4800
1489 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1496 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1497 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1499 // Sensitive headers:
1500 {"cookie", "http://foo.com/", "http://bar.com/", false},
1501 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1502 {"authorization", "http://foo.com/", "http://bar.com/", false},
1503 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1505 // But subdomains should work:
1506 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1507 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1508 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1509 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1510 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1512 for i, tt := range tests {
1513 u0, err := url.Parse(tt.initialURL)
1515 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1518 u1, err := url.Parse(tt.destURL)
1520 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1523 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1525 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1526 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1531 func TestClientRedirectTypes(t *testing.T) {
1534 tests := [...]struct {
1537 wantMethod string // desired subsequent client method
1539 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1540 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1541 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1542 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1543 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1545 5: {method: "HEAD", serverStatus: 301, wantMethod: "GET"},
1546 6: {method: "HEAD", serverStatus: 302, wantMethod: "GET"},
1547 7: {method: "HEAD", serverStatus: 303, wantMethod: "GET"},
1548 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1549 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1551 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1552 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1553 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1554 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1555 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1557 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1558 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1559 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1560 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1561 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1563 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1564 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1565 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1566 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1567 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1569 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1570 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1571 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1572 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1573 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1576 handlerc := make(chan HandlerFunc, 1)
1578 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1584 for i, tt := range tests {
1585 handlerc <- func(w ResponseWriter, r *Request) {
1586 w.Header().Set("Location", ts.URL)
1587 w.WriteHeader(tt.serverStatus)
1590 req, err := NewRequest(tt.method, ts.URL, nil)
1592 t.Errorf("#%d: NewRequest: %v", i, err)
1597 c.CheckRedirect = func(req *Request, via []*Request) error {
1598 if got, want := req.Method, tt.wantMethod; got != want {
1599 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1601 handlerc <- func(rw ResponseWriter, req *Request) {
1602 // TODO: Check that the body is valid when we do 307 and 308 support
1607 res, err := c.Do(req)
1609 t.Errorf("#%d: Response: %v", i, err)