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.
32 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
33 w.Header().Set("Last-Modified", "sometime")
34 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
37 // pedanticReadAll works like ioutil.ReadAll but additionally
38 // verifies that r obeys the documented io.Reader contract.
39 func pedanticReadAll(r io.Reader) (b []byte, err error) {
44 if n == 0 && err == nil {
45 return nil, fmt.Errorf("Read: n=0 with err=nil")
47 b = append(b, buf[:n]...)
50 if n != 0 || err != io.EOF {
51 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
61 type chanWriter chan string
63 func (w chanWriter) Write(p []byte) (n int, err error) {
68 func TestClient(t *testing.T) {
70 ts := httptest.NewServer(robotsTxtHandler)
76 b, err = pedanticReadAll(r.Body)
81 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
82 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
86 func TestClientHead_h1(t *testing.T) { testClientHead(t, false) }
87 func TestClientHead_h2(t *testing.T) { testClientHead(t, true) }
89 func testClientHead(t *testing.T, h2 bool) {
91 cst := newClientServerTest(t, h2, robotsTxtHandler)
94 r, err := cst.c.Head(cst.ts.URL)
98 if _, ok := r.Header["Last-Modified"]; !ok {
99 t.Error("Last-Modified header not found.")
103 type recordingTransport struct {
107 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
109 return nil, errors.New("dummy impl")
112 func TestGetRequestFormat(t *testing.T) {
114 tr := &recordingTransport{}
115 client := &Client{Transport: tr}
116 url := "http://dummy.faketld/"
117 client.Get(url) // Note: doesn't hit network
118 if tr.req.Method != "GET" {
119 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
121 if tr.req.URL.String() != url {
122 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
124 if tr.req.Header == nil {
125 t.Errorf("expected non-nil request Header")
129 func TestPostRequestFormat(t *testing.T) {
131 tr := &recordingTransport{}
132 client := &Client{Transport: tr}
134 url := "http://dummy.faketld/"
135 json := `{"key":"value"}`
136 b := strings.NewReader(json)
137 client.Post(url, "application/json", b) // Note: doesn't hit network
139 if tr.req.Method != "POST" {
140 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
142 if tr.req.URL.String() != url {
143 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
145 if tr.req.Header == nil {
146 t.Fatalf("expected non-nil request Header")
149 t.Error("got Close true, want false")
151 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
152 t.Errorf("got ContentLength %d, want %d", g, e)
156 func TestPostFormRequestFormat(t *testing.T) {
158 tr := &recordingTransport{}
159 client := &Client{Transport: tr}
161 urlStr := "http://dummy.faketld/"
162 form := make(url.Values)
163 form.Set("foo", "bar")
164 form.Add("foo", "bar2")
165 form.Set("bar", "baz")
166 client.PostForm(urlStr, form) // Note: doesn't hit network
168 if tr.req.Method != "POST" {
169 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
171 if tr.req.URL.String() != urlStr {
172 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
174 if tr.req.Header == nil {
175 t.Fatalf("expected non-nil request Header")
177 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
178 t.Errorf("got Content-Type %q, want %q", g, e)
181 t.Error("got Close true, want false")
183 // Depending on map iteration, body can be either of these.
184 expectedBody := "foo=bar&foo=bar2&bar=baz"
185 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
186 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
187 t.Errorf("got ContentLength %d, want %d", g, e)
189 bodyb, err := ioutil.ReadAll(tr.req.Body)
191 t.Fatalf("ReadAll on req.Body: %v", err)
193 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
194 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
198 func TestClientRedirects(t *testing.T) {
200 var ts *httptest.Server
201 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
202 n, _ := strconv.Atoi(r.FormValue("n"))
203 // Test Referer header. (7 is arbitrary position to test at)
205 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
206 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
210 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusFound)
213 fmt.Fprintf(w, "n=%d", n)
218 _, err := c.Get(ts.URL)
219 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
220 t.Errorf("with default client Get, expected error %q, got %q", e, g)
223 // HEAD request should also have the ability to follow redirects.
224 _, err = c.Head(ts.URL)
225 if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
226 t.Errorf("with default client Head, expected error %q, got %q", e, g)
229 // Do should also follow redirects.
230 greq, _ := NewRequest("GET", ts.URL, nil)
232 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
233 t.Errorf("with default client Do, expected error %q, got %q", e, g)
236 // Requests with an empty Method should also redirect (Issue 12705)
239 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
240 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
244 var lastVia []*Request
245 c = &Client{CheckRedirect: func(_ *Request, via []*Request) error {
249 res, err := c.Get(ts.URL)
251 t.Fatalf("Get error: %v", err)
254 finalUrl := res.Request.URL.String()
255 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
256 t.Errorf("with custom client, expected error %q, got %q", e, g)
258 if !strings.HasSuffix(finalUrl, "/?n=15") {
259 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
261 if e, g := 15, len(lastVia); e != g {
262 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
265 checkErr = errors.New("no redirects allowed")
266 res, err = c.Get(ts.URL)
267 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
268 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
271 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
274 if res.Header.Get("Location") == "" {
275 t.Errorf("no Location header in Response")
279 func TestPostRedirects(t *testing.T) {
285 var ts *httptest.Server
286 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
288 fmt.Fprintf(&log.Buffer, "%s %s ", r.Method, r.RequestURI)
290 if v := r.URL.Query().Get("code"); v != "" {
291 code, _ := strconv.Atoi(v)
293 w.Header().Set("Location", ts.URL)
301 want int // response code
309 for _, tt := range tests {
310 res, err := Post(ts.URL+tt.suffix, "text/plain", strings.NewReader("Some content"))
314 if res.StatusCode != tt.want {
315 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
321 want := "POST / POST /?code=301 POST /?code=302 GET / POST /?code=303 GET / POST /?code=404 "
323 t.Errorf("Log differs.\n Got: %q\nWant: %q", got, want)
327 var expectedCookies = []*Cookie{
328 {Name: "ChocolateChip", Value: "tasty"},
329 {Name: "First", Value: "Hit"},
330 {Name: "Second", Value: "Hit"},
333 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
334 for _, cookie := range r.Cookies() {
337 if r.URL.Path == "/" {
338 SetCookie(w, expectedCookies[1])
339 Redirect(w, r, "/second", StatusMovedPermanently)
341 SetCookie(w, expectedCookies[2])
342 w.Write([]byte("hello"))
346 func TestClientSendsCookieFromJar(t *testing.T) {
348 tr := &recordingTransport{}
349 client := &Client{Transport: tr}
350 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
351 us := "http://dummy.faketld/"
352 u, _ := url.Parse(us)
353 client.Jar.SetCookies(u, expectedCookies)
355 client.Get(us) // Note: doesn't hit network
356 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
358 client.Head(us) // Note: doesn't hit network
359 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
361 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
362 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
364 client.PostForm(us, url.Values{}) // Note: doesn't hit network
365 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
367 req, _ := NewRequest("GET", us, nil)
368 client.Do(req) // Note: doesn't hit network
369 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
371 req, _ = NewRequest("POST", us, nil)
372 client.Do(req) // Note: doesn't hit network
373 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
376 // Just enough correctness for our redirect tests. Uses the URL.Host as the
377 // scope of all cookies.
378 type TestJar struct {
380 perURL map[string][]*Cookie
383 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
387 j.perURL = make(map[string][]*Cookie)
389 j.perURL[u.Host] = cookies
392 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
395 return j.perURL[u.Host]
398 func TestRedirectCookiesJar(t *testing.T) {
400 var ts *httptest.Server
401 ts = httptest.NewServer(echoCookiesRedirectHandler)
406 u, _ := url.Parse(ts.URL)
407 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
408 resp, err := c.Get(ts.URL)
410 t.Fatalf("Get: %v", err)
413 matchReturnedCookies(t, expectedCookies, resp.Cookies())
416 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
417 if len(given) != len(expected) {
418 t.Logf("Received cookies: %v", given)
419 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
421 for _, ec := range expected {
423 for _, c := range given {
424 if ec.Name == c.Name && ec.Value == c.Value {
430 t.Errorf("Missing cookie %v", ec)
435 func TestJarCalls(t *testing.T) {
437 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
438 pathSuffix := r.RequestURI[1:]
439 if r.RequestURI == "/nosetcookie" {
440 return // don't set cookies for this path
442 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
443 if r.RequestURI == "/" {
444 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
448 jar := new(RecordingJar)
451 Transport: &Transport{
452 Dial: func(_ string, _ string) (net.Conn, error) {
453 return net.Dial("tcp", ts.Listener.Addr().String())
457 _, err := c.Get("http://firsthost.fake/")
461 _, err = c.Get("http://firsthost.fake/nosetcookie")
465 got := jar.log.String()
466 want := `Cookies("http://firsthost.fake/")
467 SetCookie("http://firsthost.fake/", [name=val])
468 Cookies("http://secondhost.fake/secondpath")
469 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
470 Cookies("http://firsthost.fake/nosetcookie")
473 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
477 // RecordingJar keeps a log of calls made to it, without
478 // tracking any cookies.
479 type RecordingJar struct {
484 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
485 j.logf("SetCookie(%q, %v)\n", u, cookies)
488 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
489 j.logf("Cookies(%q)\n", u)
493 func (j *RecordingJar) logf(format string, args ...interface{}) {
496 fmt.Fprintf(&j.log, format, args...)
499 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, false) }
500 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, true) }
502 func testStreamingGet(t *testing.T, h2 bool) {
504 say := make(chan string)
505 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
507 for str := range say {
515 res, err := c.Get(cst.ts.URL)
520 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
522 n, err := io.ReadFull(res.Body, buf[0:len(str)])
524 t.Fatalf("ReadFull on %q: %v", str, err)
527 t.Fatalf("Receiving %q, only read %d bytes", str, n)
529 got := string(buf[0:n])
531 t.Fatalf("Expected %q, got %q", str, got)
535 _, err = io.ReadFull(res.Body, buf[0:1])
537 t.Fatalf("at end expected EOF, got %v", err)
541 type writeCountingConn struct {
546 func (c *writeCountingConn) Write(p []byte) (int, error) {
548 return c.Conn.Write(p)
551 // TestClientWrites verifies that client requests are buffered and we
552 // don't send a TCP packet per line of the http request + body.
553 func TestClientWrites(t *testing.T) {
555 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
560 dialer := func(netz string, addr string) (net.Conn, error) {
561 c, err := net.Dial(netz, addr)
563 c = &writeCountingConn{c, &writes}
567 c := &Client{Transport: &Transport{Dial: dialer}}
569 _, err := c.Get(ts.URL)
574 t.Errorf("Get request did %d Write calls, want 1", writes)
578 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
583 t.Errorf("Post request did %d Write calls, want 1", writes)
587 func TestClientInsecureTransport(t *testing.T) {
589 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
590 w.Write([]byte("Hello"))
592 errc := make(chanWriter, 10) // but only expecting 1
593 ts.Config.ErrorLog = log.New(errc, "", 0)
596 // TODO(bradfitz): add tests for skipping hostname checks too?
597 // would require a new cert for testing, and probably
598 // redundant with these tests.
599 for _, insecure := range []bool{true, false} {
601 TLSClientConfig: &tls.Config{
602 InsecureSkipVerify: insecure,
605 defer tr.CloseIdleConnections()
606 c := &Client{Transport: tr}
607 res, err := c.Get(ts.URL)
608 if (err == nil) != insecure {
609 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
618 if !strings.Contains(v, "TLS handshake error") {
619 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
621 case <-time.After(5 * time.Second):
622 t.Errorf("timeout waiting for logged error")
627 func TestClientErrorWithRequestURI(t *testing.T) {
629 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
630 req.RequestURI = "/this/field/is/illegal/and/should/error/"
631 _, err := DefaultClient.Do(req)
633 t.Fatalf("expected an error")
635 if !strings.Contains(err.Error(), "RequestURI") {
636 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
640 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
641 certs := x509.NewCertPool()
642 for _, c := range ts.TLS.Certificates {
643 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
645 t.Fatalf("error parsing server's root cert: %v", err)
647 for _, root := range roots {
652 TLSClientConfig: &tls.Config{RootCAs: certs},
656 func TestClientWithCorrectTLSServerName(t *testing.T) {
659 const serverName = "example.com"
660 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
661 if r.TLS.ServerName != serverName {
662 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
667 trans := newTLSTransport(t, ts)
668 trans.TLSClientConfig.ServerName = serverName
669 c := &Client{Transport: trans}
670 if _, err := c.Get(ts.URL); err != nil {
671 t.Fatalf("expected successful TLS connection, got error: %v", err)
675 func TestClientWithIncorrectTLSServerName(t *testing.T) {
677 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
679 errc := make(chanWriter, 10) // but only expecting 1
680 ts.Config.ErrorLog = log.New(errc, "", 0)
682 trans := newTLSTransport(t, ts)
683 trans.TLSClientConfig.ServerName = "badserver"
684 c := &Client{Transport: trans}
685 _, err := c.Get(ts.URL)
687 t.Fatalf("expected an error")
689 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
690 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
694 if !strings.Contains(v, "TLS handshake error") {
695 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
697 case <-time.After(5 * time.Second):
698 t.Errorf("timeout waiting for logged error")
702 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
705 // tls.Config.ServerName (non-empty, set to "example.com") takes
706 // precedence over "some-other-host.tld" which previously incorrectly
707 // took precedence. We don't actually connect to (or even resolve)
708 // "some-other-host.tld", though, because of the Transport.Dial hook.
710 // The httptest.Server has a cert with "example.com" as its name.
711 func TestTransportUsesTLSConfigServerName(t *testing.T) {
713 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
714 w.Write([]byte("Hello"))
718 tr := newTLSTransport(t, ts)
719 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
720 tr.Dial = func(netw, addr string) (net.Conn, error) {
721 return net.Dial(netw, ts.Listener.Addr().String())
723 defer tr.CloseIdleConnections()
724 c := &Client{Transport: tr}
725 res, err := c.Get("https://some-other-host.tld/")
732 func TestResponseSetsTLSConnectionState(t *testing.T) {
734 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
735 w.Write([]byte("Hello"))
739 tr := newTLSTransport(t, ts)
740 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
741 tr.Dial = func(netw, addr string) (net.Conn, error) {
742 return net.Dial(netw, ts.Listener.Addr().String())
744 defer tr.CloseIdleConnections()
745 c := &Client{Transport: tr}
746 res, err := c.Get("https://example.com/")
750 defer res.Body.Close()
752 t.Fatal("Response didn't set TLS Connection State.")
754 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
755 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
759 // Check that an HTTPS client can interpret a particular TLS error
760 // to determine that the server is speaking HTTP.
761 // See golang.org/issue/11111.
762 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
764 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
767 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
768 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
769 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
773 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
774 func TestClientHeadContentLength_h1(t *testing.T) {
775 testClientHeadContentLength(t, false)
778 func TestClientHeadContentLength_h2(t *testing.T) {
779 testClientHeadContentLength(t, true)
782 func testClientHeadContentLength(t *testing.T, h2 bool) {
784 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
785 if v := r.FormValue("cl"); v != "" {
786 w.Header().Set("Content-Length", v)
798 for _, tt := range tests {
799 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
800 res, err := cst.c.Do(req)
804 if res.ContentLength != tt.want {
805 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
807 bs, err := ioutil.ReadAll(res.Body)
812 t.Errorf("Unexpected content: %q", bs)
817 func TestEmptyPasswordAuth(t *testing.T) {
820 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
821 auth := r.Header.Get("Authorization")
822 if strings.HasPrefix(auth, "Basic ") {
824 decoded, err := base64.StdEncoding.DecodeString(encoded)
828 expected := gopher + ":"
831 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
834 t.Errorf("Invalid auth %q", auth)
839 req, err := NewRequest("GET", ts.URL, nil)
843 req.URL.User = url.User(gopher)
844 resp, err := c.Do(req)
848 defer resp.Body.Close()
851 func TestBasicAuth(t *testing.T) {
853 tr := &recordingTransport{}
854 client := &Client{Transport: tr}
856 url := "http://My%20User:My%20Pass@dummy.faketld/"
857 expected := "My User:My Pass"
860 if tr.req.Method != "GET" {
861 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
863 if tr.req.URL.String() != url {
864 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
866 if tr.req.Header == nil {
867 t.Fatalf("expected non-nil request Header")
869 auth := tr.req.Header.Get("Authorization")
870 if strings.HasPrefix(auth, "Basic ") {
872 decoded, err := base64.StdEncoding.DecodeString(encoded)
878 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
881 t.Errorf("Invalid auth %q", auth)
885 func TestBasicAuthHeadersPreserved(t *testing.T) {
887 tr := &recordingTransport{}
888 client := &Client{Transport: tr}
890 // If Authorization header is provided, username in URL should not override it
891 url := "http://My%20User@dummy.faketld/"
892 req, err := NewRequest("GET", url, nil)
896 req.SetBasicAuth("My User", "My Pass")
897 expected := "My User:My Pass"
900 if tr.req.Method != "GET" {
901 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
903 if tr.req.URL.String() != url {
904 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
906 if tr.req.Header == nil {
907 t.Fatalf("expected non-nil request Header")
909 auth := tr.req.Header.Get("Authorization")
910 if strings.HasPrefix(auth, "Basic ") {
912 decoded, err := base64.StdEncoding.DecodeString(encoded)
918 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
921 t.Errorf("Invalid auth %q", auth)
926 func TestClientTimeout(t *testing.T) {
928 t.Skip("skipping in short mode")
931 sawRoot := make(chan bool, 1)
932 sawSlow := make(chan bool, 1)
933 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
934 if r.URL.Path == "/" {
936 Redirect(w, r, "/slow", StatusFound)
939 if r.URL.Path == "/slow" {
940 w.Write([]byte("Hello"))
943 time.Sleep(2 * time.Second)
948 const timeout = 500 * time.Millisecond
953 res, err := c.Get(ts.URL)
962 t.Fatal("handler never got / request")
969 t.Fatal("handler never got /slow request")
972 errc := make(chan error, 1)
974 _, err := ioutil.ReadAll(res.Body)
979 const failTime = timeout * 2
983 t.Fatal("expected error from ReadAll")
985 ne, ok := err.(net.Error)
987 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
988 } else if !ne.Timeout() {
989 t.Errorf("net.Error.Timeout = false; want true")
991 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
992 t.Errorf("error string = %q; missing timeout substring", got)
994 case <-time.After(failTime):
995 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
999 // Client.Timeout firing before getting to the body
1000 func TestClientTimeout_Headers(t *testing.T) {
1001 if testing.Short() {
1002 t.Skip("skipping in short mode")
1005 donec := make(chan bool)
1006 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1010 // Note that we use a channel send here and not a close.
1011 // The race detector doesn't know that we're waiting for a timeout
1012 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1013 // with us closing it. If we timed out immediately, we could close the testserver
1014 // before we entered the handler. We're not timing out immediately and there's
1015 // no way we would be done before we entered the handler, but the race detector
1016 // doesn't know this, so synchronize explicitly.
1017 defer func() { donec <- true }()
1019 c := &Client{Timeout: 500 * time.Millisecond}
1021 _, err := c.Get(ts.URL)
1023 t.Fatal("got response from Get; expected error")
1025 if _, ok := err.(*url.Error); !ok {
1026 t.Fatalf("Got error of type %T; want *url.Error", err)
1028 ne, ok := err.(net.Error)
1030 t.Fatalf("Got error of type %T; want some net.Error", err)
1033 t.Error("net.Error.Timeout = false; want true")
1035 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1036 t.Errorf("error string = %q; missing timeout substring", got)
1040 func TestClientRedirectEatsBody_h1(t *testing.T) {
1041 testClientRedirectEatsBody(t, false)
1044 func TestClientRedirectEatsBody_h2(t *testing.T) {
1045 testClientRedirectEatsBody(t, true)
1048 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1050 saw := make(chan string, 2)
1051 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1053 if r.URL.Path == "/" {
1054 Redirect(w, r, "/foo", StatusFound) // which includes a body
1059 res, err := cst.c.Get(cst.ts.URL)
1063 _, err = ioutil.ReadAll(res.Body)
1073 t.Fatal("server didn't see a request")
1078 case second = <-saw:
1080 t.Fatal("server didn't see a second request")
1083 if first != second {
1084 t.Fatal("server saw different client ports before & after the redirect")
1088 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1089 type eofReaderFunc func()
1091 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1096 func TestClientTrailers(t *testing.T) {
1098 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1099 w.Header().Set("Connection", "close")
1100 w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B")
1101 w.Header().Add("Trailer", "Server-Trailer-C")
1104 for k := range r.Trailer {
1105 decl = append(decl, k)
1109 slurp, err := ioutil.ReadAll(r.Body)
1111 t.Errorf("Server reading request body: %v", err)
1113 if string(slurp) != "foo" {
1114 t.Errorf("Server read request body %q; want foo", slurp)
1116 if r.Trailer == nil {
1117 io.WriteString(w, "nil Trailer")
1119 fmt.Fprintf(w, "decl: %v, vals: %s, %s",
1121 r.Trailer.Get("Client-Trailer-A"),
1122 r.Trailer.Get("Client-Trailer-B"))
1125 // How handlers set Trailers: declare it ahead of time
1126 // with the Trailer header, and then mutate the
1127 // Header() of those values later, after the response
1128 // has been written (we wrote to w above).
1129 w.Header().Set("Server-Trailer-A", "valuea")
1130 w.Header().Set("Server-Trailer-C", "valuec") // skipping B
1135 req, _ = NewRequest("POST", ts.URL, io.MultiReader(
1136 eofReaderFunc(func() {
1137 req.Trailer["Client-Trailer-A"] = []string{"valuea"}
1139 strings.NewReader("foo"),
1140 eofReaderFunc(func() {
1141 req.Trailer["Client-Trailer-B"] = []string{"valueb"}
1144 req.Trailer = Header{
1145 "Client-Trailer-A": nil, // to be set later
1146 "Client-Trailer-B": nil, // to be set later
1148 req.ContentLength = -1
1149 res, err := DefaultClient.Do(req)
1153 if err := wantBody(res, err, "decl: [Client-Trailer-A Client-Trailer-B], vals: valuea, valueb"); err != nil {
1157 "Server-Trailer-A": []string{"valuea"},
1158 "Server-Trailer-B": nil,
1159 "Server-Trailer-C": []string{"valuec"},
1161 if !reflect.DeepEqual(res.Trailer, want) {
1162 t.Errorf("Response trailers = %#v; want %#v", res.Trailer, want)
1166 func TestReferer(t *testing.T) {
1168 lastReq, newReq string // from -> to URLs
1172 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1173 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1175 // don't send a user and password:
1176 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1177 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1180 {"http://test.com", "http://link.com", "http://test.com"},
1181 {"https://test.com", "https://link.com", "https://test.com"},
1183 // https to http doesn't send a referer:
1184 {"https://test.com", "http://link.com", ""},
1185 {"https://gopher:go@test.com", "http://link.com", ""},
1187 for _, tt := range tests {
1188 l, err := url.Parse(tt.lastReq)
1192 n, err := url.Parse(tt.newReq)
1196 r := ExportRefererForURL(l, n)
1198 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)