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 != ExportErrRequestCanceled && ue.Err != ExportErrRequestCanceledConn {
317 t.Errorf("url.Error.Err = %v; want errRequestCanceled or errRequestCanceledConn", ue.Err)
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 var expectedCookies = []*Cookie{
370 {Name: "ChocolateChip", Value: "tasty"},
371 {Name: "First", Value: "Hit"},
372 {Name: "Second", Value: "Hit"},
375 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
376 for _, cookie := range r.Cookies() {
379 if r.URL.Path == "/" {
380 SetCookie(w, expectedCookies[1])
381 Redirect(w, r, "/second", StatusMovedPermanently)
383 SetCookie(w, expectedCookies[2])
384 w.Write([]byte("hello"))
388 func TestClientSendsCookieFromJar(t *testing.T) {
390 tr := &recordingTransport{}
391 client := &Client{Transport: tr}
392 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
393 us := "http://dummy.faketld/"
394 u, _ := url.Parse(us)
395 client.Jar.SetCookies(u, expectedCookies)
397 client.Get(us) // Note: doesn't hit network
398 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
400 client.Head(us) // Note: doesn't hit network
401 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
403 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
404 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
406 client.PostForm(us, url.Values{}) // Note: doesn't hit network
407 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
409 req, _ := NewRequest("GET", us, nil)
410 client.Do(req) // Note: doesn't hit network
411 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
413 req, _ = NewRequest("POST", us, nil)
414 client.Do(req) // Note: doesn't hit network
415 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
418 // Just enough correctness for our redirect tests. Uses the URL.Host as the
419 // scope of all cookies.
420 type TestJar struct {
422 perURL map[string][]*Cookie
425 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
429 j.perURL = make(map[string][]*Cookie)
431 j.perURL[u.Host] = cookies
434 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
437 return j.perURL[u.Host]
440 func TestRedirectCookiesJar(t *testing.T) {
442 var ts *httptest.Server
443 ts = httptest.NewServer(echoCookiesRedirectHandler)
448 u, _ := url.Parse(ts.URL)
449 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
450 resp, err := c.Get(ts.URL)
452 t.Fatalf("Get: %v", err)
455 matchReturnedCookies(t, expectedCookies, resp.Cookies())
458 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
459 if len(given) != len(expected) {
460 t.Logf("Received cookies: %v", given)
461 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
463 for _, ec := range expected {
465 for _, c := range given {
466 if ec.Name == c.Name && ec.Value == c.Value {
472 t.Errorf("Missing cookie %v", ec)
477 func TestJarCalls(t *testing.T) {
479 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
480 pathSuffix := r.RequestURI[1:]
481 if r.RequestURI == "/nosetcookie" {
482 return // don't set cookies for this path
484 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
485 if r.RequestURI == "/" {
486 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
490 jar := new(RecordingJar)
493 Transport: &Transport{
494 Dial: func(_ string, _ string) (net.Conn, error) {
495 return net.Dial("tcp", ts.Listener.Addr().String())
499 _, err := c.Get("http://firsthost.fake/")
503 _, err = c.Get("http://firsthost.fake/nosetcookie")
507 got := jar.log.String()
508 want := `Cookies("http://firsthost.fake/")
509 SetCookie("http://firsthost.fake/", [name=val])
510 Cookies("http://secondhost.fake/secondpath")
511 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
512 Cookies("http://firsthost.fake/nosetcookie")
515 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
519 // RecordingJar keeps a log of calls made to it, without
520 // tracking any cookies.
521 type RecordingJar struct {
526 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
527 j.logf("SetCookie(%q, %v)\n", u, cookies)
530 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
531 j.logf("Cookies(%q)\n", u)
535 func (j *RecordingJar) logf(format string, args ...interface{}) {
538 fmt.Fprintf(&j.log, format, args...)
541 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
542 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
544 func testStreamingGet(t *testing.T, h2 bool) {
546 say := make(chan string)
547 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
549 for str := range say {
557 res, err := c.Get(cst.ts.URL)
562 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
564 n, err := io.ReadFull(res.Body, buf[0:len(str)])
566 t.Fatalf("ReadFull on %q: %v", str, err)
569 t.Fatalf("Receiving %q, only read %d bytes", str, n)
571 got := string(buf[0:n])
573 t.Fatalf("Expected %q, got %q", str, got)
577 _, err = io.ReadFull(res.Body, buf[0:1])
579 t.Fatalf("at end expected EOF, got %v", err)
583 type writeCountingConn struct {
588 func (c *writeCountingConn) Write(p []byte) (int, error) {
590 return c.Conn.Write(p)
593 // TestClientWrites verifies that client requests are buffered and we
594 // don't send a TCP packet per line of the http request + body.
595 func TestClientWrites(t *testing.T) {
597 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
602 dialer := func(netz string, addr string) (net.Conn, error) {
603 c, err := net.Dial(netz, addr)
605 c = &writeCountingConn{c, &writes}
609 c := &Client{Transport: &Transport{Dial: dialer}}
611 _, err := c.Get(ts.URL)
616 t.Errorf("Get request did %d Write calls, want 1", writes)
620 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
625 t.Errorf("Post request did %d Write calls, want 1", writes)
629 func TestClientInsecureTransport(t *testing.T) {
631 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
632 w.Write([]byte("Hello"))
634 errc := make(chanWriter, 10) // but only expecting 1
635 ts.Config.ErrorLog = log.New(errc, "", 0)
638 // TODO(bradfitz): add tests for skipping hostname checks too?
639 // would require a new cert for testing, and probably
640 // redundant with these tests.
641 for _, insecure := range []bool{true, false} {
643 TLSClientConfig: &tls.Config{
644 InsecureSkipVerify: insecure,
647 defer tr.CloseIdleConnections()
648 c := &Client{Transport: tr}
649 res, err := c.Get(ts.URL)
650 if (err == nil) != insecure {
651 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
660 if !strings.Contains(v, "TLS handshake error") {
661 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
663 case <-time.After(5 * time.Second):
664 t.Errorf("timeout waiting for logged error")
669 func TestClientErrorWithRequestURI(t *testing.T) {
671 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
672 req.RequestURI = "/this/field/is/illegal/and/should/error/"
673 _, err := DefaultClient.Do(req)
675 t.Fatalf("expected an error")
677 if !strings.Contains(err.Error(), "RequestURI") {
678 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
682 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
683 certs := x509.NewCertPool()
684 for _, c := range ts.TLS.Certificates {
685 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
687 t.Fatalf("error parsing server's root cert: %v", err)
689 for _, root := range roots {
694 TLSClientConfig: &tls.Config{RootCAs: certs},
698 func TestClientWithCorrectTLSServerName(t *testing.T) {
701 const serverName = "example.com"
702 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
703 if r.TLS.ServerName != serverName {
704 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
709 trans := newTLSTransport(t, ts)
710 trans.TLSClientConfig.ServerName = serverName
711 c := &Client{Transport: trans}
712 if _, err := c.Get(ts.URL); err != nil {
713 t.Fatalf("expected successful TLS connection, got error: %v", err)
717 func TestClientWithIncorrectTLSServerName(t *testing.T) {
719 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
721 errc := make(chanWriter, 10) // but only expecting 1
722 ts.Config.ErrorLog = log.New(errc, "", 0)
724 trans := newTLSTransport(t, ts)
725 trans.TLSClientConfig.ServerName = "badserver"
726 c := &Client{Transport: trans}
727 _, err := c.Get(ts.URL)
729 t.Fatalf("expected an error")
731 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
732 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
736 if !strings.Contains(v, "TLS handshake error") {
737 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
739 case <-time.After(5 * time.Second):
740 t.Errorf("timeout waiting for logged error")
744 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
747 // tls.Config.ServerName (non-empty, set to "example.com") takes
748 // precedence over "some-other-host.tld" which previously incorrectly
749 // took precedence. We don't actually connect to (or even resolve)
750 // "some-other-host.tld", though, because of the Transport.Dial hook.
752 // The httptest.Server has a cert with "example.com" as its name.
753 func TestTransportUsesTLSConfigServerName(t *testing.T) {
755 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
756 w.Write([]byte("Hello"))
760 tr := newTLSTransport(t, ts)
761 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
762 tr.Dial = func(netw, addr string) (net.Conn, error) {
763 return net.Dial(netw, ts.Listener.Addr().String())
765 defer tr.CloseIdleConnections()
766 c := &Client{Transport: tr}
767 res, err := c.Get("https://some-other-host.tld/")
774 func TestResponseSetsTLSConnectionState(t *testing.T) {
776 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
777 w.Write([]byte("Hello"))
781 tr := newTLSTransport(t, ts)
782 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
783 tr.Dial = func(netw, addr string) (net.Conn, error) {
784 return net.Dial(netw, ts.Listener.Addr().String())
786 defer tr.CloseIdleConnections()
787 c := &Client{Transport: tr}
788 res, err := c.Get("https://example.com/")
792 defer res.Body.Close()
794 t.Fatal("Response didn't set TLS Connection State.")
796 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
797 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
801 // Check that an HTTPS client can interpret a particular TLS error
802 // to determine that the server is speaking HTTP.
803 // See golang.org/issue/11111.
804 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
806 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
809 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
810 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
811 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
815 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
816 func TestClientHeadContentLength_h1(t *testing.T) {
817 testClientHeadContentLength(t, h1Mode)
820 func TestClientHeadContentLength_h2(t *testing.T) {
821 testClientHeadContentLength(t, h2Mode)
824 func testClientHeadContentLength(t *testing.T, h2 bool) {
826 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
827 if v := r.FormValue("cl"); v != "" {
828 w.Header().Set("Content-Length", v)
840 for _, tt := range tests {
841 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
842 res, err := cst.c.Do(req)
846 if res.ContentLength != tt.want {
847 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
849 bs, err := ioutil.ReadAll(res.Body)
854 t.Errorf("Unexpected content: %q", bs)
859 func TestEmptyPasswordAuth(t *testing.T) {
862 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
863 auth := r.Header.Get("Authorization")
864 if strings.HasPrefix(auth, "Basic ") {
866 decoded, err := base64.StdEncoding.DecodeString(encoded)
870 expected := gopher + ":"
873 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
876 t.Errorf("Invalid auth %q", auth)
881 req, err := NewRequest("GET", ts.URL, nil)
885 req.URL.User = url.User(gopher)
886 resp, err := c.Do(req)
890 defer resp.Body.Close()
893 func TestBasicAuth(t *testing.T) {
895 tr := &recordingTransport{}
896 client := &Client{Transport: tr}
898 url := "http://My%20User:My%20Pass@dummy.faketld/"
899 expected := "My User:My Pass"
902 if tr.req.Method != "GET" {
903 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
905 if tr.req.URL.String() != url {
906 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
908 if tr.req.Header == nil {
909 t.Fatalf("expected non-nil request Header")
911 auth := tr.req.Header.Get("Authorization")
912 if strings.HasPrefix(auth, "Basic ") {
914 decoded, err := base64.StdEncoding.DecodeString(encoded)
920 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
923 t.Errorf("Invalid auth %q", auth)
927 func TestBasicAuthHeadersPreserved(t *testing.T) {
929 tr := &recordingTransport{}
930 client := &Client{Transport: tr}
932 // If Authorization header is provided, username in URL should not override it
933 url := "http://My%20User@dummy.faketld/"
934 req, err := NewRequest("GET", url, nil)
938 req.SetBasicAuth("My User", "My Pass")
939 expected := "My User:My Pass"
942 if tr.req.Method != "GET" {
943 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
945 if tr.req.URL.String() != url {
946 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
948 if tr.req.Header == nil {
949 t.Fatalf("expected non-nil request Header")
951 auth := tr.req.Header.Get("Authorization")
952 if strings.HasPrefix(auth, "Basic ") {
954 decoded, err := base64.StdEncoding.DecodeString(encoded)
960 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
963 t.Errorf("Invalid auth %q", auth)
968 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
969 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
971 func testClientTimeout(t *testing.T, h2 bool) {
973 t.Skip("skipping in short mode")
976 sawRoot := make(chan bool, 1)
977 sawSlow := make(chan bool, 1)
978 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
979 if r.URL.Path == "/" {
981 Redirect(w, r, "/slow", StatusFound)
984 if r.URL.Path == "/slow" {
985 w.Write([]byte("Hello"))
988 time.Sleep(2 * time.Second)
993 const timeout = 500 * time.Millisecond
994 cst.c.Timeout = timeout
996 res, err := cst.c.Get(cst.ts.URL)
1005 t.Fatal("handler never got / request")
1012 t.Fatal("handler never got /slow request")
1015 errc := make(chan error, 1)
1017 _, err := ioutil.ReadAll(res.Body)
1022 const failTime = timeout * 2
1026 t.Fatal("expected error from ReadAll")
1028 ne, ok := err.(net.Error)
1030 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1031 } else if !ne.Timeout() {
1032 t.Errorf("net.Error.Timeout = false; want true")
1034 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1035 t.Errorf("error string = %q; missing timeout substring", got)
1037 case <-time.After(failTime):
1038 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1042 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1043 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1045 // Client.Timeout firing before getting to the body
1046 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1047 if testing.Short() {
1048 t.Skip("skipping in short mode")
1051 donec := make(chan bool)
1052 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1056 // Note that we use a channel send here and not a close.
1057 // The race detector doesn't know that we're waiting for a timeout
1058 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1059 // with us closing it. If we timed out immediately, we could close the testserver
1060 // before we entered the handler. We're not timing out immediately and there's
1061 // no way we would be done before we entered the handler, but the race detector
1062 // doesn't know this, so synchronize explicitly.
1063 defer func() { donec <- true }()
1065 cst.c.Timeout = 500 * time.Millisecond
1066 _, err := cst.c.Get(cst.ts.URL)
1068 t.Fatal("got response from Get; expected error")
1070 if _, ok := err.(*url.Error); !ok {
1071 t.Fatalf("Got error of type %T; want *url.Error", err)
1073 ne, ok := err.(net.Error)
1075 t.Fatalf("Got error of type %T; want some net.Error", err)
1078 t.Error("net.Error.Timeout = false; want true")
1080 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1081 t.Errorf("error string = %q; missing timeout substring", got)
1085 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1086 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1087 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1089 saw := make(chan string, 2)
1090 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1092 if r.URL.Path == "/" {
1093 Redirect(w, r, "/foo", StatusFound) // which includes a body
1098 res, err := cst.c.Get(cst.ts.URL)
1102 _, err = ioutil.ReadAll(res.Body)
1112 t.Fatal("server didn't see a request")
1117 case second = <-saw:
1119 t.Fatal("server didn't see a second request")
1122 if first != second {
1123 t.Fatal("server saw different client ports before & after the redirect")
1127 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1128 type eofReaderFunc func()
1130 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1135 func TestReferer(t *testing.T) {
1137 lastReq, newReq string // from -> to URLs
1141 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1142 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1144 // don't send a user and password:
1145 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1146 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1149 {"http://test.com", "http://link.com", "http://test.com"},
1150 {"https://test.com", "https://link.com", "https://test.com"},
1152 // https to http doesn't send a referer:
1153 {"https://test.com", "http://link.com", ""},
1154 {"https://gopher:go@test.com", "http://link.com", ""},
1156 for _, tt := range tests {
1157 l, err := url.Parse(tt.lastReq)
1161 n, err := url.Parse(tt.newReq)
1165 r := ExportRefererForURL(l, n)
1167 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)