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, h1Mode) }
87 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
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
246 c = &Client{CheckRedirect: func(req *Request, via []*Request) error {
251 res, err := c.Get(ts.URL)
253 t.Fatalf("Get error: %v", err)
256 finalUrl := res.Request.URL.String()
257 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
258 t.Errorf("with custom client, expected error %q, got %q", e, g)
260 if !strings.HasSuffix(finalUrl, "/?n=15") {
261 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
263 if e, g := 15, len(lastVia); e != g {
264 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
267 // Test that Request.Cancel is propagated between requests (Issue 14053)
268 creq, _ := NewRequest("HEAD", ts.URL, nil)
269 cancel := make(chan struct{})
271 if _, err := c.Do(creq); err != nil {
275 t.Fatal("didn't see redirect")
277 if lastReq.Cancel != cancel {
278 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
281 checkErr = errors.New("no redirects allowed")
282 res, err = c.Get(ts.URL)
283 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
284 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
287 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
290 if res.Header.Get("Location") == "" {
291 t.Errorf("no Location header in Response")
295 func TestClientRedirectContext(t *testing.T) {
297 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
298 Redirect(w, r, "/", StatusFound)
302 ctx, cancel := context.WithCancel(context.Background())
303 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
306 return errors.New("too many redirects")
310 req, _ := NewRequest("GET", ts.URL, nil)
311 req = req.WithContext(ctx)
313 ue, ok := err.(*url.Error)
315 t.Fatalf("got error %T; want *url.Error", err)
317 if ue.Err != context.Canceled {
318 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
322 func TestPostRedirects(t *testing.T) {
328 var ts *httptest.Server
329 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
331 fmt.Fprintf(&log.Buffer, "%s %s ", r.Method, r.RequestURI)
333 if v := r.URL.Query().Get("code"); v != "" {
334 code, _ := strconv.Atoi(v)
336 w.Header().Set("Location", ts.URL)
344 want int // response code
352 for _, tt := range tests {
353 res, err := Post(ts.URL+tt.suffix, "text/plain", strings.NewReader("Some content"))
357 if res.StatusCode != tt.want {
358 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
364 want := "POST / POST /?code=301 POST /?code=302 GET / POST /?code=303 GET / POST /?code=404 "
366 t.Errorf("Log differs.\n Got: %q\nWant: %q", got, want)
370 func TestClientRedirectUseResponse(t *testing.T) {
372 const body = "Hello, world."
373 var ts *httptest.Server
374 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
375 if strings.Contains(r.URL.Path, "/other") {
376 io.WriteString(w, "wrong body")
378 w.Header().Set("Location", ts.URL+"/other")
379 w.WriteHeader(StatusFound)
380 io.WriteString(w, body)
385 c := &Client{CheckRedirect: func(req *Request, via []*Request) error {
386 if req.Response == nil {
387 t.Error("expected non-nil Request.Response")
389 return ErrUseLastResponse
391 res, err := c.Get(ts.URL)
395 if res.StatusCode != StatusFound {
396 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
398 defer res.Body.Close()
399 slurp, err := ioutil.ReadAll(res.Body)
403 if string(slurp) != body {
404 t.Errorf("body = %q; want %q", slurp, body)
408 var expectedCookies = []*Cookie{
409 {Name: "ChocolateChip", Value: "tasty"},
410 {Name: "First", Value: "Hit"},
411 {Name: "Second", Value: "Hit"},
414 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
415 for _, cookie := range r.Cookies() {
418 if r.URL.Path == "/" {
419 SetCookie(w, expectedCookies[1])
420 Redirect(w, r, "/second", StatusMovedPermanently)
422 SetCookie(w, expectedCookies[2])
423 w.Write([]byte("hello"))
427 func TestClientSendsCookieFromJar(t *testing.T) {
429 tr := &recordingTransport{}
430 client := &Client{Transport: tr}
431 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
432 us := "http://dummy.faketld/"
433 u, _ := url.Parse(us)
434 client.Jar.SetCookies(u, expectedCookies)
436 client.Get(us) // Note: doesn't hit network
437 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
439 client.Head(us) // Note: doesn't hit network
440 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
442 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
443 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
445 client.PostForm(us, url.Values{}) // Note: doesn't hit network
446 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
448 req, _ := NewRequest("GET", us, nil)
449 client.Do(req) // Note: doesn't hit network
450 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
452 req, _ = NewRequest("POST", us, nil)
453 client.Do(req) // Note: doesn't hit network
454 matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
457 // Just enough correctness for our redirect tests. Uses the URL.Host as the
458 // scope of all cookies.
459 type TestJar struct {
461 perURL map[string][]*Cookie
464 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
468 j.perURL = make(map[string][]*Cookie)
470 j.perURL[u.Host] = cookies
473 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
476 return j.perURL[u.Host]
479 func TestRedirectCookiesJar(t *testing.T) {
481 var ts *httptest.Server
482 ts = httptest.NewServer(echoCookiesRedirectHandler)
487 u, _ := url.Parse(ts.URL)
488 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
489 resp, err := c.Get(ts.URL)
491 t.Fatalf("Get: %v", err)
494 matchReturnedCookies(t, expectedCookies, resp.Cookies())
497 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
498 if len(given) != len(expected) {
499 t.Logf("Received cookies: %v", given)
500 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
502 for _, ec := range expected {
504 for _, c := range given {
505 if ec.Name == c.Name && ec.Value == c.Value {
511 t.Errorf("Missing cookie %v", ec)
516 func TestJarCalls(t *testing.T) {
518 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
519 pathSuffix := r.RequestURI[1:]
520 if r.RequestURI == "/nosetcookie" {
521 return // don't set cookies for this path
523 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
524 if r.RequestURI == "/" {
525 Redirect(w, r, "http://secondhost.fake/secondpath", 302)
529 jar := new(RecordingJar)
532 Transport: &Transport{
533 Dial: func(_ string, _ string) (net.Conn, error) {
534 return net.Dial("tcp", ts.Listener.Addr().String())
538 _, err := c.Get("http://firsthost.fake/")
542 _, err = c.Get("http://firsthost.fake/nosetcookie")
546 got := jar.log.String()
547 want := `Cookies("http://firsthost.fake/")
548 SetCookie("http://firsthost.fake/", [name=val])
549 Cookies("http://secondhost.fake/secondpath")
550 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
551 Cookies("http://firsthost.fake/nosetcookie")
554 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
558 // RecordingJar keeps a log of calls made to it, without
559 // tracking any cookies.
560 type RecordingJar struct {
565 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
566 j.logf("SetCookie(%q, %v)\n", u, cookies)
569 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
570 j.logf("Cookies(%q)\n", u)
574 func (j *RecordingJar) logf(format string, args ...interface{}) {
577 fmt.Fprintf(&j.log, format, args...)
580 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
581 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
583 func testStreamingGet(t *testing.T, h2 bool) {
585 say := make(chan string)
586 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
588 for str := range say {
596 res, err := c.Get(cst.ts.URL)
601 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
603 n, err := io.ReadFull(res.Body, buf[0:len(str)])
605 t.Fatalf("ReadFull on %q: %v", str, err)
608 t.Fatalf("Receiving %q, only read %d bytes", str, n)
610 got := string(buf[0:n])
612 t.Fatalf("Expected %q, got %q", str, got)
616 _, err = io.ReadFull(res.Body, buf[0:1])
618 t.Fatalf("at end expected EOF, got %v", err)
622 type writeCountingConn struct {
627 func (c *writeCountingConn) Write(p []byte) (int, error) {
629 return c.Conn.Write(p)
632 // TestClientWrites verifies that client requests are buffered and we
633 // don't send a TCP packet per line of the http request + body.
634 func TestClientWrites(t *testing.T) {
636 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
641 dialer := func(netz string, addr string) (net.Conn, error) {
642 c, err := net.Dial(netz, addr)
644 c = &writeCountingConn{c, &writes}
648 c := &Client{Transport: &Transport{Dial: dialer}}
650 _, err := c.Get(ts.URL)
655 t.Errorf("Get request did %d Write calls, want 1", writes)
659 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
664 t.Errorf("Post request did %d Write calls, want 1", writes)
668 func TestClientInsecureTransport(t *testing.T) {
670 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
671 w.Write([]byte("Hello"))
673 errc := make(chanWriter, 10) // but only expecting 1
674 ts.Config.ErrorLog = log.New(errc, "", 0)
677 // TODO(bradfitz): add tests for skipping hostname checks too?
678 // would require a new cert for testing, and probably
679 // redundant with these tests.
680 for _, insecure := range []bool{true, false} {
682 TLSClientConfig: &tls.Config{
683 InsecureSkipVerify: insecure,
686 defer tr.CloseIdleConnections()
687 c := &Client{Transport: tr}
688 res, err := c.Get(ts.URL)
689 if (err == nil) != insecure {
690 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
699 if !strings.Contains(v, "TLS handshake error") {
700 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
702 case <-time.After(5 * time.Second):
703 t.Errorf("timeout waiting for logged error")
708 func TestClientErrorWithRequestURI(t *testing.T) {
710 req, _ := NewRequest("GET", "http://localhost:1234/", nil)
711 req.RequestURI = "/this/field/is/illegal/and/should/error/"
712 _, err := DefaultClient.Do(req)
714 t.Fatalf("expected an error")
716 if !strings.Contains(err.Error(), "RequestURI") {
717 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
721 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
722 certs := x509.NewCertPool()
723 for _, c := range ts.TLS.Certificates {
724 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
726 t.Fatalf("error parsing server's root cert: %v", err)
728 for _, root := range roots {
733 TLSClientConfig: &tls.Config{RootCAs: certs},
737 func TestClientWithCorrectTLSServerName(t *testing.T) {
740 const serverName = "example.com"
741 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
742 if r.TLS.ServerName != serverName {
743 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
748 trans := newTLSTransport(t, ts)
749 trans.TLSClientConfig.ServerName = serverName
750 c := &Client{Transport: trans}
751 if _, err := c.Get(ts.URL); err != nil {
752 t.Fatalf("expected successful TLS connection, got error: %v", err)
756 func TestClientWithIncorrectTLSServerName(t *testing.T) {
758 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
760 errc := make(chanWriter, 10) // but only expecting 1
761 ts.Config.ErrorLog = log.New(errc, "", 0)
763 trans := newTLSTransport(t, ts)
764 trans.TLSClientConfig.ServerName = "badserver"
765 c := &Client{Transport: trans}
766 _, err := c.Get(ts.URL)
768 t.Fatalf("expected an error")
770 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
771 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
775 if !strings.Contains(v, "TLS handshake error") {
776 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
778 case <-time.After(5 * time.Second):
779 t.Errorf("timeout waiting for logged error")
783 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
786 // tls.Config.ServerName (non-empty, set to "example.com") takes
787 // precedence over "some-other-host.tld" which previously incorrectly
788 // took precedence. We don't actually connect to (or even resolve)
789 // "some-other-host.tld", though, because of the Transport.Dial hook.
791 // The httptest.Server has a cert with "example.com" as its name.
792 func TestTransportUsesTLSConfigServerName(t *testing.T) {
794 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
795 w.Write([]byte("Hello"))
799 tr := newTLSTransport(t, ts)
800 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
801 tr.Dial = func(netw, addr string) (net.Conn, error) {
802 return net.Dial(netw, ts.Listener.Addr().String())
804 defer tr.CloseIdleConnections()
805 c := &Client{Transport: tr}
806 res, err := c.Get("https://some-other-host.tld/")
813 func TestResponseSetsTLSConnectionState(t *testing.T) {
815 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
816 w.Write([]byte("Hello"))
820 tr := newTLSTransport(t, ts)
821 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
822 tr.Dial = func(netw, addr string) (net.Conn, error) {
823 return net.Dial(netw, ts.Listener.Addr().String())
825 defer tr.CloseIdleConnections()
826 c := &Client{Transport: tr}
827 res, err := c.Get("https://example.com/")
831 defer res.Body.Close()
833 t.Fatal("Response didn't set TLS Connection State.")
835 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
836 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
840 // Check that an HTTPS client can interpret a particular TLS error
841 // to determine that the server is speaking HTTP.
842 // See golang.org/issue/11111.
843 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
845 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
848 _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
849 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
850 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
854 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
855 func TestClientHeadContentLength_h1(t *testing.T) {
856 testClientHeadContentLength(t, h1Mode)
859 func TestClientHeadContentLength_h2(t *testing.T) {
860 testClientHeadContentLength(t, h2Mode)
863 func testClientHeadContentLength(t *testing.T, h2 bool) {
865 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
866 if v := r.FormValue("cl"); v != "" {
867 w.Header().Set("Content-Length", v)
879 for _, tt := range tests {
880 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
881 res, err := cst.c.Do(req)
885 if res.ContentLength != tt.want {
886 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
888 bs, err := ioutil.ReadAll(res.Body)
893 t.Errorf("Unexpected content: %q", bs)
898 func TestEmptyPasswordAuth(t *testing.T) {
901 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
902 auth := r.Header.Get("Authorization")
903 if strings.HasPrefix(auth, "Basic ") {
905 decoded, err := base64.StdEncoding.DecodeString(encoded)
909 expected := gopher + ":"
912 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
915 t.Errorf("Invalid auth %q", auth)
920 req, err := NewRequest("GET", ts.URL, nil)
924 req.URL.User = url.User(gopher)
925 resp, err := c.Do(req)
929 defer resp.Body.Close()
932 func TestBasicAuth(t *testing.T) {
934 tr := &recordingTransport{}
935 client := &Client{Transport: tr}
937 url := "http://My%20User:My%20Pass@dummy.faketld/"
938 expected := "My User:My Pass"
941 if tr.req.Method != "GET" {
942 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
944 if tr.req.URL.String() != url {
945 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
947 if tr.req.Header == nil {
948 t.Fatalf("expected non-nil request Header")
950 auth := tr.req.Header.Get("Authorization")
951 if strings.HasPrefix(auth, "Basic ") {
953 decoded, err := base64.StdEncoding.DecodeString(encoded)
959 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
962 t.Errorf("Invalid auth %q", auth)
966 func TestBasicAuthHeadersPreserved(t *testing.T) {
968 tr := &recordingTransport{}
969 client := &Client{Transport: tr}
971 // If Authorization header is provided, username in URL should not override it
972 url := "http://My%20User@dummy.faketld/"
973 req, err := NewRequest("GET", url, nil)
977 req.SetBasicAuth("My User", "My Pass")
978 expected := "My User:My Pass"
981 if tr.req.Method != "GET" {
982 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
984 if tr.req.URL.String() != url {
985 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
987 if tr.req.Header == nil {
988 t.Fatalf("expected non-nil request Header")
990 auth := tr.req.Header.Get("Authorization")
991 if strings.HasPrefix(auth, "Basic ") {
993 decoded, err := base64.StdEncoding.DecodeString(encoded)
999 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1002 t.Errorf("Invalid auth %q", auth)
1007 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1008 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1010 func testClientTimeout(t *testing.T, h2 bool) {
1011 if testing.Short() {
1012 t.Skip("skipping in short mode")
1015 sawRoot := make(chan bool, 1)
1016 sawSlow := make(chan bool, 1)
1017 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1018 if r.URL.Path == "/" {
1020 Redirect(w, r, "/slow", StatusFound)
1023 if r.URL.Path == "/slow" {
1024 w.Write([]byte("Hello"))
1027 time.Sleep(2 * time.Second)
1032 const timeout = 500 * time.Millisecond
1033 cst.c.Timeout = timeout
1035 res, err := cst.c.Get(cst.ts.URL)
1044 t.Fatal("handler never got / request")
1051 t.Fatal("handler never got /slow request")
1054 errc := make(chan error, 1)
1056 _, err := ioutil.ReadAll(res.Body)
1061 const failTime = timeout * 2
1065 t.Fatal("expected error from ReadAll")
1067 ne, ok := err.(net.Error)
1069 t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1070 } else if !ne.Timeout() {
1071 t.Errorf("net.Error.Timeout = false; want true")
1073 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1074 t.Errorf("error string = %q; missing timeout substring", got)
1076 case <-time.After(failTime):
1077 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1081 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1082 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1084 // Client.Timeout firing before getting to the body
1085 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1086 if testing.Short() {
1087 t.Skip("skipping in short mode")
1090 donec := make(chan bool)
1091 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1095 // Note that we use a channel send here and not a close.
1096 // The race detector doesn't know that we're waiting for a timeout
1097 // and thinks that the waitgroup inside httptest.Server is added to concurrently
1098 // with us closing it. If we timed out immediately, we could close the testserver
1099 // before we entered the handler. We're not timing out immediately and there's
1100 // no way we would be done before we entered the handler, but the race detector
1101 // doesn't know this, so synchronize explicitly.
1102 defer func() { donec <- true }()
1104 cst.c.Timeout = 500 * time.Millisecond
1105 _, err := cst.c.Get(cst.ts.URL)
1107 t.Fatal("got response from Get; expected error")
1109 if _, ok := err.(*url.Error); !ok {
1110 t.Fatalf("Got error of type %T; want *url.Error", err)
1112 ne, ok := err.(net.Error)
1114 t.Fatalf("Got error of type %T; want some net.Error", err)
1117 t.Error("net.Error.Timeout = false; want true")
1119 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1120 t.Errorf("error string = %q; missing timeout substring", got)
1124 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1125 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1126 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1128 saw := make(chan string, 2)
1129 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1131 if r.URL.Path == "/" {
1132 Redirect(w, r, "/foo", StatusFound) // which includes a body
1137 res, err := cst.c.Get(cst.ts.URL)
1141 _, err = ioutil.ReadAll(res.Body)
1151 t.Fatal("server didn't see a request")
1156 case second = <-saw:
1158 t.Fatal("server didn't see a second request")
1161 if first != second {
1162 t.Fatal("server saw different client ports before & after the redirect")
1166 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1167 type eofReaderFunc func()
1169 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1174 func TestReferer(t *testing.T) {
1176 lastReq, newReq string // from -> to URLs
1180 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1181 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1183 // don't send a user and password:
1184 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1185 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1188 {"http://test.com", "http://link.com", "http://test.com"},
1189 {"https://test.com", "https://link.com", "https://test.com"},
1191 // https to http doesn't send a referer:
1192 {"https://test.com", "http://link.com", ""},
1193 {"https://gopher:go@test.com", "http://link.com", ""},
1195 for _, tt := range tests {
1196 l, err := url.Parse(tt.lastReq)
1200 n, err := url.Parse(tt.newReq)
1204 r := ExportRefererForURL(l, n)
1206 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1211 // issue15577Tripper returns a Response with a redirect response
1212 // header and doesn't populate its Response.Request field.
1213 type issue15577Tripper struct{}
1215 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1218 Header: map[string][]string{"Location": {"http://www.example.com/"}},
1219 Body: ioutil.NopCloser(strings.NewReader("")),
1224 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1225 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1227 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1228 Transport: issue15577Tripper{},
1230 // Check that this doesn't crash:
1231 c.Get("http://dummy.tld")
1234 // Issue 4800: copy (some) headers when Client follows a redirect
1235 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1237 ua = "some-agent/1.2"
1241 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1243 "User-Agent": []string{ua},
1244 "X-Foo": []string{xfoo},
1245 "Referer": []string{ts2URL},
1246 "Accept-Encoding": []string{"gzip"},
1248 if !reflect.DeepEqual(r.Header, want) {
1249 t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1252 w.Header().Set("Result", "got errors")
1254 w.Header().Set("Result", "ok")
1258 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1259 Redirect(w, r, ts1.URL, StatusFound)
1265 defer tr.CloseIdleConnections()
1268 CheckRedirect: func(r *Request, via []*Request) error {
1270 "User-Agent": []string{ua},
1271 "X-Foo": []string{xfoo},
1272 "Referer": []string{ts2URL},
1274 if !reflect.DeepEqual(r.Header, want) {
1275 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1281 req, _ := NewRequest("GET", ts2.URL, nil)
1282 req.Header.Add("User-Agent", ua)
1283 req.Header.Add("X-Foo", xfoo)
1284 req.Header.Add("Cookie", "foo=bar")
1285 req.Header.Add("Authorization", "secretpassword")
1286 res, err := c.Do(req)
1290 defer res.Body.Close()
1291 if res.StatusCode != 200 {
1294 if got := res.Header.Get("Result"); got != "ok" {
1295 t.Errorf("result = %q; want ok", got)
1299 // Part of Issue 4800
1300 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1307 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1308 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1310 // Sensitive headers:
1311 {"cookie", "http://foo.com/", "http://bar.com/", false},
1312 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1313 {"authorization", "http://foo.com/", "http://bar.com/", false},
1314 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1316 // But subdomains should work:
1317 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1318 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1319 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1320 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1321 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1323 for i, tt := range tests {
1324 u0, err := url.Parse(tt.initialURL)
1326 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1329 u1, err := url.Parse(tt.destURL)
1331 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1334 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1336 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1337 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1342 func TestClientRedirectTypes(t *testing.T) {
1345 tests := [...]struct {
1346 broken int // broken is bug number
1349 wantMethod string // desired subsequent client method
1351 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1352 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1353 2: {method: "POST", serverStatus: 307, wantMethod: "POST", broken: 16840},
1355 5: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1356 6: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1357 7: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1358 8: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1359 9: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1361 10: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE", broken: 13994},
1364 handlerc := make(chan HandlerFunc, 1)
1366 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1372 for i, tt := range tests {
1374 t.Logf("#%d: skipping known broken test case. See Issue #%d", i, tt.broken)
1378 handlerc <- func(w ResponseWriter, r *Request) {
1379 w.Header().Set("Location", ts.URL)
1380 w.WriteHeader(tt.serverStatus)
1383 req, err := NewRequest(tt.method, ts.URL, nil)
1385 t.Errorf("#%d: NewRequest: %v", i, err)
1390 c.CheckRedirect = func(req *Request, via []*Request) error {
1391 if got, want := req.Method, tt.wantMethod; got != want {
1392 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1394 handlerc <- func(rw ResponseWriter, req *Request) {
1395 // TODO: Check that the body is valid when we do 307 and 308 support
1400 res, err := c.Do(req)
1402 t.Errorf("#%d: Response: %v", i, err)