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.
31 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
32 w.Header().Set("Last-Modified", "sometime")
33 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
36 // pedanticReadAll works like ioutil.ReadAll but additionally
37 // verifies that r obeys the documented io.Reader contract.
38 func pedanticReadAll(r io.Reader) (b []byte, err error) {
43 if n == 0 && err == nil {
44 return nil, fmt.Errorf("Read: n=0 with err=nil")
46 b = append(b, buf[:n]...)
49 if n != 0 || err != io.EOF {
50 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
60 type chanWriter chan string
62 func (w chanWriter) Write(p []byte) (n int, err error) {
67 func TestClient(t *testing.T) {
69 ts := httptest.NewServer(robotsTxtHandler)
75 b, err = pedanticReadAll(r.Body)
80 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
81 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
85 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
86 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
88 func testClientHead(t *testing.T, h2 bool) {
90 cst := newClientServerTest(t, h2, robotsTxtHandler)
93 r, err := cst.c.Head(cst.ts.URL)
97 if _, ok := r.Header["Last-Modified"]; !ok {
98 t.Error("Last-Modified header not found.")
102 type recordingTransport struct {
106 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
108 return nil, errors.New("dummy impl")
111 func TestGetRequestFormat(t *testing.T) {
113 tr := &recordingTransport{}
114 client := &Client{Transport: tr}
115 url := "http://dummy.faketld/"
116 client.Get(url) // Note: doesn't hit network
117 if tr.req.Method != "GET" {
118 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
120 if tr.req.URL.String() != url {
121 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
123 if tr.req.Header == nil {
124 t.Errorf("expected non-nil request Header")
128 func TestPostRequestFormat(t *testing.T) {
130 tr := &recordingTransport{}
131 client := &Client{Transport: tr}
133 url := "http://dummy.faketld/"
134 json := `{"key":"value"}`
135 b := strings.NewReader(json)
136 client.Post(url, "application/json", b) // Note: doesn't hit network
138 if tr.req.Method != "POST" {
139 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
141 if tr.req.URL.String() != url {
142 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
144 if tr.req.Header == nil {
145 t.Fatalf("expected non-nil request Header")
148 t.Error("got Close true, want false")
150 if g, e := tr.req.ContentLength, int64(len(json)); g != e {
151 t.Errorf("got ContentLength %d, want %d", g, e)
155 func TestPostFormRequestFormat(t *testing.T) {
157 tr := &recordingTransport{}
158 client := &Client{Transport: tr}
160 urlStr := "http://dummy.faketld/"
161 form := make(url.Values)
162 form.Set("foo", "bar")
163 form.Add("foo", "bar2")
164 form.Set("bar", "baz")
165 client.PostForm(urlStr, form) // Note: doesn't hit network
167 if tr.req.Method != "POST" {
168 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
170 if tr.req.URL.String() != urlStr {
171 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
173 if tr.req.Header == nil {
174 t.Fatalf("expected non-nil request Header")
176 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
177 t.Errorf("got Content-Type %q, want %q", g, e)
180 t.Error("got Close true, want false")
182 // Depending on map iteration, body can be either of these.
183 expectedBody := "foo=bar&foo=bar2&bar=baz"
184 expectedBody1 := "bar=baz&foo=bar&foo=bar2"
185 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
186 t.Errorf("got ContentLength %d, want %d", g, e)
188 bodyb, err := ioutil.ReadAll(tr.req.Body)
190 t.Fatalf("ReadAll on req.Body: %v", err)
192 if g := string(bodyb); g != expectedBody && g != expectedBody1 {
193 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
197 func TestClientRedirects(t *testing.T) {
199 var ts *httptest.Server
200 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
201 n, _ := strconv.Atoi(r.FormValue("n"))
202 // Test Referer header. (7 is arbitrary position to test at)
204 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
205 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
209 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusFound)
212 fmt.Fprintf(w, "n=%d", n)
217 _, err := c.Get(ts.URL)
218 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
219 t.Errorf("with default client Get, expected error %q, got %q", e, g)
222 // HEAD request should also have the ability to follow redirects.
223 _, err = c.Head(ts.URL)
224 if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
225 t.Errorf("with default client Head, expected error %q, got %q", e, g)
228 // Do should also follow redirects.
229 greq, _ := NewRequest("GET", ts.URL, nil)
231 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
232 t.Errorf("with default client Do, expected error %q, got %q", e, g)
235 // Requests with an empty Method should also redirect (Issue 12705)
238 if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
239 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
243 var lastVia []*Request
245 c = &Client{CheckRedirect: func(req *Request, via []*Request) error {
250 res, err := c.Get(ts.URL)
252 t.Fatalf("Get error: %v", err)
255 finalUrl := res.Request.URL.String()
256 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
257 t.Errorf("with custom client, expected error %q, got %q", e, g)
259 if !strings.HasSuffix(finalUrl, "/?n=15") {
260 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
262 if e, g := 15, len(lastVia); e != g {
263 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
266 // Test that Request.Cancel is propagated between requests (Issue 14053)
267 creq, _ := NewRequest("HEAD", ts.URL, nil)
268 cancel := make(chan struct{})
270 if _, err := c.Do(creq); err != nil {
274 t.Fatal("didn't see redirect")
276 if lastReq.Cancel != cancel {
277 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
280 checkErr = errors.New("no redirects allowed")
281 res, err = c.Get(ts.URL)
282 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
283 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
286 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
289 if res.Header.Get("Location") == "" {
290 t.Errorf("no Location header in Response")
294 func TestClientRedirectContext(t *testing.T) {
296 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
297 Redirect(w, r, "/", StatusFound)
301 ctx, cancel := context.WithCancel(context.Background())
302 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
305 return errors.New("too many redirects")
309 req, _ := NewRequest("GET", ts.URL, nil)
310 req = req.WithContext(ctx)
312 ue, ok := err.(*url.Error)
314 t.Fatalf("got error %T; want *url.Error", err)
316 if ue.Err != context.Canceled {
317 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
321 func TestPostRedirects(t *testing.T) {
327 var ts *httptest.Server
328 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
330 fmt.Fprintf(&log.Buffer, "%s %s ", r.Method, r.RequestURI)
332 if v := r.URL.Query().Get("code"); v != "" {
333 code, _ := strconv.Atoi(v)
335 w.Header().Set("Location", ts.URL)
343 want int // response code
351 for _, tt := range tests {
352 res, err := Post(ts.URL+tt.suffix, "text/plain", strings.NewReader("Some content"))
356 if res.StatusCode != tt.want {
357 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
363 want := "POST / POST /?code=301 POST /?code=302 GET / POST /?code=303 GET / POST /?code=404 "
365 t.Errorf("Log differs.\n Got: %q\nWant: %q", got, want)
369 func TestClientRedirectUseResponse(t *testing.T) {
371 const body = "Hello, world."
372 var ts *httptest.Server
373 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
374 if strings.Contains(r.URL.Path, "/other") {
375 io.WriteString(w, "wrong body")
377 w.Header().Set("Location", ts.URL+"/other")
378 w.WriteHeader(StatusFound)
379 io.WriteString(w, body)
384 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
385 if req.Response == nil {
386 t.Error("expected non-nil Request.Response")
388 return ErrUseLastResponse
390 res, err := c.Get(ts.URL)
394 if res.StatusCode != StatusFound {
395 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
397 defer res.Body.Close()
398 slurp, err := ioutil.ReadAll(res.Body)
402 if string(slurp) != body {
403 t.Errorf("body = %q; want %q", slurp, body)
407 var expectedCookies = []*Cookie{
408 {Name: "ChocolateChip", Value: "tasty"},
409 {Name: "First", Value: "Hit"},
410 {Name: "Second", Value: "Hit"},
413 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
414 for _, cookie := range r.Cookies() {
417 if r.URL.Path == "/" {
418 SetCookie(w, expectedCookies[1])
419 Redirect(w, r, "/second", StatusMovedPermanently)
421 SetCookie(w, expectedCookies[2])
422 w.Write([]byte("hello"))
426 func TestClientSendsCookieFromJar(t *testing.T) {
428 tr := &recordingTransport{}
429 client := &Client{Transport: tr}
430 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
431 us := "http://dummy.faketld/"
432 u, _ := url.Parse(us)
433 client.Jar.SetCookies(u, expectedCookies)
435 client.Get(us) // Note: doesn't hit network
436 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
438 client.Head(us) // Note: doesn't hit network
439 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
441 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
442 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
444 client.PostForm(us, url.Values{}) // Note: doesn't hit network
445 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
447 req, _ := NewRequest("GET", us, nil)
448 client.Do(req) // Note: doesn't hit network
449 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
451 req, _ = NewRequest("POST", us, nil)
452 client.Do(req) // Note: doesn't hit network
453 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
456 // Just enough correctness for our redirect tests. Uses the URL.Host as the
457 // scope of all cookies.
458 type TestJar struct {
460 perURL map[string][]*Cookie
463 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
467 j.perURL = make(map[string][]*Cookie)
469 j.perURL[u.Host] = cookies
472 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
475 return j.perURL[u.Host]
478 func TestRedirectCookiesJar(t *testing.T) {
480 var ts *httptest.Server
481 ts = httptest.NewServer(echoCookiesRedirectHandler)
486 u, _ := url.Parse(ts.URL)
487 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
488 resp, err := c.Get(ts.URL)
490 t.Fatalf("Get: %v", err)
493 matchReturnedCookies(t, expectedCookies, resp.Cookies())
496 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
497 if len(given) != len(expected) {
498 t.Logf("Received cookies: %v", given)
499 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
501 for _, ec := range expected {
503 for _, c := range given {
504 if ec.Name == c.Name && ec.Value == c.Value {
510 t.Errorf("Missing cookie %v", ec)
515 func TestJarCalls(t *testing.T) {
517 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
518 pathSuffix := r.RequestURI[1:]
519 if r.RequestURI == "/nosetcookie" {
520 return // don't set cookies for this path
522 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
523 if r.RequestURI == "/" {
524 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
528 jar := new(RecordingJar)
531 Transport: &Transport{
532 Dial: func(_ string, _ string) (net.Conn, error) {
533 return net.Dial("tcp", ts.Listener.Addr().String())
537 _, err := c.Get("http://firsthost.fake/")
541 _, err = c.Get("http://firsthost.fake/nosetcookie")
545 got := jar.log.String()
546 want := `Cookies("http://firsthost.fake/")
547 SetCookie("http://firsthost.fake/", [name=val])
548 Cookies("http://secondhost.fake/secondpath")
549 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
550 Cookies("http://firsthost.fake/nosetcookie")
553 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
557 // RecordingJar keeps a log of calls made to it, without
558 // tracking any cookies.
559 type RecordingJar struct {
564 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
565 j.logf("SetCookie(%q, %v)\n", u, cookies)
568 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
569 j.logf("Cookies(%q)\n", u)
573 func (j *RecordingJar) logf(format string, args ...interface{}) {
576 fmt.Fprintf(&j.log, format, args...)
579 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
580 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
582 func testStreamingGet(t *testing.T, h2 bool) {
584 say := make(chan string)
585 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
587 for str := range say {
595 res, err := c.Get(cst.ts.URL)
600 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
602 n, err := io.ReadFull(res.Body, buf[0:len(str)])
604 t.Fatalf("ReadFull on %q: %v", str, err)
607 t.Fatalf("Receiving %q, only read %d bytes", str, n)
609 got := string(buf[0:n])
611 t.Fatalf("Expected %q, got %q", str, got)
615 _, err = io.ReadFull(res.Body, buf[0:1])
617 t.Fatalf("at end expected EOF, got %v", err)
621 type writeCountingConn struct {
626 func (c *writeCountingConn) Write(p []byte) (int, error) {
628 return c.Conn.Write(p)
631 // TestClientWrites verifies that client requests are buffered and we
632 // don't send a TCP packet per line of the http request + body.
633 func TestClientWrites(t *testing.T) {
635 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
640 dialer := func(netz string, addr string) (net.Conn, error) {
641 c, err := net.Dial(netz, addr)
643 c = &writeCountingConn{c, &writes}
647 c := &Client{Transport: &Transport{Dial: dialer}}
649 _, err := c.Get(ts.URL)
654 t.Errorf("Get request did %d Write calls, want 1", writes)
658 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
663 t.Errorf("Post request did %d Write calls, want 1", writes)
667 func TestClientInsecureTransport(t *testing.T) {
669 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
670 w.Write([]byte("Hello"))
672 errc := make(chanWriter, 10) // but only expecting 1
673 ts.Config.ErrorLog = log.New(errc, "", 0)
676 // TODO(bradfitz): add tests for skipping hostname checks too?
677 // would require a new cert for testing, and probably
678 // redundant with these tests.
679 for _, insecure := range []bool{true, false} {
681 TLSClientConfig: &tls.Config{
682 InsecureSkipVerify: insecure,
685 defer tr.CloseIdleConnections()
686 c := &Client{Transport: tr}
687 res, err := c.Get(ts.URL)
688 if (err == nil) != insecure {
689 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
698 if !strings.Contains(v, "TLS handshake error") {
699 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
701 case <-time.After(5 * time.Second):
702 t.Errorf("timeout waiting for logged error")
707 func TestClientErrorWithRequestURI(t *testing.T) {
709 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
710 req.RequestURI = "/this/field/is/illegal/and/should/error/"
711 _, err := DefaultClient.Do(req)
713 t.Fatalf("expected an error")
715 if !strings.Contains(err.Error(), "RequestURI") {
716 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
720 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
721 certs := x509.NewCertPool()
722 for _, c := range ts.TLS.Certificates {
723 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
725 t.Fatalf("error parsing server's root cert: %v", err)
727 for _, root := range roots {
732 TLSClientConfig: &tls.Config{RootCAs: certs},
736 func TestClientWithCorrectTLSServerName(t *testing.T) {
739 const serverName = "example.com"
740 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
741 if r.TLS.ServerName != serverName {
742 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
747 trans := newTLSTransport(t, ts)
748 trans.TLSClientConfig.ServerName = serverName
749 c := &Client{Transport: trans}
750 if _, err := c.Get(ts.URL); err != nil {
751 t.Fatalf("expected successful TLS connection, got error: %v", err)
755 func TestClientWithIncorrectTLSServerName(t *testing.T) {
757 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
759 errc := make(chanWriter, 10) // but only expecting 1
760 ts.Config.ErrorLog = log.New(errc, "", 0)
762 trans := newTLSTransport(t, ts)
763 trans.TLSClientConfig.ServerName = "badserver"
764 c := &Client{Transport: trans}
765 _, err := c.Get(ts.URL)
767 t.Fatalf("expected an error")
769 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
770 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
774 if !strings.Contains(v, "TLS handshake error") {
775 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
777 case <-time.After(5 * time.Second):
778 t.Errorf("timeout waiting for logged error")
782 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
785 // tls.Config.ServerName (non-empty, set to "example.com") takes
786 // precedence over "some-other-host.tld" which previously incorrectly
787 // took precedence. We don't actually connect to (or even resolve)
788 // "some-other-host.tld", though, because of the Transport.Dial hook.
790 // The httptest.Server has a cert with "example.com" as its name.
791 func TestTransportUsesTLSConfigServerName(t *testing.T) {
793 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
794 w.Write([]byte("Hello"))
798 tr := newTLSTransport(t, ts)
799 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
800 tr.Dial = func(netw, addr string) (net.Conn, error) {
801 return net.Dial(netw, ts.Listener.Addr().String())
803 defer tr.CloseIdleConnections()
804 c := &Client{Transport: tr}
805 res, err := c.Get("https://some-other-host.tld/")
812 func TestResponseSetsTLSConnectionState(t *testing.T) {
814 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
815 w.Write([]byte("Hello"))
819 tr := newTLSTransport(t, ts)
820 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
821 tr.Dial = func(netw, addr string) (net.Conn, error) {
822 return net.Dial(netw, ts.Listener.Addr().String())
824 defer tr.CloseIdleConnections()
825 c := &Client{Transport: tr}
826 res, err := c.Get("https://example.com/")
830 defer res.Body.Close()
832 t.Fatal("Response didn't set TLS Connection State.")
834 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
835 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
839 // Check that an HTTPS client can interpret a particular TLS error
840 // to determine that the server is speaking HTTP.
841 // See golang.org/issue/11111.
842 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
844 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
847 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
848 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
849 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
853 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
854 func TestClientHeadContentLength_h1(t *testing.T) {
855 testClientHeadContentLength(t, h1Mode)
858 func TestClientHeadContentLength_h2(t *testing.T) {
859 testClientHeadContentLength(t, h2Mode)
862 func testClientHeadContentLength(t *testing.T, h2 bool) {
864 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
865 if v := r.FormValue("cl"); v != "" {
866 w.Header().Set("Content-Length", v)
878 for _, tt := range tests {
879 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
880 res, err := cst.c.Do(req)
884 if res.ContentLength != tt.want {
885 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
887 bs, err := ioutil.ReadAll(res.Body)
892 t.Errorf("Unexpected content: %q", bs)
897 func TestEmptyPasswordAuth(t *testing.T) {
900 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
901 auth := r.Header.Get("Authorization")
902 if strings.HasPrefix(auth, "Basic ") {
904 decoded, err := base64.StdEncoding.DecodeString(encoded)
908 expected := gopher + ":"
911 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
914 t.Errorf("Invalid auth %q", auth)
919 req, err := NewRequest("GET", ts.URL, nil)
923 req.URL.User = url.User(gopher)
924 resp, err := c.Do(req)
928 defer resp.Body.Close()
931 func TestBasicAuth(t *testing.T) {
933 tr := &recordingTransport{}
934 client := &Client{Transport: tr}
936 url := "http://My%20User:My%20Pass@dummy.faketld/"
937 expected := "My User:My Pass"
940 if tr.req.Method != "GET" {
941 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
943 if tr.req.URL.String() != url {
944 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
946 if tr.req.Header == nil {
947 t.Fatalf("expected non-nil request Header")
949 auth := tr.req.Header.Get("Authorization")
950 if strings.HasPrefix(auth, "Basic ") {
952 decoded, err := base64.StdEncoding.DecodeString(encoded)
958 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
961 t.Errorf("Invalid auth %q", auth)
965 func TestBasicAuthHeadersPreserved(t *testing.T) {
967 tr := &recordingTransport{}
968 client := &Client{Transport: tr}
970 // If Authorization header is provided, username in URL should not override it
971 url := "http://My%20User@dummy.faketld/"
972 req, err := NewRequest("GET", url, nil)
976 req.SetBasicAuth("My User", "My Pass")
977 expected := "My User:My Pass"
980 if tr.req.Method != "GET" {
981 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
983 if tr.req.URL.String() != url {
984 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
986 if tr.req.Header == nil {
987 t.Fatalf("expected non-nil request Header")
989 auth := tr.req.Header.Get("Authorization")
990 if strings.HasPrefix(auth, "Basic ") {
992 decoded, err := base64.StdEncoding.DecodeString(encoded)
998 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1001 t.Errorf("Invalid auth %q", auth)
1006 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1007 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1009 func testClientTimeout(t *testing.T, h2 bool) {
1010 if testing.Short() {
1011 t.Skip("skipping in short mode")
1014 sawRoot := make(chan bool, 1)
1015 sawSlow := make(chan bool, 1)
1016 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1017 if r.URL.Path == "/" {
1019 Redirect(w, r, "/slow", StatusFound)
1022 if r.URL.Path == "/slow" {
1023 w.Write([]byte("Hello"))
1026 time.Sleep(2 * time.Second)
1031 const timeout = 500 * time.Millisecond
1032 cst.c.Timeout = timeout
1034 res, err := cst.c.Get(cst.ts.URL)
1043 t.Fatal("handler never got / request")
1050 t.Fatal("handler never got /slow request")
1053 errc := make(chan error, 1)
1055 _, err := ioutil.ReadAll(res.Body)
1060 const failTime = timeout * 2
1064 t.Fatal("expected error from ReadAll")
1066 ne, ok := err.(net.Error)
1068 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1069 } else if !ne.Timeout() {
1070 t.Errorf("net.Error.Timeout = false; want true")
1072 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1073 t.Errorf("error string = %q; missing timeout substring", got)
1075 case <-time.After(failTime):
1076 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1080 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1081 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1083 // Client.Timeout firing before getting to the body
1084 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1085 if testing.Short() {
1086 t.Skip("skipping in short mode")
1089 donec := make(chan bool)
1090 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1094 // Note that we use a channel send here and not a close.
1095 // The race detector doesn't know that we're waiting for a timeout
1096 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1097 // with us closing it. If we timed out immediately, we could close the testserver
1098 // before we entered the handler. We're not timing out immediately and there's
1099 // no way we would be done before we entered the handler, but the race detector
1100 // doesn't know this, so synchronize explicitly.
1101 defer func() { donec <- true }()
1103 cst.c.Timeout = 500 * time.Millisecond
1104 _, err := cst.c.Get(cst.ts.URL)
1106 t.Fatal("got response from Get; expected error")
1108 if _, ok := err.(*url.Error); !ok {
1109 t.Fatalf("Got error of type %T; want *url.Error", err)
1111 ne, ok := err.(net.Error)
1113 t.Fatalf("Got error of type %T; want some net.Error", err)
1116 t.Error("net.Error.Timeout = false; want true")
1118 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1119 t.Errorf("error string = %q; missing timeout substring", got)
1123 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1124 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1125 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1127 saw := make(chan string, 2)
1128 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1130 if r.URL.Path == "/" {
1131 Redirect(w, r, "/foo", StatusFound) // which includes a body
1136 res, err := cst.c.Get(cst.ts.URL)
1140 _, err = ioutil.ReadAll(res.Body)
1150 t.Fatal("server didn't see a request")
1155 case second = <-saw:
1157 t.Fatal("server didn't see a second request")
1160 if first != second {
1161 t.Fatal("server saw different client ports before & after the redirect")
1165 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1166 type eofReaderFunc func()
1168 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1173 func TestReferer(t *testing.T) {
1175 lastReq, newReq string // from -> to URLs
1179 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1180 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1182 // don't send a user and password:
1183 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1184 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1187 {"http://test.com", "http://link.com", "http://test.com"},
1188 {"https://test.com", "https://link.com", "https://test.com"},
1190 // https to http doesn't send a referer:
1191 {"https://test.com", "http://link.com", ""},
1192 {"https://gopher:go@test.com", "http://link.com", ""},
1194 for _, tt := range tests {
1195 l, err := url.Parse(tt.lastReq)
1199 n, err := url.Parse(tt.newReq)
1203 r := ExportRefererForURL(l, n)
1205 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1210 // issue15577Tripper returns a Response with a redirect response
1211 // header and doesn't populate its Response.Request field.
1212 type issue15577Tripper struct{}
1214 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1217 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1218 Body: ioutil.NopCloser(strings.NewReader("")),
1223 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1224 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1226 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1227 Transport: issue15577Tripper{},
1229 // Check that this doesn't crash:
1230 c.Get("http://dummy.tld")