]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/client_test.go
net/http: deflake TestClientTimeout
[gostls13.git] / src / net / http / client_test.go
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.
4
5 // Tests for client.go
6
7 package http_test
8
9 import (
10         "bytes"
11         "context"
12         "crypto/tls"
13         "crypto/x509"
14         "encoding/base64"
15         "errors"
16         "fmt"
17         "io"
18         "io/ioutil"
19         "log"
20         "net"
21         . "net/http"
22         "net/http/cookiejar"
23         "net/http/httptest"
24         "net/url"
25         "reflect"
26         "strconv"
27         "strings"
28         "sync"
29         "testing"
30         "time"
31 )
32
33 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
34         w.Header().Set("Last-Modified", "sometime")
35         fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
36 })
37
38 // pedanticReadAll works like ioutil.ReadAll but additionally
39 // verifies that r obeys the documented io.Reader contract.
40 func pedanticReadAll(r io.Reader) (b []byte, err error) {
41         var bufa [64]byte
42         buf := bufa[:]
43         for {
44                 n, err := r.Read(buf)
45                 if n == 0 && err == nil {
46                         return nil, fmt.Errorf("Read: n=0 with err=nil")
47                 }
48                 b = append(b, buf[:n]...)
49                 if err == io.EOF {
50                         n, err := r.Read(buf)
51                         if n != 0 || err != io.EOF {
52                                 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
53                         }
54                         return b, nil
55                 }
56                 if err != nil {
57                         return b, err
58                 }
59         }
60 }
61
62 type chanWriter chan string
63
64 func (w chanWriter) Write(p []byte) (n int, err error) {
65         w <- string(p)
66         return len(p), nil
67 }
68
69 func TestClient(t *testing.T) {
70         setParallel(t)
71         defer afterTest(t)
72         ts := httptest.NewServer(robotsTxtHandler)
73         defer ts.Close()
74
75         c := &Client{Transport: &Transport{DisableKeepAlives: true}}
76         r, err := c.Get(ts.URL)
77         var b []byte
78         if err == nil {
79                 b, err = pedanticReadAll(r.Body)
80                 r.Body.Close()
81         }
82         if err != nil {
83                 t.Error(err)
84         } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
85                 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
86         }
87 }
88
89 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
90 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
91
92 func testClientHead(t *testing.T, h2 bool) {
93         defer afterTest(t)
94         cst := newClientServerTest(t, h2, robotsTxtHandler)
95         defer cst.close()
96
97         r, err := cst.c.Head(cst.ts.URL)
98         if err != nil {
99                 t.Fatal(err)
100         }
101         if _, ok := r.Header["Last-Modified"]; !ok {
102                 t.Error("Last-Modified header not found.")
103         }
104 }
105
106 type recordingTransport struct {
107         req *Request
108 }
109
110 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
111         t.req = req
112         return nil, errors.New("dummy impl")
113 }
114
115 func TestGetRequestFormat(t *testing.T) {
116         setParallel(t)
117         defer afterTest(t)
118         tr := &recordingTransport{}
119         client := &Client{Transport: tr}
120         url := "http://dummy.faketld/"
121         client.Get(url) // Note: doesn't hit network
122         if tr.req.Method != "GET" {
123                 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
124         }
125         if tr.req.URL.String() != url {
126                 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
127         }
128         if tr.req.Header == nil {
129                 t.Errorf("expected non-nil request Header")
130         }
131 }
132
133 func TestPostRequestFormat(t *testing.T) {
134         defer afterTest(t)
135         tr := &recordingTransport{}
136         client := &Client{Transport: tr}
137
138         url := "http://dummy.faketld/"
139         json := `{"key":"value"}`
140         b := strings.NewReader(json)
141         client.Post(url, "application/json", b) // Note: doesn't hit network
142
143         if tr.req.Method != "POST" {
144                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
145         }
146         if tr.req.URL.String() != url {
147                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
148         }
149         if tr.req.Header == nil {
150                 t.Fatalf("expected non-nil request Header")
151         }
152         if tr.req.Close {
153                 t.Error("got Close true, want false")
154         }
155         if g, e := tr.req.ContentLength, int64(len(json)); g != e {
156                 t.Errorf("got ContentLength %d, want %d", g, e)
157         }
158 }
159
160 func TestPostFormRequestFormat(t *testing.T) {
161         defer afterTest(t)
162         tr := &recordingTransport{}
163         client := &Client{Transport: tr}
164
165         urlStr := "http://dummy.faketld/"
166         form := make(url.Values)
167         form.Set("foo", "bar")
168         form.Add("foo", "bar2")
169         form.Set("bar", "baz")
170         client.PostForm(urlStr, form) // Note: doesn't hit network
171
172         if tr.req.Method != "POST" {
173                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
174         }
175         if tr.req.URL.String() != urlStr {
176                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
177         }
178         if tr.req.Header == nil {
179                 t.Fatalf("expected non-nil request Header")
180         }
181         if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
182                 t.Errorf("got Content-Type %q, want %q", g, e)
183         }
184         if tr.req.Close {
185                 t.Error("got Close true, want false")
186         }
187         // Depending on map iteration, body can be either of these.
188         expectedBody := "foo=bar&foo=bar2&bar=baz"
189         expectedBody1 := "bar=baz&foo=bar&foo=bar2"
190         if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
191                 t.Errorf("got ContentLength %d, want %d", g, e)
192         }
193         bodyb, err := ioutil.ReadAll(tr.req.Body)
194         if err != nil {
195                 t.Fatalf("ReadAll on req.Body: %v", err)
196         }
197         if g := string(bodyb); g != expectedBody && g != expectedBody1 {
198                 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
199         }
200 }
201
202 func TestClientRedirects(t *testing.T) {
203         setParallel(t)
204         defer afterTest(t)
205         var ts *httptest.Server
206         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
207                 n, _ := strconv.Atoi(r.FormValue("n"))
208                 // Test Referer header. (7 is arbitrary position to test at)
209                 if n == 7 {
210                         if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
211                                 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
212                         }
213                 }
214                 if n < 15 {
215                         Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
216                         return
217                 }
218                 fmt.Fprintf(w, "n=%d", n)
219         }))
220         defer ts.Close()
221
222         tr := &Transport{}
223         defer tr.CloseIdleConnections()
224
225         c := &Client{Transport: tr}
226         _, err := c.Get(ts.URL)
227         if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
228                 t.Errorf("with default client Get, expected error %q, got %q", e, g)
229         }
230
231         // HEAD request should also have the ability to follow redirects.
232         _, err = c.Head(ts.URL)
233         if e, g := "Head /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
234                 t.Errorf("with default client Head, expected error %q, got %q", e, g)
235         }
236
237         // Do should also follow redirects.
238         greq, _ := NewRequest("GET", ts.URL, nil)
239         _, err = c.Do(greq)
240         if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
241                 t.Errorf("with default client Do, expected error %q, got %q", e, g)
242         }
243
244         // Requests with an empty Method should also redirect (Issue 12705)
245         greq.Method = ""
246         _, err = c.Do(greq)
247         if e, g := "Get /?n=10: stopped after 10 redirects", fmt.Sprintf("%v", err); e != g {
248                 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
249         }
250
251         var checkErr error
252         var lastVia []*Request
253         var lastReq *Request
254         c = &Client{
255                 Transport: tr,
256                 CheckRedirect: func(req *Request, via []*Request) error {
257                         lastReq = req
258                         lastVia = via
259                         return checkErr
260                 },
261         }
262         res, err := c.Get(ts.URL)
263         if err != nil {
264                 t.Fatalf("Get error: %v", err)
265         }
266         res.Body.Close()
267         finalUrl := res.Request.URL.String()
268         if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
269                 t.Errorf("with custom client, expected error %q, got %q", e, g)
270         }
271         if !strings.HasSuffix(finalUrl, "/?n=15") {
272                 t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
273         }
274         if e, g := 15, len(lastVia); e != g {
275                 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
276         }
277
278         // Test that Request.Cancel is propagated between requests (Issue 14053)
279         creq, _ := NewRequest("HEAD", ts.URL, nil)
280         cancel := make(chan struct{})
281         creq.Cancel = cancel
282         if _, err := c.Do(creq); err != nil {
283                 t.Fatal(err)
284         }
285         if lastReq == nil {
286                 t.Fatal("didn't see redirect")
287         }
288         if lastReq.Cancel != cancel {
289                 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
290         }
291
292         checkErr = errors.New("no redirects allowed")
293         res, err = c.Get(ts.URL)
294         if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
295                 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
296         }
297         if res == nil {
298                 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
299         }
300         res.Body.Close()
301         if res.Header.Get("Location") == "" {
302                 t.Errorf("no Location header in Response")
303         }
304 }
305
306 func TestClientRedirectContext(t *testing.T) {
307         setParallel(t)
308         defer afterTest(t)
309         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
310                 Redirect(w, r, "/", StatusTemporaryRedirect)
311         }))
312         defer ts.Close()
313
314         tr := &Transport{}
315         defer tr.CloseIdleConnections()
316
317         ctx, cancel := context.WithCancel(context.Background())
318         c := &Client{
319                 Transport: tr,
320                 CheckRedirect: func(req *Request, via []*Request) error {
321                         cancel()
322                         if len(via) > 2 {
323                                 return errors.New("too many redirects")
324                         }
325                         return nil
326                 },
327         }
328         req, _ := NewRequest("GET", ts.URL, nil)
329         req = req.WithContext(ctx)
330         _, err := c.Do(req)
331         ue, ok := err.(*url.Error)
332         if !ok {
333                 t.Fatalf("got error %T; want *url.Error", err)
334         }
335         if ue.Err != context.Canceled {
336                 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
337         }
338 }
339
340 type redirectTest struct {
341         suffix       string
342         want         int // response code
343         redirectBody string
344 }
345
346 func TestPostRedirects(t *testing.T) {
347         postRedirectTests := []redirectTest{
348                 {"/", 200, "first"},
349                 {"/?code=301&next=302", 200, "c301"},
350                 {"/?code=302&next=302", 200, "c302"},
351                 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
352                 {"/?code=304", 304, "c304"},
353                 {"/?code=305", 305, "c305"},
354                 {"/?code=307&next=303,308,302", 200, "c307"},
355                 {"/?code=308&next=302,301", 200, "c308"},
356                 {"/?code=404", 404, "c404"},
357         }
358
359         wantSegments := []string{
360                 `POST / "first"`,
361                 `POST /?code=301&next=302 "c301"`,
362                 `GET /?code=302 "c301"`,
363                 `GET / "c301"`,
364                 `POST /?code=302&next=302 "c302"`,
365                 `GET /?code=302 "c302"`,
366                 `GET / "c302"`,
367                 `POST /?code=303&next=301 "c303wc301"`,
368                 `GET /?code=301 "c303wc301"`,
369                 `GET / "c303wc301"`,
370                 `POST /?code=304 "c304"`,
371                 `POST /?code=305 "c305"`,
372                 `POST /?code=307&next=303,308,302 "c307"`,
373                 `POST /?code=303&next=308,302 "c307"`,
374                 `GET /?code=308&next=302 "c307"`,
375                 `GET /?code=302 "c307"`,
376                 `GET / "c307"`,
377                 `POST /?code=308&next=302,301 "c308"`,
378                 `POST /?code=302&next=301 "c308"`,
379                 `GET /?code=301 "c308"`,
380                 `GET / "c308"`,
381                 `POST /?code=404 "c404"`,
382         }
383         want := strings.Join(wantSegments, "\n")
384         testRedirectsByMethod(t, "POST", postRedirectTests, want)
385 }
386
387 func TestDeleteRedirects(t *testing.T) {
388         deleteRedirectTests := []redirectTest{
389                 {"/", 200, "first"},
390                 {"/?code=301&next=302,308", 200, "c301"},
391                 {"/?code=302&next=302", 200, "c302"},
392                 {"/?code=303", 200, "c303"},
393                 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
394                 {"/?code=308&next=307", 200, "c308"},
395                 {"/?code=404", 404, "c404"},
396         }
397
398         wantSegments := []string{
399                 `DELETE / "first"`,
400                 `DELETE /?code=301&next=302,308 "c301"`,
401                 `GET /?code=302&next=308 "c301"`,
402                 `GET /?code=308 "c301"`,
403                 `GET / "c301"`,
404                 `DELETE /?code=302&next=302 "c302"`,
405                 `GET /?code=302 "c302"`,
406                 `GET / "c302"`,
407                 `DELETE /?code=303 "c303"`,
408                 `GET / "c303"`,
409                 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
410                 `DELETE /?code=301&next=308,303,302,304 "c307"`,
411                 `GET /?code=308&next=303,302,304 "c307"`,
412                 `GET /?code=303&next=302,304 "c307"`,
413                 `GET /?code=302&next=304 "c307"`,
414                 `GET /?code=304 "c307"`,
415                 `DELETE /?code=308&next=307 "c308"`,
416                 `DELETE /?code=307 "c308"`,
417                 `DELETE / "c308"`,
418                 `DELETE /?code=404 "c404"`,
419         }
420         want := strings.Join(wantSegments, "\n")
421         testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
422 }
423
424 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
425         defer afterTest(t)
426         var log struct {
427                 sync.Mutex
428                 bytes.Buffer
429         }
430         var ts *httptest.Server
431         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
432                 log.Lock()
433                 slurp, _ := ioutil.ReadAll(r.Body)
434                 fmt.Fprintf(&log.Buffer, "%s %s %q\n", r.Method, r.RequestURI, slurp)
435                 log.Unlock()
436                 urlQuery := r.URL.Query()
437                 if v := urlQuery.Get("code"); v != "" {
438                         location := ts.URL
439                         if final := urlQuery.Get("next"); final != "" {
440                                 splits := strings.Split(final, ",")
441                                 first, rest := splits[0], splits[1:]
442                                 location = fmt.Sprintf("%s?code=%s", location, first)
443                                 if len(rest) > 0 {
444                                         location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
445                                 }
446                         }
447                         code, _ := strconv.Atoi(v)
448                         if code/100 == 3 {
449                                 w.Header().Set("Location", location)
450                         }
451                         w.WriteHeader(code)
452                 }
453         }))
454         defer ts.Close()
455
456         for _, tt := range table {
457                 content := tt.redirectBody
458                 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
459                 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil }
460                 res, err := DefaultClient.Do(req)
461
462                 if err != nil {
463                         t.Fatal(err)
464                 }
465                 if res.StatusCode != tt.want {
466                         t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
467                 }
468         }
469         log.Lock()
470         got := log.String()
471         log.Unlock()
472
473         got = strings.TrimSpace(got)
474         want = strings.TrimSpace(want)
475
476         if got != want {
477                 t.Errorf("Log differs.\n Got:\n%s\nWant:\n%s\n", got, want)
478         }
479 }
480
481 func TestClientRedirectUseResponse(t *testing.T) {
482         setParallel(t)
483         defer afterTest(t)
484         const body = "Hello, world."
485         var ts *httptest.Server
486         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
487                 if strings.Contains(r.URL.Path, "/other") {
488                         io.WriteString(w, "wrong body")
489                 } else {
490                         w.Header().Set("Location", ts.URL+"/other")
491                         w.WriteHeader(StatusFound)
492                         io.WriteString(w, body)
493                 }
494         }))
495         defer ts.Close()
496
497         tr := &Transport{}
498         defer tr.CloseIdleConnections()
499
500         c := &Client{
501                 Transport: tr,
502                 CheckRedirect: func(req *Request, via []*Request) error {
503                         if req.Response == nil {
504                                 t.Error("expected non-nil Request.Response")
505                         }
506                         return ErrUseLastResponse
507                 },
508         }
509         res, err := c.Get(ts.URL)
510         if err != nil {
511                 t.Fatal(err)
512         }
513         if res.StatusCode != StatusFound {
514                 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
515         }
516         defer res.Body.Close()
517         slurp, err := ioutil.ReadAll(res.Body)
518         if err != nil {
519                 t.Fatal(err)
520         }
521         if string(slurp) != body {
522                 t.Errorf("body = %q; want %q", slurp, body)
523         }
524 }
525
526 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
527 // have a Location header.
528 func TestClientRedirect308NoLocation(t *testing.T) {
529         setParallel(t)
530         defer afterTest(t)
531         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
532                 w.Header().Set("Foo", "Bar")
533                 w.WriteHeader(308)
534         }))
535         defer ts.Close()
536         res, err := Get(ts.URL)
537         if err != nil {
538                 t.Fatal(err)
539         }
540         res.Body.Close()
541         if res.StatusCode != 308 {
542                 t.Errorf("status = %d; want %d", res.StatusCode, 308)
543         }
544         if got := res.Header.Get("Foo"); got != "Bar" {
545                 t.Errorf("Foo header = %q; want Bar", got)
546         }
547 }
548
549 // Don't follow a 307/308 if we can't resent the request body.
550 func TestClientRedirect308NoGetBody(t *testing.T) {
551         setParallel(t)
552         defer afterTest(t)
553         const fakeURL = "https://localhost:1234/" // won't be hit
554         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
555                 w.Header().Set("Location", fakeURL)
556                 w.WriteHeader(308)
557         }))
558         defer ts.Close()
559         req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
560         if err != nil {
561                 t.Fatal(err)
562         }
563         req.GetBody = nil // so it can't rewind.
564         res, err := DefaultClient.Do(req)
565         if err != nil {
566                 t.Fatal(err)
567         }
568         res.Body.Close()
569         if res.StatusCode != 308 {
570                 t.Errorf("status = %d; want %d", res.StatusCode, 308)
571         }
572         if got := res.Header.Get("Location"); got != fakeURL {
573                 t.Errorf("Location header = %q; want %q", got, fakeURL)
574         }
575 }
576
577 var expectedCookies = []*Cookie{
578         {Name: "ChocolateChip", Value: "tasty"},
579         {Name: "First", Value: "Hit"},
580         {Name: "Second", Value: "Hit"},
581 }
582
583 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
584         for _, cookie := range r.Cookies() {
585                 SetCookie(w, cookie)
586         }
587         if r.URL.Path == "/" {
588                 SetCookie(w, expectedCookies[1])
589                 Redirect(w, r, "/second", StatusMovedPermanently)
590         } else {
591                 SetCookie(w, expectedCookies[2])
592                 w.Write([]byte("hello"))
593         }
594 })
595
596 func TestClientSendsCookieFromJar(t *testing.T) {
597         defer afterTest(t)
598         tr := &recordingTransport{}
599         client := &Client{Transport: tr}
600         client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
601         us := "http://dummy.faketld/"
602         u, _ := url.Parse(us)
603         client.Jar.SetCookies(u, expectedCookies)
604
605         client.Get(us) // Note: doesn't hit network
606         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
607
608         client.Head(us) // Note: doesn't hit network
609         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
610
611         client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
612         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
613
614         client.PostForm(us, url.Values{}) // Note: doesn't hit network
615         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
616
617         req, _ := NewRequest("GET", us, nil)
618         client.Do(req) // Note: doesn't hit network
619         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
620
621         req, _ = NewRequest("POST", us, nil)
622         client.Do(req) // Note: doesn't hit network
623         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
624 }
625
626 // Just enough correctness for our redirect tests. Uses the URL.Host as the
627 // scope of all cookies.
628 type TestJar struct {
629         m      sync.Mutex
630         perURL map[string][]*Cookie
631 }
632
633 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
634         j.m.Lock()
635         defer j.m.Unlock()
636         if j.perURL == nil {
637                 j.perURL = make(map[string][]*Cookie)
638         }
639         j.perURL[u.Host] = cookies
640 }
641
642 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
643         j.m.Lock()
644         defer j.m.Unlock()
645         return j.perURL[u.Host]
646 }
647
648 func TestRedirectCookiesJar(t *testing.T) {
649         setParallel(t)
650         defer afterTest(t)
651         var ts *httptest.Server
652         ts = httptest.NewServer(echoCookiesRedirectHandler)
653         defer ts.Close()
654         tr := &Transport{}
655         defer tr.CloseIdleConnections()
656         c := &Client{
657                 Transport: tr,
658                 Jar:       new(TestJar),
659         }
660         u, _ := url.Parse(ts.URL)
661         c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
662         resp, err := c.Get(ts.URL)
663         if err != nil {
664                 t.Fatalf("Get: %v", err)
665         }
666         resp.Body.Close()
667         matchReturnedCookies(t, expectedCookies, resp.Cookies())
668 }
669
670 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
671         if len(given) != len(expected) {
672                 t.Logf("Received cookies: %v", given)
673                 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
674         }
675         for _, ec := range expected {
676                 foundC := false
677                 for _, c := range given {
678                         if ec.Name == c.Name && ec.Value == c.Value {
679                                 foundC = true
680                                 break
681                         }
682                 }
683                 if !foundC {
684                         t.Errorf("Missing cookie %v", ec)
685                 }
686         }
687 }
688
689 func TestJarCalls(t *testing.T) {
690         defer afterTest(t)
691         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
692                 pathSuffix := r.RequestURI[1:]
693                 if r.RequestURI == "/nosetcookie" {
694                         return // don't set cookies for this path
695                 }
696                 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
697                 if r.RequestURI == "/" {
698                         Redirect(w, r, "http://secondhost.fake/secondpath", 302)
699                 }
700         }))
701         defer ts.Close()
702         jar := new(RecordingJar)
703         c := &Client{
704                 Jar: jar,
705                 Transport: &Transport{
706                         Dial: func(_ string, _ string) (net.Conn, error) {
707                                 return net.Dial("tcp", ts.Listener.Addr().String())
708                         },
709                 },
710         }
711         _, err := c.Get("http://firsthost.fake/")
712         if err != nil {
713                 t.Fatal(err)
714         }
715         _, err = c.Get("http://firsthost.fake/nosetcookie")
716         if err != nil {
717                 t.Fatal(err)
718         }
719         got := jar.log.String()
720         want := `Cookies("http://firsthost.fake/")
721 SetCookie("http://firsthost.fake/", [name=val])
722 Cookies("http://secondhost.fake/secondpath")
723 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
724 Cookies("http://firsthost.fake/nosetcookie")
725 `
726         if got != want {
727                 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
728         }
729 }
730
731 // RecordingJar keeps a log of calls made to it, without
732 // tracking any cookies.
733 type RecordingJar struct {
734         mu  sync.Mutex
735         log bytes.Buffer
736 }
737
738 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
739         j.logf("SetCookie(%q, %v)\n", u, cookies)
740 }
741
742 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
743         j.logf("Cookies(%q)\n", u)
744         return nil
745 }
746
747 func (j *RecordingJar) logf(format string, args ...interface{}) {
748         j.mu.Lock()
749         defer j.mu.Unlock()
750         fmt.Fprintf(&j.log, format, args...)
751 }
752
753 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
754 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
755
756 func testStreamingGet(t *testing.T, h2 bool) {
757         defer afterTest(t)
758         say := make(chan string)
759         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
760                 w.(Flusher).Flush()
761                 for str := range say {
762                         w.Write([]byte(str))
763                         w.(Flusher).Flush()
764                 }
765         }))
766         defer cst.close()
767
768         c := cst.c
769         res, err := c.Get(cst.ts.URL)
770         if err != nil {
771                 t.Fatal(err)
772         }
773         var buf [10]byte
774         for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
775                 say <- str
776                 n, err := io.ReadFull(res.Body, buf[0:len(str)])
777                 if err != nil {
778                         t.Fatalf("ReadFull on %q: %v", str, err)
779                 }
780                 if n != len(str) {
781                         t.Fatalf("Receiving %q, only read %d bytes", str, n)
782                 }
783                 got := string(buf[0:n])
784                 if got != str {
785                         t.Fatalf("Expected %q, got %q", str, got)
786                 }
787         }
788         close(say)
789         _, err = io.ReadFull(res.Body, buf[0:1])
790         if err != io.EOF {
791                 t.Fatalf("at end expected EOF, got %v", err)
792         }
793 }
794
795 type writeCountingConn struct {
796         net.Conn
797         count *int
798 }
799
800 func (c *writeCountingConn) Write(p []byte) (int, error) {
801         *c.count++
802         return c.Conn.Write(p)
803 }
804
805 // TestClientWrites verifies that client requests are buffered and we
806 // don't send a TCP packet per line of the http request + body.
807 func TestClientWrites(t *testing.T) {
808         defer afterTest(t)
809         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
810         }))
811         defer ts.Close()
812
813         writes := 0
814         dialer := func(netz string, addr string) (net.Conn, error) {
815                 c, err := net.Dial(netz, addr)
816                 if err == nil {
817                         c = &writeCountingConn{c, &writes}
818                 }
819                 return c, err
820         }
821         c := &Client{Transport: &Transport{Dial: dialer}}
822
823         _, err := c.Get(ts.URL)
824         if err != nil {
825                 t.Fatal(err)
826         }
827         if writes != 1 {
828                 t.Errorf("Get request did %d Write calls, want 1", writes)
829         }
830
831         writes = 0
832         _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
833         if err != nil {
834                 t.Fatal(err)
835         }
836         if writes != 1 {
837                 t.Errorf("Post request did %d Write calls, want 1", writes)
838         }
839 }
840
841 func TestClientInsecureTransport(t *testing.T) {
842         setParallel(t)
843         defer afterTest(t)
844         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
845                 w.Write([]byte("Hello"))
846         }))
847         errc := make(chanWriter, 10) // but only expecting 1
848         ts.Config.ErrorLog = log.New(errc, "", 0)
849         defer ts.Close()
850
851         // TODO(bradfitz): add tests for skipping hostname checks too?
852         // would require a new cert for testing, and probably
853         // redundant with these tests.
854         for _, insecure := range []bool{true, false} {
855                 tr := &Transport{
856                         TLSClientConfig: &tls.Config{
857                                 InsecureSkipVerify: insecure,
858                         },
859                 }
860                 defer tr.CloseIdleConnections()
861                 c := &Client{Transport: tr}
862                 res, err := c.Get(ts.URL)
863                 if (err == nil) != insecure {
864                         t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
865                 }
866                 if res != nil {
867                         res.Body.Close()
868                 }
869         }
870
871         select {
872         case v := <-errc:
873                 if !strings.Contains(v, "TLS handshake error") {
874                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
875                 }
876         case <-time.After(5 * time.Second):
877                 t.Errorf("timeout waiting for logged error")
878         }
879
880 }
881
882 func TestClientErrorWithRequestURI(t *testing.T) {
883         defer afterTest(t)
884         req, _ := NewRequest("GET", "http://localhost:1234/", nil)
885         req.RequestURI = "/this/field/is/illegal/and/should/error/"
886         _, err := DefaultClient.Do(req)
887         if err == nil {
888                 t.Fatalf("expected an error")
889         }
890         if !strings.Contains(err.Error(), "RequestURI") {
891                 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
892         }
893 }
894
895 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
896         certs := x509.NewCertPool()
897         for _, c := range ts.TLS.Certificates {
898                 roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
899                 if err != nil {
900                         t.Fatalf("error parsing server's root cert: %v", err)
901                 }
902                 for _, root := range roots {
903                         certs.AddCert(root)
904                 }
905         }
906         return &Transport{
907                 TLSClientConfig: &tls.Config{RootCAs: certs},
908         }
909 }
910
911 func TestClientWithCorrectTLSServerName(t *testing.T) {
912         defer afterTest(t)
913
914         const serverName = "example.com"
915         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
916                 if r.TLS.ServerName != serverName {
917                         t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
918                 }
919         }))
920         defer ts.Close()
921
922         trans := newTLSTransport(t, ts)
923         trans.TLSClientConfig.ServerName = serverName
924         c := &Client{Transport: trans}
925         if _, err := c.Get(ts.URL); err != nil {
926                 t.Fatalf("expected successful TLS connection, got error: %v", err)
927         }
928 }
929
930 func TestClientWithIncorrectTLSServerName(t *testing.T) {
931         defer afterTest(t)
932         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
933         defer ts.Close()
934         errc := make(chanWriter, 10) // but only expecting 1
935         ts.Config.ErrorLog = log.New(errc, "", 0)
936
937         trans := newTLSTransport(t, ts)
938         trans.TLSClientConfig.ServerName = "badserver"
939         c := &Client{Transport: trans}
940         _, err := c.Get(ts.URL)
941         if err == nil {
942                 t.Fatalf("expected an error")
943         }
944         if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
945                 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
946         }
947         select {
948         case v := <-errc:
949                 if !strings.Contains(v, "TLS handshake error") {
950                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
951                 }
952         case <-time.After(5 * time.Second):
953                 t.Errorf("timeout waiting for logged error")
954         }
955 }
956
957 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
958 // when not empty.
959 //
960 // tls.Config.ServerName (non-empty, set to "example.com") takes
961 // precedence over "some-other-host.tld" which previously incorrectly
962 // took precedence. We don't actually connect to (or even resolve)
963 // "some-other-host.tld", though, because of the Transport.Dial hook.
964 //
965 // The httptest.Server has a cert with "example.com" as its name.
966 func TestTransportUsesTLSConfigServerName(t *testing.T) {
967         defer afterTest(t)
968         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
969                 w.Write([]byte("Hello"))
970         }))
971         defer ts.Close()
972
973         tr := newTLSTransport(t, ts)
974         tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
975         tr.Dial = func(netw, addr string) (net.Conn, error) {
976                 return net.Dial(netw, ts.Listener.Addr().String())
977         }
978         defer tr.CloseIdleConnections()
979         c := &Client{Transport: tr}
980         res, err := c.Get("https://some-other-host.tld/")
981         if err != nil {
982                 t.Fatal(err)
983         }
984         res.Body.Close()
985 }
986
987 func TestResponseSetsTLSConnectionState(t *testing.T) {
988         defer afterTest(t)
989         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
990                 w.Write([]byte("Hello"))
991         }))
992         defer ts.Close()
993
994         tr := newTLSTransport(t, ts)
995         tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
996         tr.Dial = func(netw, addr string) (net.Conn, error) {
997                 return net.Dial(netw, ts.Listener.Addr().String())
998         }
999         defer tr.CloseIdleConnections()
1000         c := &Client{Transport: tr}
1001         res, err := c.Get("https://example.com/")
1002         if err != nil {
1003                 t.Fatal(err)
1004         }
1005         defer res.Body.Close()
1006         if res.TLS == nil {
1007                 t.Fatal("Response didn't set TLS Connection State.")
1008         }
1009         if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
1010                 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
1011         }
1012 }
1013
1014 // Check that an HTTPS client can interpret a particular TLS error
1015 // to determine that the server is speaking HTTP.
1016 // See golang.org/issue/11111.
1017 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1018         defer afterTest(t)
1019         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1020         defer ts.Close()
1021
1022         _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1023         if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1024                 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1025         }
1026 }
1027
1028 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1029 func TestClientHeadContentLength_h1(t *testing.T) {
1030         testClientHeadContentLength(t, h1Mode)
1031 }
1032
1033 func TestClientHeadContentLength_h2(t *testing.T) {
1034         testClientHeadContentLength(t, h2Mode)
1035 }
1036
1037 func testClientHeadContentLength(t *testing.T, h2 bool) {
1038         defer afterTest(t)
1039         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1040                 if v := r.FormValue("cl"); v != "" {
1041                         w.Header().Set("Content-Length", v)
1042                 }
1043         }))
1044         defer cst.close()
1045         tests := []struct {
1046                 suffix string
1047                 want   int64
1048         }{
1049                 {"/?cl=1234", 1234},
1050                 {"/?cl=0", 0},
1051                 {"", -1},
1052         }
1053         for _, tt := range tests {
1054                 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1055                 res, err := cst.c.Do(req)
1056                 if err != nil {
1057                         t.Fatal(err)
1058                 }
1059                 if res.ContentLength != tt.want {
1060                         t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1061                 }
1062                 bs, err := ioutil.ReadAll(res.Body)
1063                 if err != nil {
1064                         t.Fatal(err)
1065                 }
1066                 if len(bs) != 0 {
1067                         t.Errorf("Unexpected content: %q", bs)
1068                 }
1069         }
1070 }
1071
1072 func TestEmptyPasswordAuth(t *testing.T) {
1073         setParallel(t)
1074         defer afterTest(t)
1075         gopher := "gopher"
1076         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1077                 auth := r.Header.Get("Authorization")
1078                 if strings.HasPrefix(auth, "Basic ") {
1079                         encoded := auth[6:]
1080                         decoded, err := base64.StdEncoding.DecodeString(encoded)
1081                         if err != nil {
1082                                 t.Fatal(err)
1083                         }
1084                         expected := gopher + ":"
1085                         s := string(decoded)
1086                         if expected != s {
1087                                 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1088                         }
1089                 } else {
1090                         t.Errorf("Invalid auth %q", auth)
1091                 }
1092         }))
1093         defer ts.Close()
1094         tr := &Transport{}
1095         defer tr.CloseIdleConnections()
1096         c := &Client{Transport: tr}
1097         req, err := NewRequest("GET", ts.URL, nil)
1098         if err != nil {
1099                 t.Fatal(err)
1100         }
1101         req.URL.User = url.User(gopher)
1102         resp, err := c.Do(req)
1103         if err != nil {
1104                 t.Fatal(err)
1105         }
1106         defer resp.Body.Close()
1107 }
1108
1109 func TestBasicAuth(t *testing.T) {
1110         defer afterTest(t)
1111         tr := &recordingTransport{}
1112         client := &Client{Transport: tr}
1113
1114         url := "http://My%20User:My%20Pass@dummy.faketld/"
1115         expected := "My User:My Pass"
1116         client.Get(url)
1117
1118         if tr.req.Method != "GET" {
1119                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1120         }
1121         if tr.req.URL.String() != url {
1122                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1123         }
1124         if tr.req.Header == nil {
1125                 t.Fatalf("expected non-nil request Header")
1126         }
1127         auth := tr.req.Header.Get("Authorization")
1128         if strings.HasPrefix(auth, "Basic ") {
1129                 encoded := auth[6:]
1130                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1131                 if err != nil {
1132                         t.Fatal(err)
1133                 }
1134                 s := string(decoded)
1135                 if expected != s {
1136                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1137                 }
1138         } else {
1139                 t.Errorf("Invalid auth %q", auth)
1140         }
1141 }
1142
1143 func TestBasicAuthHeadersPreserved(t *testing.T) {
1144         defer afterTest(t)
1145         tr := &recordingTransport{}
1146         client := &Client{Transport: tr}
1147
1148         // If Authorization header is provided, username in URL should not override it
1149         url := "http://My%20User@dummy.faketld/"
1150         req, err := NewRequest("GET", url, nil)
1151         if err != nil {
1152                 t.Fatal(err)
1153         }
1154         req.SetBasicAuth("My User", "My Pass")
1155         expected := "My User:My Pass"
1156         client.Do(req)
1157
1158         if tr.req.Method != "GET" {
1159                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1160         }
1161         if tr.req.URL.String() != url {
1162                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1163         }
1164         if tr.req.Header == nil {
1165                 t.Fatalf("expected non-nil request Header")
1166         }
1167         auth := tr.req.Header.Get("Authorization")
1168         if strings.HasPrefix(auth, "Basic ") {
1169                 encoded := auth[6:]
1170                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1171                 if err != nil {
1172                         t.Fatal(err)
1173                 }
1174                 s := string(decoded)
1175                 if expected != s {
1176                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1177                 }
1178         } else {
1179                 t.Errorf("Invalid auth %q", auth)
1180         }
1181
1182 }
1183
1184 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1185 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1186
1187 func testClientTimeout(t *testing.T, h2 bool) {
1188         setParallel(t)
1189         defer afterTest(t)
1190         testDone := make(chan struct{})
1191
1192         const timeout = 100 * time.Millisecond
1193
1194         sawRoot := make(chan bool, 1)
1195         sawSlow := make(chan bool, 1)
1196         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1197                 if r.URL.Path == "/" {
1198                         sawRoot <- true
1199                         Redirect(w, r, "/slow", StatusFound)
1200                         return
1201                 }
1202                 if r.URL.Path == "/slow" {
1203                         sawSlow <- true
1204                         w.Write([]byte("Hello"))
1205                         w.(Flusher).Flush()
1206                         select {
1207                         case <-testDone:
1208                         case <-time.After(timeout * 10):
1209                         }
1210                         return
1211                 }
1212         }))
1213         defer cst.close()
1214         defer close(testDone)
1215         cst.c.Timeout = timeout
1216
1217         res, err := cst.c.Get(cst.ts.URL)
1218         if err != nil {
1219                 if strings.Contains(err.Error(), "Client.Timeout") {
1220                         t.Skip("host too slow to get fast resource in 100ms")
1221                 }
1222                 t.Fatal(err)
1223         }
1224
1225         select {
1226         case <-sawRoot:
1227                 // good.
1228         default:
1229                 t.Fatal("handler never got / request")
1230         }
1231
1232         select {
1233         case <-sawSlow:
1234                 // good.
1235         default:
1236                 t.Fatal("handler never got /slow request")
1237         }
1238
1239         errc := make(chan error, 1)
1240         go func() {
1241                 _, err := ioutil.ReadAll(res.Body)
1242                 errc <- err
1243                 res.Body.Close()
1244         }()
1245
1246         const failTime = timeout * 2
1247         select {
1248         case err := <-errc:
1249                 if err == nil {
1250                         t.Fatal("expected error from ReadAll")
1251                 }
1252                 ne, ok := err.(net.Error)
1253                 if !ok {
1254                         t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1255                 } else if !ne.Timeout() {
1256                         t.Errorf("net.Error.Timeout = false; want true")
1257                 }
1258                 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1259                         t.Errorf("error string = %q; missing timeout substring", got)
1260                 }
1261         case <-time.After(failTime):
1262                 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
1263         }
1264 }
1265
1266 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1267 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1268
1269 // Client.Timeout firing before getting to the body
1270 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1271         setParallel(t)
1272         defer afterTest(t)
1273         donec := make(chan bool, 1)
1274         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1275                 <-donec
1276         }))
1277         defer cst.close()
1278         // Note that we use a channel send here and not a close.
1279         // The race detector doesn't know that we're waiting for a timeout
1280         // and thinks that the waitgroup inside httptest.Server is added to concurrently
1281         // with us closing it. If we timed out immediately, we could close the testserver
1282         // before we entered the handler. We're not timing out immediately and there's
1283         // no way we would be done before we entered the handler, but the race detector
1284         // doesn't know this, so synchronize explicitly.
1285         defer func() { donec <- true }()
1286
1287         cst.c.Timeout = 5 * time.Millisecond
1288         res, err := cst.c.Get(cst.ts.URL)
1289         if err == nil {
1290                 res.Body.Close()
1291                 t.Fatal("got response from Get; expected error")
1292         }
1293         if _, ok := err.(*url.Error); !ok {
1294                 t.Fatalf("Got error of type %T; want *url.Error", err)
1295         }
1296         ne, ok := err.(net.Error)
1297         if !ok {
1298                 t.Fatalf("Got error of type %T; want some net.Error", err)
1299         }
1300         if !ne.Timeout() {
1301                 t.Error("net.Error.Timeout = false; want true")
1302         }
1303         if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1304                 t.Errorf("error string = %q; missing timeout substring", got)
1305         }
1306 }
1307
1308 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1309 // returned.
1310 func TestClientTimeoutCancel(t *testing.T) {
1311         setParallel(t)
1312         defer afterTest(t)
1313
1314         testDone := make(chan struct{})
1315         ctx, cancel := context.WithCancel(context.Background())
1316
1317         cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1318                 w.(Flusher).Flush()
1319                 <-testDone
1320         }))
1321         defer cst.close()
1322         defer close(testDone)
1323
1324         cst.c.Timeout = 1 * time.Hour
1325         req, _ := NewRequest("GET", cst.ts.URL, nil)
1326         req.Cancel = ctx.Done()
1327         res, err := cst.c.Do(req)
1328         if err != nil {
1329                 t.Fatal(err)
1330         }
1331         cancel()
1332         _, err = io.Copy(ioutil.Discard, res.Body)
1333         if err != ExportErrRequestCanceled {
1334                 t.Fatal("error = %v; want errRequestCanceled")
1335         }
1336 }
1337
1338 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1339 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1340 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1341         setParallel(t)
1342         defer afterTest(t)
1343         saw := make(chan string, 2)
1344         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1345                 saw <- r.RemoteAddr
1346                 if r.URL.Path == "/" {
1347                         Redirect(w, r, "/foo", StatusFound) // which includes a body
1348                 }
1349         }))
1350         defer cst.close()
1351
1352         res, err := cst.c.Get(cst.ts.URL)
1353         if err != nil {
1354                 t.Fatal(err)
1355         }
1356         _, err = ioutil.ReadAll(res.Body)
1357         res.Body.Close()
1358         if err != nil {
1359                 t.Fatal(err)
1360         }
1361
1362         var first string
1363         select {
1364         case first = <-saw:
1365         default:
1366                 t.Fatal("server didn't see a request")
1367         }
1368
1369         var second string
1370         select {
1371         case second = <-saw:
1372         default:
1373                 t.Fatal("server didn't see a second request")
1374         }
1375
1376         if first != second {
1377                 t.Fatal("server saw different client ports before & after the redirect")
1378         }
1379 }
1380
1381 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1382 type eofReaderFunc func()
1383
1384 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1385         f()
1386         return 0, io.EOF
1387 }
1388
1389 func TestReferer(t *testing.T) {
1390         tests := []struct {
1391                 lastReq, newReq string // from -> to URLs
1392                 want            string
1393         }{
1394                 // don't send user:
1395                 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1396                 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1397
1398                 // don't send a user and password:
1399                 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1400                 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1401
1402                 // nothing to do:
1403                 {"http://test.com", "http://link.com", "http://test.com"},
1404                 {"https://test.com", "https://link.com", "https://test.com"},
1405
1406                 // https to http doesn't send a referer:
1407                 {"https://test.com", "http://link.com", ""},
1408                 {"https://gopher:go@test.com", "http://link.com", ""},
1409         }
1410         for _, tt := range tests {
1411                 l, err := url.Parse(tt.lastReq)
1412                 if err != nil {
1413                         t.Fatal(err)
1414                 }
1415                 n, err := url.Parse(tt.newReq)
1416                 if err != nil {
1417                         t.Fatal(err)
1418                 }
1419                 r := ExportRefererForURL(l, n)
1420                 if r != tt.want {
1421                         t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1422                 }
1423         }
1424 }
1425
1426 // issue15577Tripper returns a Response with a redirect response
1427 // header and doesn't populate its Response.Request field.
1428 type issue15577Tripper struct{}
1429
1430 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1431         resp := &Response{
1432                 StatusCode: 303,
1433                 Header:     map[string][]string{"Location": {"http://www.example.com/"}},
1434                 Body:       ioutil.NopCloser(strings.NewReader("")),
1435         }
1436         return resp, nil
1437 }
1438
1439 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1440 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1441         c := &Client{
1442                 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1443                 Transport:     issue15577Tripper{},
1444         }
1445         // Check that this doesn't crash:
1446         c.Get("http://dummy.tld")
1447 }
1448
1449 // Issue 4800: copy (some) headers when Client follows a redirect
1450 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1451         const (
1452                 ua   = "some-agent/1.2"
1453                 xfoo = "foo-val"
1454         )
1455         var ts2URL string
1456         ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1457                 want := Header{
1458                         "User-Agent":      []string{ua},
1459                         "X-Foo":           []string{xfoo},
1460                         "Referer":         []string{ts2URL},
1461                         "Accept-Encoding": []string{"gzip"},
1462                 }
1463                 if !reflect.DeepEqual(r.Header, want) {
1464                         t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1465                 }
1466                 if t.Failed() {
1467                         w.Header().Set("Result", "got errors")
1468                 } else {
1469                         w.Header().Set("Result", "ok")
1470                 }
1471         }))
1472         defer ts1.Close()
1473         ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1474                 Redirect(w, r, ts1.URL, StatusFound)
1475         }))
1476         defer ts2.Close()
1477         ts2URL = ts2.URL
1478
1479         tr := &Transport{}
1480         defer tr.CloseIdleConnections()
1481         c := &Client{
1482                 Transport: tr,
1483                 CheckRedirect: func(r *Request, via []*Request) error {
1484                         want := Header{
1485                                 "User-Agent": []string{ua},
1486                                 "X-Foo":      []string{xfoo},
1487                                 "Referer":    []string{ts2URL},
1488                         }
1489                         if !reflect.DeepEqual(r.Header, want) {
1490                                 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1491                         }
1492                         return nil
1493                 },
1494         }
1495
1496         req, _ := NewRequest("GET", ts2.URL, nil)
1497         req.Header.Add("User-Agent", ua)
1498         req.Header.Add("X-Foo", xfoo)
1499         req.Header.Add("Cookie", "foo=bar")
1500         req.Header.Add("Authorization", "secretpassword")
1501         res, err := c.Do(req)
1502         if err != nil {
1503                 t.Fatal(err)
1504         }
1505         defer res.Body.Close()
1506         if res.StatusCode != 200 {
1507                 t.Fatal(res.Status)
1508         }
1509         if got := res.Header.Get("Result"); got != "ok" {
1510                 t.Errorf("result = %q; want ok", got)
1511         }
1512 }
1513
1514 // Issue 17494: cookies should be altered when Client follows redirects.
1515 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1516         cookieMap := func(cs []*Cookie) map[string][]string {
1517                 m := make(map[string][]string)
1518                 for _, c := range cs {
1519                         m[c.Name] = append(m[c.Name], c.Value)
1520                 }
1521                 return m
1522         }
1523
1524         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1525                 var want map[string][]string
1526                 got := cookieMap(r.Cookies())
1527
1528                 c, _ := r.Cookie("Cycle")
1529                 switch c.Value {
1530                 case "0":
1531                         want = map[string][]string{
1532                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1533                                 "Cookie2": {"OldValue2"},
1534                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1535                                 "Cookie4": {"OldValue4"},
1536                                 "Cycle":   {"0"},
1537                         }
1538                         SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1539                         SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1540                         Redirect(w, r, "/", StatusFound)
1541                 case "1":
1542                         want = map[string][]string{
1543                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1544                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1545                                 "Cookie4": {"OldValue4"},
1546                                 "Cycle":   {"1"},
1547                         }
1548                         SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1549                         SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1550                         SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1551                         Redirect(w, r, "/", StatusFound)
1552                 case "2":
1553                         want = map[string][]string{
1554                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1555                                 "Cookie3": {"NewValue3"},
1556                                 "Cookie4": {"NewValue4"},
1557                                 "Cycle":   {"2"},
1558                         }
1559                         SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1560                         SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1561                         Redirect(w, r, "/", StatusFound)
1562                 case "3":
1563                         want = map[string][]string{
1564                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1565                                 "Cookie3": {"NewValue3"},
1566                                 "Cookie4": {"NewValue4"},
1567                                 "Cookie5": {"NewValue5"},
1568                                 "Cycle":   {"3"},
1569                         }
1570                         // Don't redirect to ensure the loop ends.
1571                 default:
1572                         t.Errorf("unexpected redirect cycle")
1573                         return
1574                 }
1575
1576                 if !reflect.DeepEqual(got, want) {
1577                         t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1578                 }
1579         }))
1580         defer ts.Close()
1581
1582         tr := &Transport{}
1583         defer tr.CloseIdleConnections()
1584         jar, _ := cookiejar.New(nil)
1585         c := &Client{
1586                 Transport: tr,
1587                 Jar:       jar,
1588         }
1589
1590         u, _ := url.Parse(ts.URL)
1591         req, _ := NewRequest("GET", ts.URL, nil)
1592         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1593         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1594         req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1595         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1596         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1597         jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1598         jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1599         res, err := c.Do(req)
1600         if err != nil {
1601                 t.Fatal(err)
1602         }
1603         defer res.Body.Close()
1604         if res.StatusCode != 200 {
1605                 t.Fatal(res.Status)
1606         }
1607 }
1608
1609 // Part of Issue 4800
1610 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1611         tests := []struct {
1612                 header     string
1613                 initialURL string
1614                 destURL    string
1615                 want       bool
1616         }{
1617                 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1618                 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1619
1620                 // Sensitive headers:
1621                 {"cookie", "http://foo.com/", "http://bar.com/", false},
1622                 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1623                 {"authorization", "http://foo.com/", "http://bar.com/", false},
1624                 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1625
1626                 // But subdomains should work:
1627                 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1628                 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1629                 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1630                 // TODO(bradfitz): make this test work, once issue 16142 is fixed:
1631                 // {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1632         }
1633         for i, tt := range tests {
1634                 u0, err := url.Parse(tt.initialURL)
1635                 if err != nil {
1636                         t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1637                         continue
1638                 }
1639                 u1, err := url.Parse(tt.destURL)
1640                 if err != nil {
1641                         t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1642                         continue
1643                 }
1644                 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1645                 if got != tt.want {
1646                         t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1647                                 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1648                 }
1649         }
1650 }
1651
1652 func TestClientRedirectTypes(t *testing.T) {
1653         setParallel(t)
1654         defer afterTest(t)
1655
1656         tests := [...]struct {
1657                 method       string
1658                 serverStatus int
1659                 wantMethod   string // desired subsequent client method
1660         }{
1661                 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1662                 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1663                 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1664                 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1665                 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1666
1667                 5: {method: "HEAD", serverStatus: 301, wantMethod: "GET"},
1668                 6: {method: "HEAD", serverStatus: 302, wantMethod: "GET"},
1669                 7: {method: "HEAD", serverStatus: 303, wantMethod: "GET"},
1670                 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1671                 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1672
1673                 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1674                 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1675                 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1676                 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1677                 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1678
1679                 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1680                 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1681                 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1682                 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1683                 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1684
1685                 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1686                 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1687                 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1688                 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1689                 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1690
1691                 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1692                 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1693                 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1694                 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1695                 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1696         }
1697
1698         handlerc := make(chan HandlerFunc, 1)
1699
1700         ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1701                 h := <-handlerc
1702                 h(rw, req)
1703         }))
1704         defer ts.Close()
1705
1706         tr := &Transport{}
1707         defer tr.CloseIdleConnections()
1708
1709         for i, tt := range tests {
1710                 handlerc <- func(w ResponseWriter, r *Request) {
1711                         w.Header().Set("Location", ts.URL)
1712                         w.WriteHeader(tt.serverStatus)
1713                 }
1714
1715                 req, err := NewRequest(tt.method, ts.URL, nil)
1716                 if err != nil {
1717                         t.Errorf("#%d: NewRequest: %v", i, err)
1718                         continue
1719                 }
1720
1721                 c := &Client{Transport: tr}
1722                 c.CheckRedirect = func(req *Request, via []*Request) error {
1723                         if got, want := req.Method, tt.wantMethod; got != want {
1724                                 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1725                         }
1726                         handlerc <- func(rw ResponseWriter, req *Request) {
1727                                 // TODO: Check that the body is valid when we do 307 and 308 support
1728                         }
1729                         return nil
1730                 }
1731
1732                 res, err := c.Do(req)
1733                 if err != nil {
1734                         t.Errorf("#%d: Response: %v", i, err)
1735                         continue
1736                 }
1737
1738                 res.Body.Close()
1739         }
1740 }