]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/client_test.go
net/http: skip TestClientTimeout_Headers_h{1,2} on windows/arm and windows/arm64
[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         "encoding/base64"
14         "errors"
15         "fmt"
16         "internal/testenv"
17         "io"
18         "log"
19         "net"
20         . "net/http"
21         "net/http/cookiejar"
22         "net/http/httptest"
23         "net/url"
24         "reflect"
25         "runtime"
26         "strconv"
27         "strings"
28         "sync"
29         "sync/atomic"
30         "testing"
31         "time"
32 )
33
34 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
35         w.Header().Set("Last-Modified", "sometime")
36         fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
37 })
38
39 // pedanticReadAll works like io.ReadAll but additionally
40 // verifies that r obeys the documented io.Reader contract.
41 func pedanticReadAll(r io.Reader) (b []byte, err error) {
42         var bufa [64]byte
43         buf := bufa[:]
44         for {
45                 n, err := r.Read(buf)
46                 if n == 0 && err == nil {
47                         return nil, fmt.Errorf("Read: n=0 with err=nil")
48                 }
49                 b = append(b, buf[:n]...)
50                 if err == io.EOF {
51                         n, err := r.Read(buf)
52                         if n != 0 || err != io.EOF {
53                                 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
54                         }
55                         return b, nil
56                 }
57                 if err != nil {
58                         return b, err
59                 }
60         }
61 }
62
63 type chanWriter chan string
64
65 func (w chanWriter) Write(p []byte) (n int, err error) {
66         w <- string(p)
67         return len(p), nil
68 }
69
70 func TestClient(t *testing.T) {
71         setParallel(t)
72         defer afterTest(t)
73         ts := httptest.NewServer(robotsTxtHandler)
74         defer ts.Close()
75
76         c := ts.Client()
77         r, err := c.Get(ts.URL)
78         var b []byte
79         if err == nil {
80                 b, err = pedanticReadAll(r.Body)
81                 r.Body.Close()
82         }
83         if err != nil {
84                 t.Error(err)
85         } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
86                 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
87         }
88 }
89
90 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
91 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
92
93 func testClientHead(t *testing.T, h2 bool) {
94         defer afterTest(t)
95         cst := newClientServerTest(t, h2, robotsTxtHandler)
96         defer cst.close()
97
98         r, err := cst.c.Head(cst.ts.URL)
99         if err != nil {
100                 t.Fatal(err)
101         }
102         if _, ok := r.Header["Last-Modified"]; !ok {
103                 t.Error("Last-Modified header not found.")
104         }
105 }
106
107 type recordingTransport struct {
108         req *Request
109 }
110
111 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
112         t.req = req
113         return nil, errors.New("dummy impl")
114 }
115
116 func TestGetRequestFormat(t *testing.T) {
117         setParallel(t)
118         defer afterTest(t)
119         tr := &recordingTransport{}
120         client := &Client{Transport: tr}
121         url := "http://dummy.faketld/"
122         client.Get(url) // Note: doesn't hit network
123         if tr.req.Method != "GET" {
124                 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
125         }
126         if tr.req.URL.String() != url {
127                 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
128         }
129         if tr.req.Header == nil {
130                 t.Errorf("expected non-nil request Header")
131         }
132 }
133
134 func TestPostRequestFormat(t *testing.T) {
135         defer afterTest(t)
136         tr := &recordingTransport{}
137         client := &Client{Transport: tr}
138
139         url := "http://dummy.faketld/"
140         json := `{"key":"value"}`
141         b := strings.NewReader(json)
142         client.Post(url, "application/json", b) // Note: doesn't hit network
143
144         if tr.req.Method != "POST" {
145                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
146         }
147         if tr.req.URL.String() != url {
148                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
149         }
150         if tr.req.Header == nil {
151                 t.Fatalf("expected non-nil request Header")
152         }
153         if tr.req.Close {
154                 t.Error("got Close true, want false")
155         }
156         if g, e := tr.req.ContentLength, int64(len(json)); g != e {
157                 t.Errorf("got ContentLength %d, want %d", g, e)
158         }
159 }
160
161 func TestPostFormRequestFormat(t *testing.T) {
162         defer afterTest(t)
163         tr := &recordingTransport{}
164         client := &Client{Transport: tr}
165
166         urlStr := "http://dummy.faketld/"
167         form := make(url.Values)
168         form.Set("foo", "bar")
169         form.Add("foo", "bar2")
170         form.Set("bar", "baz")
171         client.PostForm(urlStr, form) // Note: doesn't hit network
172
173         if tr.req.Method != "POST" {
174                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
175         }
176         if tr.req.URL.String() != urlStr {
177                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
178         }
179         if tr.req.Header == nil {
180                 t.Fatalf("expected non-nil request Header")
181         }
182         if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
183                 t.Errorf("got Content-Type %q, want %q", g, e)
184         }
185         if tr.req.Close {
186                 t.Error("got Close true, want false")
187         }
188         // Depending on map iteration, body can be either of these.
189         expectedBody := "foo=bar&foo=bar2&bar=baz"
190         expectedBody1 := "bar=baz&foo=bar&foo=bar2"
191         if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
192                 t.Errorf("got ContentLength %d, want %d", g, e)
193         }
194         bodyb, err := io.ReadAll(tr.req.Body)
195         if err != nil {
196                 t.Fatalf("ReadAll on req.Body: %v", err)
197         }
198         if g := string(bodyb); g != expectedBody && g != expectedBody1 {
199                 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
200         }
201 }
202
203 func TestClientRedirects(t *testing.T) {
204         setParallel(t)
205         defer afterTest(t)
206         var ts *httptest.Server
207         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
208                 n, _ := strconv.Atoi(r.FormValue("n"))
209                 // Test Referer header. (7 is arbitrary position to test at)
210                 if n == 7 {
211                         if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
212                                 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
213                         }
214                 }
215                 if n < 15 {
216                         Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
217                         return
218                 }
219                 fmt.Fprintf(w, "n=%d", n)
220         }))
221         defer ts.Close()
222
223         c := ts.Client()
224         _, err := c.Get(ts.URL)
225         if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
226                 t.Errorf("with default client Get, expected error %q, got %q", e, g)
227         }
228
229         // HEAD request should also have the ability to follow redirects.
230         _, err = c.Head(ts.URL)
231         if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
232                 t.Errorf("with default client Head, expected error %q, got %q", e, g)
233         }
234
235         // Do should also follow redirects.
236         greq, _ := NewRequest("GET", ts.URL, nil)
237         _, err = c.Do(greq)
238         if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
239                 t.Errorf("with default client Do, expected error %q, got %q", e, g)
240         }
241
242         // Requests with an empty Method should also redirect (Issue 12705)
243         greq.Method = ""
244         _, err = c.Do(greq)
245         if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
246                 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
247         }
248
249         var checkErr error
250         var lastVia []*Request
251         var lastReq *Request
252         c.CheckRedirect = func(req *Request, via []*Request) error {
253                 lastReq = req
254                 lastVia = via
255                 return checkErr
256         }
257         res, err := c.Get(ts.URL)
258         if err != nil {
259                 t.Fatalf("Get error: %v", err)
260         }
261         res.Body.Close()
262         finalURL := res.Request.URL.String()
263         if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
264                 t.Errorf("with custom client, expected error %q, got %q", e, g)
265         }
266         if !strings.HasSuffix(finalURL, "/?n=15") {
267                 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
268         }
269         if e, g := 15, len(lastVia); e != g {
270                 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
271         }
272
273         // Test that Request.Cancel is propagated between requests (Issue 14053)
274         creq, _ := NewRequest("HEAD", ts.URL, nil)
275         cancel := make(chan struct{})
276         creq.Cancel = cancel
277         if _, err := c.Do(creq); err != nil {
278                 t.Fatal(err)
279         }
280         if lastReq == nil {
281                 t.Fatal("didn't see redirect")
282         }
283         if lastReq.Cancel != cancel {
284                 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
285         }
286
287         checkErr = errors.New("no redirects allowed")
288         res, err = c.Get(ts.URL)
289         if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
290                 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
291         }
292         if res == nil {
293                 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
294         }
295         res.Body.Close()
296         if res.Header.Get("Location") == "" {
297                 t.Errorf("no Location header in Response")
298         }
299 }
300
301 // Tests that Client redirects' contexts are derived from the original request's context.
302 func TestClientRedirectContext(t *testing.T) {
303         setParallel(t)
304         defer afterTest(t)
305         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
306                 Redirect(w, r, "/", StatusTemporaryRedirect)
307         }))
308         defer ts.Close()
309
310         ctx, cancel := context.WithCancel(context.Background())
311         c := ts.Client()
312         c.CheckRedirect = func(req *Request, via []*Request) error {
313                 cancel()
314                 select {
315                 case <-req.Context().Done():
316                         return nil
317                 case <-time.After(5 * time.Second):
318                         return errors.New("redirected request's context never expired after root request canceled")
319                 }
320         }
321         req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
322         _, err := c.Do(req)
323         ue, ok := err.(*url.Error)
324         if !ok {
325                 t.Fatalf("got error %T; want *url.Error", err)
326         }
327         if ue.Err != context.Canceled {
328                 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
329         }
330 }
331
332 type redirectTest struct {
333         suffix       string
334         want         int // response code
335         redirectBody string
336 }
337
338 func TestPostRedirects(t *testing.T) {
339         postRedirectTests := []redirectTest{
340                 {"/", 200, "first"},
341                 {"/?code=301&next=302", 200, "c301"},
342                 {"/?code=302&next=302", 200, "c302"},
343                 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
344                 {"/?code=304", 304, "c304"},
345                 {"/?code=305", 305, "c305"},
346                 {"/?code=307&next=303,308,302", 200, "c307"},
347                 {"/?code=308&next=302,301", 200, "c308"},
348                 {"/?code=404", 404, "c404"},
349         }
350
351         wantSegments := []string{
352                 `POST / "first"`,
353                 `POST /?code=301&next=302 "c301"`,
354                 `GET /?code=302 ""`,
355                 `GET / ""`,
356                 `POST /?code=302&next=302 "c302"`,
357                 `GET /?code=302 ""`,
358                 `GET / ""`,
359                 `POST /?code=303&next=301 "c303wc301"`,
360                 `GET /?code=301 ""`,
361                 `GET / ""`,
362                 `POST /?code=304 "c304"`,
363                 `POST /?code=305 "c305"`,
364                 `POST /?code=307&next=303,308,302 "c307"`,
365                 `POST /?code=303&next=308,302 "c307"`,
366                 `GET /?code=308&next=302 ""`,
367                 `GET /?code=302 "c307"`,
368                 `GET / ""`,
369                 `POST /?code=308&next=302,301 "c308"`,
370                 `POST /?code=302&next=301 "c308"`,
371                 `GET /?code=301 ""`,
372                 `GET / ""`,
373                 `POST /?code=404 "c404"`,
374         }
375         want := strings.Join(wantSegments, "\n")
376         testRedirectsByMethod(t, "POST", postRedirectTests, want)
377 }
378
379 func TestDeleteRedirects(t *testing.T) {
380         deleteRedirectTests := []redirectTest{
381                 {"/", 200, "first"},
382                 {"/?code=301&next=302,308", 200, "c301"},
383                 {"/?code=302&next=302", 200, "c302"},
384                 {"/?code=303", 200, "c303"},
385                 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
386                 {"/?code=308&next=307", 200, "c308"},
387                 {"/?code=404", 404, "c404"},
388         }
389
390         wantSegments := []string{
391                 `DELETE / "first"`,
392                 `DELETE /?code=301&next=302,308 "c301"`,
393                 `GET /?code=302&next=308 ""`,
394                 `GET /?code=308 ""`,
395                 `GET / "c301"`,
396                 `DELETE /?code=302&next=302 "c302"`,
397                 `GET /?code=302 ""`,
398                 `GET / ""`,
399                 `DELETE /?code=303 "c303"`,
400                 `GET / ""`,
401                 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
402                 `DELETE /?code=301&next=308,303,302,304 "c307"`,
403                 `GET /?code=308&next=303,302,304 ""`,
404                 `GET /?code=303&next=302,304 "c307"`,
405                 `GET /?code=302&next=304 ""`,
406                 `GET /?code=304 ""`,
407                 `DELETE /?code=308&next=307 "c308"`,
408                 `DELETE /?code=307 "c308"`,
409                 `DELETE / "c308"`,
410                 `DELETE /?code=404 "c404"`,
411         }
412         want := strings.Join(wantSegments, "\n")
413         testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
414 }
415
416 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
417         defer afterTest(t)
418         var log struct {
419                 sync.Mutex
420                 bytes.Buffer
421         }
422         var ts *httptest.Server
423         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
424                 log.Lock()
425                 slurp, _ := io.ReadAll(r.Body)
426                 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
427                 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
428                         fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
429                 }
430                 log.WriteByte('\n')
431                 log.Unlock()
432                 urlQuery := r.URL.Query()
433                 if v := urlQuery.Get("code"); v != "" {
434                         location := ts.URL
435                         if final := urlQuery.Get("next"); final != "" {
436                                 first, rest, _ := strings.Cut(final, ",")
437                                 location = fmt.Sprintf("%s?code=%s", location, first)
438                                 if rest != "" {
439                                         location = fmt.Sprintf("%s&next=%s", location, rest)
440                                 }
441                         }
442                         code, _ := strconv.Atoi(v)
443                         if code/100 == 3 {
444                                 w.Header().Set("Location", location)
445                         }
446                         w.WriteHeader(code)
447                 }
448         }))
449         defer ts.Close()
450
451         c := ts.Client()
452         for _, tt := range table {
453                 content := tt.redirectBody
454                 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
455                 req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
456                 res, err := c.Do(req)
457
458                 if err != nil {
459                         t.Fatal(err)
460                 }
461                 if res.StatusCode != tt.want {
462                         t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
463                 }
464         }
465         log.Lock()
466         got := log.String()
467         log.Unlock()
468
469         got = strings.TrimSpace(got)
470         want = strings.TrimSpace(want)
471
472         if got != want {
473                 got, want, lines := removeCommonLines(got, want)
474                 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
475         }
476 }
477
478 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
479         for {
480                 nl := strings.IndexByte(a, '\n')
481                 if nl < 0 {
482                         return a, b, commonLines
483                 }
484                 line := a[:nl+1]
485                 if !strings.HasPrefix(b, line) {
486                         return a, b, commonLines
487                 }
488                 commonLines++
489                 a = a[len(line):]
490                 b = b[len(line):]
491         }
492 }
493
494 func TestClientRedirectUseResponse(t *testing.T) {
495         setParallel(t)
496         defer afterTest(t)
497         const body = "Hello, world."
498         var ts *httptest.Server
499         ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
500                 if strings.Contains(r.URL.Path, "/other") {
501                         io.WriteString(w, "wrong body")
502                 } else {
503                         w.Header().Set("Location", ts.URL+"/other")
504                         w.WriteHeader(StatusFound)
505                         io.WriteString(w, body)
506                 }
507         }))
508         defer ts.Close()
509
510         c := ts.Client()
511         c.CheckRedirect = func(req *Request, via []*Request) error {
512                 if req.Response == nil {
513                         t.Error("expected non-nil Request.Response")
514                 }
515                 return ErrUseLastResponse
516         }
517         res, err := c.Get(ts.URL)
518         if err != nil {
519                 t.Fatal(err)
520         }
521         if res.StatusCode != StatusFound {
522                 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
523         }
524         defer res.Body.Close()
525         slurp, err := io.ReadAll(res.Body)
526         if err != nil {
527                 t.Fatal(err)
528         }
529         if string(slurp) != body {
530                 t.Errorf("body = %q; want %q", slurp, body)
531         }
532 }
533
534 // Issue 17773: don't follow a 308 (or 307) if the response doesn't
535 // have a Location header.
536 func TestClientRedirect308NoLocation(t *testing.T) {
537         setParallel(t)
538         defer afterTest(t)
539         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
540                 w.Header().Set("Foo", "Bar")
541                 w.WriteHeader(308)
542         }))
543         defer ts.Close()
544         c := ts.Client()
545         res, err := c.Get(ts.URL)
546         if err != nil {
547                 t.Fatal(err)
548         }
549         res.Body.Close()
550         if res.StatusCode != 308 {
551                 t.Errorf("status = %d; want %d", res.StatusCode, 308)
552         }
553         if got := res.Header.Get("Foo"); got != "Bar" {
554                 t.Errorf("Foo header = %q; want Bar", got)
555         }
556 }
557
558 // Don't follow a 307/308 if we can't resent the request body.
559 func TestClientRedirect308NoGetBody(t *testing.T) {
560         setParallel(t)
561         defer afterTest(t)
562         const fakeURL = "https://localhost:1234/" // won't be hit
563         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
564                 w.Header().Set("Location", fakeURL)
565                 w.WriteHeader(308)
566         }))
567         defer ts.Close()
568         req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
569         if err != nil {
570                 t.Fatal(err)
571         }
572         c := ts.Client()
573         req.GetBody = nil // so it can't rewind.
574         res, err := c.Do(req)
575         if err != nil {
576                 t.Fatal(err)
577         }
578         res.Body.Close()
579         if res.StatusCode != 308 {
580                 t.Errorf("status = %d; want %d", res.StatusCode, 308)
581         }
582         if got := res.Header.Get("Location"); got != fakeURL {
583                 t.Errorf("Location header = %q; want %q", got, fakeURL)
584         }
585 }
586
587 var expectedCookies = []*Cookie{
588         {Name: "ChocolateChip", Value: "tasty"},
589         {Name: "First", Value: "Hit"},
590         {Name: "Second", Value: "Hit"},
591 }
592
593 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
594         for _, cookie := range r.Cookies() {
595                 SetCookie(w, cookie)
596         }
597         if r.URL.Path == "/" {
598                 SetCookie(w, expectedCookies[1])
599                 Redirect(w, r, "/second", StatusMovedPermanently)
600         } else {
601                 SetCookie(w, expectedCookies[2])
602                 w.Write([]byte("hello"))
603         }
604 })
605
606 func TestClientSendsCookieFromJar(t *testing.T) {
607         defer afterTest(t)
608         tr := &recordingTransport{}
609         client := &Client{Transport: tr}
610         client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
611         us := "http://dummy.faketld/"
612         u, _ := url.Parse(us)
613         client.Jar.SetCookies(u, expectedCookies)
614
615         client.Get(us) // Note: doesn't hit network
616         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
617
618         client.Head(us) // Note: doesn't hit network
619         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
620
621         client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
622         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
623
624         client.PostForm(us, url.Values{}) // Note: doesn't hit network
625         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
626
627         req, _ := NewRequest("GET", us, nil)
628         client.Do(req) // Note: doesn't hit network
629         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
630
631         req, _ = NewRequest("POST", us, nil)
632         client.Do(req) // Note: doesn't hit network
633         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
634 }
635
636 // Just enough correctness for our redirect tests. Uses the URL.Host as the
637 // scope of all cookies.
638 type TestJar struct {
639         m      sync.Mutex
640         perURL map[string][]*Cookie
641 }
642
643 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
644         j.m.Lock()
645         defer j.m.Unlock()
646         if j.perURL == nil {
647                 j.perURL = make(map[string][]*Cookie)
648         }
649         j.perURL[u.Host] = cookies
650 }
651
652 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
653         j.m.Lock()
654         defer j.m.Unlock()
655         return j.perURL[u.Host]
656 }
657
658 func TestRedirectCookiesJar(t *testing.T) {
659         setParallel(t)
660         defer afterTest(t)
661         var ts *httptest.Server
662         ts = httptest.NewServer(echoCookiesRedirectHandler)
663         defer ts.Close()
664         c := ts.Client()
665         c.Jar = new(TestJar)
666         u, _ := url.Parse(ts.URL)
667         c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
668         resp, err := c.Get(ts.URL)
669         if err != nil {
670                 t.Fatalf("Get: %v", err)
671         }
672         resp.Body.Close()
673         matchReturnedCookies(t, expectedCookies, resp.Cookies())
674 }
675
676 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
677         if len(given) != len(expected) {
678                 t.Logf("Received cookies: %v", given)
679                 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
680         }
681         for _, ec := range expected {
682                 foundC := false
683                 for _, c := range given {
684                         if ec.Name == c.Name && ec.Value == c.Value {
685                                 foundC = true
686                                 break
687                         }
688                 }
689                 if !foundC {
690                         t.Errorf("Missing cookie %v", ec)
691                 }
692         }
693 }
694
695 func TestJarCalls(t *testing.T) {
696         defer afterTest(t)
697         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
698                 pathSuffix := r.RequestURI[1:]
699                 if r.RequestURI == "/nosetcookie" {
700                         return // don't set cookies for this path
701                 }
702                 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
703                 if r.RequestURI == "/" {
704                         Redirect(w, r, "http://secondhost.fake/secondpath", 302)
705                 }
706         }))
707         defer ts.Close()
708         jar := new(RecordingJar)
709         c := ts.Client()
710         c.Jar = jar
711         c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
712                 return net.Dial("tcp", ts.Listener.Addr().String())
713         }
714         _, err := c.Get("http://firsthost.fake/")
715         if err != nil {
716                 t.Fatal(err)
717         }
718         _, err = c.Get("http://firsthost.fake/nosetcookie")
719         if err != nil {
720                 t.Fatal(err)
721         }
722         got := jar.log.String()
723         want := `Cookies("http://firsthost.fake/")
724 SetCookie("http://firsthost.fake/", [name=val])
725 Cookies("http://secondhost.fake/secondpath")
726 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
727 Cookies("http://firsthost.fake/nosetcookie")
728 `
729         if got != want {
730                 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
731         }
732 }
733
734 // RecordingJar keeps a log of calls made to it, without
735 // tracking any cookies.
736 type RecordingJar struct {
737         mu  sync.Mutex
738         log bytes.Buffer
739 }
740
741 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
742         j.logf("SetCookie(%q, %v)\n", u, cookies)
743 }
744
745 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
746         j.logf("Cookies(%q)\n", u)
747         return nil
748 }
749
750 func (j *RecordingJar) logf(format string, args ...any) {
751         j.mu.Lock()
752         defer j.mu.Unlock()
753         fmt.Fprintf(&j.log, format, args...)
754 }
755
756 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
757 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
758
759 func testStreamingGet(t *testing.T, h2 bool) {
760         defer afterTest(t)
761         say := make(chan string)
762         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
763                 w.(Flusher).Flush()
764                 for str := range say {
765                         w.Write([]byte(str))
766                         w.(Flusher).Flush()
767                 }
768         }))
769         defer cst.close()
770
771         c := cst.c
772         res, err := c.Get(cst.ts.URL)
773         if err != nil {
774                 t.Fatal(err)
775         }
776         var buf [10]byte
777         for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
778                 say <- str
779                 n, err := io.ReadFull(res.Body, buf[0:len(str)])
780                 if err != nil {
781                         t.Fatalf("ReadFull on %q: %v", str, err)
782                 }
783                 if n != len(str) {
784                         t.Fatalf("Receiving %q, only read %d bytes", str, n)
785                 }
786                 got := string(buf[0:n])
787                 if got != str {
788                         t.Fatalf("Expected %q, got %q", str, got)
789                 }
790         }
791         close(say)
792         _, err = io.ReadFull(res.Body, buf[0:1])
793         if err != io.EOF {
794                 t.Fatalf("at end expected EOF, got %v", err)
795         }
796 }
797
798 type writeCountingConn struct {
799         net.Conn
800         count *int
801 }
802
803 func (c *writeCountingConn) Write(p []byte) (int, error) {
804         *c.count++
805         return c.Conn.Write(p)
806 }
807
808 // TestClientWrites verifies that client requests are buffered and we
809 // don't send a TCP packet per line of the http request + body.
810 func TestClientWrites(t *testing.T) {
811         defer afterTest(t)
812         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
813         }))
814         defer ts.Close()
815
816         writes := 0
817         dialer := func(netz string, addr string) (net.Conn, error) {
818                 c, err := net.Dial(netz, addr)
819                 if err == nil {
820                         c = &writeCountingConn{c, &writes}
821                 }
822                 return c, err
823         }
824         c := ts.Client()
825         c.Transport.(*Transport).Dial = dialer
826
827         _, err := c.Get(ts.URL)
828         if err != nil {
829                 t.Fatal(err)
830         }
831         if writes != 1 {
832                 t.Errorf("Get request did %d Write calls, want 1", writes)
833         }
834
835         writes = 0
836         _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
837         if err != nil {
838                 t.Fatal(err)
839         }
840         if writes != 1 {
841                 t.Errorf("Post request did %d Write calls, want 1", writes)
842         }
843 }
844
845 func TestClientInsecureTransport(t *testing.T) {
846         setParallel(t)
847         defer afterTest(t)
848         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
849                 w.Write([]byte("Hello"))
850         }))
851         errc := make(chanWriter, 10) // but only expecting 1
852         ts.Config.ErrorLog = log.New(errc, "", 0)
853         defer ts.Close()
854
855         // TODO(bradfitz): add tests for skipping hostname checks too?
856         // would require a new cert for testing, and probably
857         // redundant with these tests.
858         c := ts.Client()
859         for _, insecure := range []bool{true, false} {
860                 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
861                         InsecureSkipVerify: insecure,
862                 }
863                 res, err := c.Get(ts.URL)
864                 if (err == nil) != insecure {
865                         t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
866                 }
867                 if res != nil {
868                         res.Body.Close()
869                 }
870         }
871
872         select {
873         case v := <-errc:
874                 if !strings.Contains(v, "TLS handshake error") {
875                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
876                 }
877         case <-time.After(5 * time.Second):
878                 t.Errorf("timeout waiting for logged error")
879         }
880
881 }
882
883 func TestClientErrorWithRequestURI(t *testing.T) {
884         defer afterTest(t)
885         req, _ := NewRequest("GET", "http://localhost:1234/", nil)
886         req.RequestURI = "/this/field/is/illegal/and/should/error/"
887         _, err := DefaultClient.Do(req)
888         if err == nil {
889                 t.Fatalf("expected an error")
890         }
891         if !strings.Contains(err.Error(), "RequestURI") {
892                 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
893         }
894 }
895
896 func TestClientWithCorrectTLSServerName(t *testing.T) {
897         defer afterTest(t)
898
899         const serverName = "example.com"
900         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
901                 if r.TLS.ServerName != serverName {
902                         t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
903                 }
904         }))
905         defer ts.Close()
906
907         c := ts.Client()
908         c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
909         if _, err := c.Get(ts.URL); err != nil {
910                 t.Fatalf("expected successful TLS connection, got error: %v", err)
911         }
912 }
913
914 func TestClientWithIncorrectTLSServerName(t *testing.T) {
915         defer afterTest(t)
916         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
917         defer ts.Close()
918         errc := make(chanWriter, 10) // but only expecting 1
919         ts.Config.ErrorLog = log.New(errc, "", 0)
920
921         c := ts.Client()
922         c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
923         _, err := c.Get(ts.URL)
924         if err == nil {
925                 t.Fatalf("expected an error")
926         }
927         if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
928                 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
929         }
930         select {
931         case v := <-errc:
932                 if !strings.Contains(v, "TLS handshake error") {
933                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
934                 }
935         case <-time.After(5 * time.Second):
936                 t.Errorf("timeout waiting for logged error")
937         }
938 }
939
940 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
941 // when not empty.
942 //
943 // tls.Config.ServerName (non-empty, set to "example.com") takes
944 // precedence over "some-other-host.tld" which previously incorrectly
945 // took precedence. We don't actually connect to (or even resolve)
946 // "some-other-host.tld", though, because of the Transport.Dial hook.
947 //
948 // The httptest.Server has a cert with "example.com" as its name.
949 func TestTransportUsesTLSConfigServerName(t *testing.T) {
950         defer afterTest(t)
951         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
952                 w.Write([]byte("Hello"))
953         }))
954         defer ts.Close()
955
956         c := ts.Client()
957         tr := c.Transport.(*Transport)
958         tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
959         tr.Dial = func(netw, addr string) (net.Conn, error) {
960                 return net.Dial(netw, ts.Listener.Addr().String())
961         }
962         res, err := c.Get("https://some-other-host.tld/")
963         if err != nil {
964                 t.Fatal(err)
965         }
966         res.Body.Close()
967 }
968
969 func TestResponseSetsTLSConnectionState(t *testing.T) {
970         defer afterTest(t)
971         ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
972                 w.Write([]byte("Hello"))
973         }))
974         defer ts.Close()
975
976         c := ts.Client()
977         tr := c.Transport.(*Transport)
978         tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
979         tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
980         tr.Dial = func(netw, addr string) (net.Conn, error) {
981                 return net.Dial(netw, ts.Listener.Addr().String())
982         }
983         res, err := c.Get("https://example.com/")
984         if err != nil {
985                 t.Fatal(err)
986         }
987         defer res.Body.Close()
988         if res.TLS == nil {
989                 t.Fatal("Response didn't set TLS Connection State.")
990         }
991         if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
992                 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
993         }
994 }
995
996 // Check that an HTTPS client can interpret a particular TLS error
997 // to determine that the server is speaking HTTP.
998 // See golang.org/issue/11111.
999 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
1000         defer afterTest(t)
1001         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
1002         ts.Config.ErrorLog = quietLog
1003         defer ts.Close()
1004
1005         _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
1006         if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
1007                 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
1008         }
1009 }
1010
1011 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
1012 func TestClientHeadContentLength_h1(t *testing.T) {
1013         testClientHeadContentLength(t, h1Mode)
1014 }
1015
1016 func TestClientHeadContentLength_h2(t *testing.T) {
1017         testClientHeadContentLength(t, h2Mode)
1018 }
1019
1020 func testClientHeadContentLength(t *testing.T, h2 bool) {
1021         defer afterTest(t)
1022         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1023                 if v := r.FormValue("cl"); v != "" {
1024                         w.Header().Set("Content-Length", v)
1025                 }
1026         }))
1027         defer cst.close()
1028         tests := []struct {
1029                 suffix string
1030                 want   int64
1031         }{
1032                 {"/?cl=1234", 1234},
1033                 {"/?cl=0", 0},
1034                 {"", -1},
1035         }
1036         for _, tt := range tests {
1037                 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1038                 res, err := cst.c.Do(req)
1039                 if err != nil {
1040                         t.Fatal(err)
1041                 }
1042                 if res.ContentLength != tt.want {
1043                         t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1044                 }
1045                 bs, err := io.ReadAll(res.Body)
1046                 if err != nil {
1047                         t.Fatal(err)
1048                 }
1049                 if len(bs) != 0 {
1050                         t.Errorf("Unexpected content: %q", bs)
1051                 }
1052         }
1053 }
1054
1055 func TestEmptyPasswordAuth(t *testing.T) {
1056         setParallel(t)
1057         defer afterTest(t)
1058         gopher := "gopher"
1059         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1060                 auth := r.Header.Get("Authorization")
1061                 if strings.HasPrefix(auth, "Basic ") {
1062                         encoded := auth[6:]
1063                         decoded, err := base64.StdEncoding.DecodeString(encoded)
1064                         if err != nil {
1065                                 t.Fatal(err)
1066                         }
1067                         expected := gopher + ":"
1068                         s := string(decoded)
1069                         if expected != s {
1070                                 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1071                         }
1072                 } else {
1073                         t.Errorf("Invalid auth %q", auth)
1074                 }
1075         }))
1076         defer ts.Close()
1077         req, err := NewRequest("GET", ts.URL, nil)
1078         if err != nil {
1079                 t.Fatal(err)
1080         }
1081         req.URL.User = url.User(gopher)
1082         c := ts.Client()
1083         resp, err := c.Do(req)
1084         if err != nil {
1085                 t.Fatal(err)
1086         }
1087         defer resp.Body.Close()
1088 }
1089
1090 func TestBasicAuth(t *testing.T) {
1091         defer afterTest(t)
1092         tr := &recordingTransport{}
1093         client := &Client{Transport: tr}
1094
1095         url := "http://My%20User:My%20Pass@dummy.faketld/"
1096         expected := "My User:My Pass"
1097         client.Get(url)
1098
1099         if tr.req.Method != "GET" {
1100                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1101         }
1102         if tr.req.URL.String() != url {
1103                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1104         }
1105         if tr.req.Header == nil {
1106                 t.Fatalf("expected non-nil request Header")
1107         }
1108         auth := tr.req.Header.Get("Authorization")
1109         if strings.HasPrefix(auth, "Basic ") {
1110                 encoded := auth[6:]
1111                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1112                 if err != nil {
1113                         t.Fatal(err)
1114                 }
1115                 s := string(decoded)
1116                 if expected != s {
1117                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1118                 }
1119         } else {
1120                 t.Errorf("Invalid auth %q", auth)
1121         }
1122 }
1123
1124 func TestBasicAuthHeadersPreserved(t *testing.T) {
1125         defer afterTest(t)
1126         tr := &recordingTransport{}
1127         client := &Client{Transport: tr}
1128
1129         // If Authorization header is provided, username in URL should not override it
1130         url := "http://My%20User@dummy.faketld/"
1131         req, err := NewRequest("GET", url, nil)
1132         if err != nil {
1133                 t.Fatal(err)
1134         }
1135         req.SetBasicAuth("My User", "My Pass")
1136         expected := "My User:My Pass"
1137         client.Do(req)
1138
1139         if tr.req.Method != "GET" {
1140                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1141         }
1142         if tr.req.URL.String() != url {
1143                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1144         }
1145         if tr.req.Header == nil {
1146                 t.Fatalf("expected non-nil request Header")
1147         }
1148         auth := tr.req.Header.Get("Authorization")
1149         if strings.HasPrefix(auth, "Basic ") {
1150                 encoded := auth[6:]
1151                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1152                 if err != nil {
1153                         t.Fatal(err)
1154                 }
1155                 s := string(decoded)
1156                 if expected != s {
1157                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1158                 }
1159         } else {
1160                 t.Errorf("Invalid auth %q", auth)
1161         }
1162
1163 }
1164
1165 func TestStripPasswordFromError(t *testing.T) {
1166         client := &Client{Transport: &recordingTransport{}}
1167         testCases := []struct {
1168                 desc string
1169                 in   string
1170                 out  string
1171         }{
1172                 {
1173                         desc: "Strip password from error message",
1174                         in:   "http://user:password@dummy.faketld/",
1175                         out:  `Get "http://user:***@dummy.faketld/": dummy impl`,
1176                 },
1177                 {
1178                         desc: "Don't Strip password from domain name",
1179                         in:   "http://user:password@password.faketld/",
1180                         out:  `Get "http://user:***@password.faketld/": dummy impl`,
1181                 },
1182                 {
1183                         desc: "Don't Strip password from path",
1184                         in:   "http://user:password@dummy.faketld/password",
1185                         out:  `Get "http://user:***@dummy.faketld/password": dummy impl`,
1186                 },
1187                 {
1188                         desc: "Strip escaped password",
1189                         in:   "http://user:pa%2Fssword@dummy.faketld/",
1190                         out:  `Get "http://user:***@dummy.faketld/": dummy impl`,
1191                 },
1192         }
1193         for _, tC := range testCases {
1194                 t.Run(tC.desc, func(t *testing.T) {
1195                         _, err := client.Get(tC.in)
1196                         if err.Error() != tC.out {
1197                                 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1198                                         tC.in, tC.out, err.Error())
1199                         }
1200                 })
1201         }
1202 }
1203
1204 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
1205 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
1206
1207 func testClientTimeout(t *testing.T, h2 bool) {
1208         setParallel(t)
1209         defer afterTest(t)
1210
1211         var (
1212                 mu           sync.Mutex
1213                 nonce        string // a unique per-request string
1214                 sawSlowNonce bool   // true if the handler saw /slow?nonce=<nonce>
1215         )
1216         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1217                 _ = r.ParseForm()
1218                 if r.URL.Path == "/" {
1219                         Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
1220                         return
1221                 }
1222                 if r.URL.Path == "/slow" {
1223                         mu.Lock()
1224                         if r.Form.Get("nonce") == nonce {
1225                                 sawSlowNonce = true
1226                         } else {
1227                                 t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
1228                         }
1229                         mu.Unlock()
1230
1231                         w.Write([]byte("Hello"))
1232                         w.(Flusher).Flush()
1233                         <-r.Context().Done()
1234                         return
1235                 }
1236         }))
1237         defer cst.close()
1238
1239         // Try to trigger a timeout after reading part of the response body.
1240         // The initial timeout is emprically usually long enough on a decently fast
1241         // machine, but if we undershoot we'll retry with exponentially longer
1242         // timeouts until the test either passes or times out completely.
1243         // This keeps the test reasonably fast in the typical case but allows it to
1244         // also eventually succeed on arbitrarily slow machines.
1245         timeout := 10 * time.Millisecond
1246         nextNonce := 0
1247         for ; ; timeout *= 2 {
1248                 if timeout <= 0 {
1249                         // The only way we can feasibly hit this while the test is running is if
1250                         // the request fails without actually waiting for the timeout to occur.
1251                         t.Fatalf("timeout overflow")
1252                 }
1253                 if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
1254                         t.Fatalf("failed to produce expected timeout before test deadline")
1255                 }
1256                 t.Logf("attempting test with timeout %v", timeout)
1257                 cst.c.Timeout = timeout
1258
1259                 mu.Lock()
1260                 nonce = fmt.Sprint(nextNonce)
1261                 nextNonce++
1262                 sawSlowNonce = false
1263                 mu.Unlock()
1264                 res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
1265                 if err != nil {
1266                         if strings.Contains(err.Error(), "Client.Timeout") {
1267                                 // Timed out before handler could respond.
1268                                 t.Logf("timeout before response received")
1269                                 continue
1270                         }
1271                         t.Fatal(err)
1272                 }
1273
1274                 mu.Lock()
1275                 ok := sawSlowNonce
1276                 mu.Unlock()
1277                 if !ok {
1278                         t.Fatal("handler never got /slow request, but client returned response")
1279                 }
1280
1281                 _, err = io.ReadAll(res.Body)
1282                 res.Body.Close()
1283
1284                 if err == nil {
1285                         t.Fatal("expected error from ReadAll")
1286                 }
1287                 ne, ok := err.(net.Error)
1288                 if !ok {
1289                         t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1290                 } else if !ne.Timeout() {
1291                         t.Errorf("net.Error.Timeout = false; want true")
1292                 }
1293                 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1294                         if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1295                                 testenv.SkipFlaky(t, 43120)
1296                         }
1297                         t.Errorf("error string = %q; missing timeout substring", got)
1298                 }
1299
1300                 break
1301         }
1302 }
1303
1304 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
1305 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
1306
1307 // Client.Timeout firing before getting to the body
1308 func testClientTimeout_Headers(t *testing.T, h2 bool) {
1309         setParallel(t)
1310         defer afterTest(t)
1311         donec := make(chan bool, 1)
1312         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1313                 <-donec
1314         }), optQuietLog)
1315         defer cst.close()
1316         // Note that we use a channel send here and not a close.
1317         // The race detector doesn't know that we're waiting for a timeout
1318         // and thinks that the waitgroup inside httptest.Server is added to concurrently
1319         // with us closing it. If we timed out immediately, we could close the testserver
1320         // before we entered the handler. We're not timing out immediately and there's
1321         // no way we would be done before we entered the handler, but the race detector
1322         // doesn't know this, so synchronize explicitly.
1323         defer func() { donec <- true }()
1324
1325         cst.c.Timeout = 5 * time.Millisecond
1326         res, err := cst.c.Get(cst.ts.URL)
1327         if err == nil {
1328                 res.Body.Close()
1329                 t.Fatal("got response from Get; expected error")
1330         }
1331         if _, ok := err.(*url.Error); !ok {
1332                 t.Fatalf("Got error of type %T; want *url.Error", err)
1333         }
1334         ne, ok := err.(net.Error)
1335         if !ok {
1336                 t.Fatalf("Got error of type %T; want some net.Error", err)
1337         }
1338         if !ne.Timeout() {
1339                 t.Error("net.Error.Timeout = false; want true")
1340         }
1341         if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1342                 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1343                         testenv.SkipFlaky(t, 43120)
1344                 }
1345                 t.Errorf("error string = %q; missing timeout substring", got)
1346         }
1347 }
1348
1349 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1350 // returned.
1351 func TestClientTimeoutCancel(t *testing.T) {
1352         setParallel(t)
1353         defer afterTest(t)
1354
1355         testDone := make(chan struct{})
1356         ctx, cancel := context.WithCancel(context.Background())
1357
1358         cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1359                 w.(Flusher).Flush()
1360                 <-testDone
1361         }))
1362         defer cst.close()
1363         defer close(testDone)
1364
1365         cst.c.Timeout = 1 * time.Hour
1366         req, _ := NewRequest("GET", cst.ts.URL, nil)
1367         req.Cancel = ctx.Done()
1368         res, err := cst.c.Do(req)
1369         if err != nil {
1370                 t.Fatal(err)
1371         }
1372         cancel()
1373         _, err = io.Copy(io.Discard, res.Body)
1374         if err != ExportErrRequestCanceled {
1375                 t.Fatalf("error = %v; want errRequestCanceled", err)
1376         }
1377 }
1378
1379 func TestClientTimeoutDoesNotExpire_h1(t *testing.T) { testClientTimeoutDoesNotExpire(t, h1Mode) }
1380 func TestClientTimeoutDoesNotExpire_h2(t *testing.T) { testClientTimeoutDoesNotExpire(t, h2Mode) }
1381
1382 // Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1383 func testClientTimeoutDoesNotExpire(t *testing.T, h2 bool) {
1384         setParallel(t)
1385         defer afterTest(t)
1386
1387         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1388                 w.Write([]byte("body"))
1389         }))
1390         defer cst.close()
1391
1392         cst.c.Timeout = 1 * time.Hour
1393         req, _ := NewRequest("GET", cst.ts.URL, nil)
1394         res, err := cst.c.Do(req)
1395         if err != nil {
1396                 t.Fatal(err)
1397         }
1398         if _, err = io.Copy(io.Discard, res.Body); err != nil {
1399                 t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1400         }
1401         if err = res.Body.Close(); err != nil {
1402                 t.Fatalf("res.Body.Close() = %v, want nil", err)
1403         }
1404 }
1405
1406 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
1407 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
1408 func testClientRedirectEatsBody(t *testing.T, h2 bool) {
1409         setParallel(t)
1410         defer afterTest(t)
1411         saw := make(chan string, 2)
1412         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
1413                 saw <- r.RemoteAddr
1414                 if r.URL.Path == "/" {
1415                         Redirect(w, r, "/foo", StatusFound) // which includes a body
1416                 }
1417         }))
1418         defer cst.close()
1419
1420         res, err := cst.c.Get(cst.ts.URL)
1421         if err != nil {
1422                 t.Fatal(err)
1423         }
1424         _, err = io.ReadAll(res.Body)
1425         res.Body.Close()
1426         if err != nil {
1427                 t.Fatal(err)
1428         }
1429
1430         var first string
1431         select {
1432         case first = <-saw:
1433         default:
1434                 t.Fatal("server didn't see a request")
1435         }
1436
1437         var second string
1438         select {
1439         case second = <-saw:
1440         default:
1441                 t.Fatal("server didn't see a second request")
1442         }
1443
1444         if first != second {
1445                 t.Fatal("server saw different client ports before & after the redirect")
1446         }
1447 }
1448
1449 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1450 type eofReaderFunc func()
1451
1452 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1453         f()
1454         return 0, io.EOF
1455 }
1456
1457 func TestReferer(t *testing.T) {
1458         tests := []struct {
1459                 lastReq, newReq string // from -> to URLs
1460                 want            string
1461         }{
1462                 // don't send user:
1463                 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1464                 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1465
1466                 // don't send a user and password:
1467                 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1468                 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1469
1470                 // nothing to do:
1471                 {"http://test.com", "http://link.com", "http://test.com"},
1472                 {"https://test.com", "https://link.com", "https://test.com"},
1473
1474                 // https to http doesn't send a referer:
1475                 {"https://test.com", "http://link.com", ""},
1476                 {"https://gopher:go@test.com", "http://link.com", ""},
1477         }
1478         for _, tt := range tests {
1479                 l, err := url.Parse(tt.lastReq)
1480                 if err != nil {
1481                         t.Fatal(err)
1482                 }
1483                 n, err := url.Parse(tt.newReq)
1484                 if err != nil {
1485                         t.Fatal(err)
1486                 }
1487                 r := ExportRefererForURL(l, n)
1488                 if r != tt.want {
1489                         t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1490                 }
1491         }
1492 }
1493
1494 // issue15577Tripper returns a Response with a redirect response
1495 // header and doesn't populate its Response.Request field.
1496 type issue15577Tripper struct{}
1497
1498 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1499         resp := &Response{
1500                 StatusCode: 303,
1501                 Header:     map[string][]string{"Location": {"http://www.example.com/"}},
1502                 Body:       io.NopCloser(strings.NewReader("")),
1503         }
1504         return resp, nil
1505 }
1506
1507 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1508 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1509         c := &Client{
1510                 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1511                 Transport:     issue15577Tripper{},
1512         }
1513         // Check that this doesn't crash:
1514         c.Get("http://dummy.tld")
1515 }
1516
1517 // Issue 4800: copy (some) headers when Client follows a redirect.
1518 func TestClientCopyHeadersOnRedirect(t *testing.T) {
1519         const (
1520                 ua   = "some-agent/1.2"
1521                 xfoo = "foo-val"
1522         )
1523         var ts2URL string
1524         ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1525                 want := Header{
1526                         "User-Agent":      []string{ua},
1527                         "X-Foo":           []string{xfoo},
1528                         "Referer":         []string{ts2URL},
1529                         "Accept-Encoding": []string{"gzip"},
1530                 }
1531                 if !reflect.DeepEqual(r.Header, want) {
1532                         t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1533                 }
1534                 if t.Failed() {
1535                         w.Header().Set("Result", "got errors")
1536                 } else {
1537                         w.Header().Set("Result", "ok")
1538                 }
1539         }))
1540         defer ts1.Close()
1541         ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1542                 Redirect(w, r, ts1.URL, StatusFound)
1543         }))
1544         defer ts2.Close()
1545         ts2URL = ts2.URL
1546
1547         c := ts1.Client()
1548         c.CheckRedirect = func(r *Request, via []*Request) error {
1549                 want := Header{
1550                         "User-Agent": []string{ua},
1551                         "X-Foo":      []string{xfoo},
1552                         "Referer":    []string{ts2URL},
1553                 }
1554                 if !reflect.DeepEqual(r.Header, want) {
1555                         t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1556                 }
1557                 return nil
1558         }
1559
1560         req, _ := NewRequest("GET", ts2.URL, nil)
1561         req.Header.Add("User-Agent", ua)
1562         req.Header.Add("X-Foo", xfoo)
1563         req.Header.Add("Cookie", "foo=bar")
1564         req.Header.Add("Authorization", "secretpassword")
1565         res, err := c.Do(req)
1566         if err != nil {
1567                 t.Fatal(err)
1568         }
1569         defer res.Body.Close()
1570         if res.StatusCode != 200 {
1571                 t.Fatal(res.Status)
1572         }
1573         if got := res.Header.Get("Result"); got != "ok" {
1574                 t.Errorf("result = %q; want ok", got)
1575         }
1576 }
1577
1578 // Issue 22233: copy host when Client follows a relative redirect.
1579 func TestClientCopyHostOnRedirect(t *testing.T) {
1580         // Virtual hostname: should not receive any request.
1581         virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1582                 t.Errorf("Virtual host received request %v", r.URL)
1583                 w.WriteHeader(403)
1584                 io.WriteString(w, "should not see this response")
1585         }))
1586         defer virtual.Close()
1587         virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1588         t.Logf("Virtual host is %v", virtualHost)
1589
1590         // Actual hostname: should not receive any request.
1591         const wantBody = "response body"
1592         var tsURL string
1593         var tsHost string
1594         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1595                 switch r.URL.Path {
1596                 case "/":
1597                         // Relative redirect.
1598                         if r.Host != virtualHost {
1599                                 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1600                                 w.WriteHeader(404)
1601                                 return
1602                         }
1603                         w.Header().Set("Location", "/hop")
1604                         w.WriteHeader(302)
1605                 case "/hop":
1606                         // Absolute redirect.
1607                         if r.Host != virtualHost {
1608                                 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1609                                 w.WriteHeader(404)
1610                                 return
1611                         }
1612                         w.Header().Set("Location", tsURL+"/final")
1613                         w.WriteHeader(302)
1614                 case "/final":
1615                         if r.Host != tsHost {
1616                                 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1617                                 w.WriteHeader(404)
1618                                 return
1619                         }
1620                         w.WriteHeader(200)
1621                         io.WriteString(w, wantBody)
1622                 default:
1623                         t.Errorf("Serving unexpected path %q", r.URL.Path)
1624                         w.WriteHeader(404)
1625                 }
1626         }))
1627         defer ts.Close()
1628         tsURL = ts.URL
1629         tsHost = strings.TrimPrefix(ts.URL, "http://")
1630         t.Logf("Server host is %v", tsHost)
1631
1632         c := ts.Client()
1633         req, _ := NewRequest("GET", ts.URL, nil)
1634         req.Host = virtualHost
1635         resp, err := c.Do(req)
1636         if err != nil {
1637                 t.Fatal(err)
1638         }
1639         defer resp.Body.Close()
1640         if resp.StatusCode != 200 {
1641                 t.Fatal(resp.Status)
1642         }
1643         if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1644                 t.Errorf("body = %q; want %q", got, wantBody)
1645         }
1646 }
1647
1648 // Issue 17494: cookies should be altered when Client follows redirects.
1649 func TestClientAltersCookiesOnRedirect(t *testing.T) {
1650         cookieMap := func(cs []*Cookie) map[string][]string {
1651                 m := make(map[string][]string)
1652                 for _, c := range cs {
1653                         m[c.Name] = append(m[c.Name], c.Value)
1654                 }
1655                 return m
1656         }
1657
1658         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1659                 var want map[string][]string
1660                 got := cookieMap(r.Cookies())
1661
1662                 c, _ := r.Cookie("Cycle")
1663                 switch c.Value {
1664                 case "0":
1665                         want = map[string][]string{
1666                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1667                                 "Cookie2": {"OldValue2"},
1668                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1669                                 "Cookie4": {"OldValue4"},
1670                                 "Cycle":   {"0"},
1671                         }
1672                         SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1673                         SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1674                         Redirect(w, r, "/", StatusFound)
1675                 case "1":
1676                         want = map[string][]string{
1677                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1678                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1679                                 "Cookie4": {"OldValue4"},
1680                                 "Cycle":   {"1"},
1681                         }
1682                         SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1683                         SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1684                         SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1685                         Redirect(w, r, "/", StatusFound)
1686                 case "2":
1687                         want = map[string][]string{
1688                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1689                                 "Cookie3": {"NewValue3"},
1690                                 "Cookie4": {"NewValue4"},
1691                                 "Cycle":   {"2"},
1692                         }
1693                         SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1694                         SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1695                         Redirect(w, r, "/", StatusFound)
1696                 case "3":
1697                         want = map[string][]string{
1698                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1699                                 "Cookie3": {"NewValue3"},
1700                                 "Cookie4": {"NewValue4"},
1701                                 "Cookie5": {"NewValue5"},
1702                                 "Cycle":   {"3"},
1703                         }
1704                         // Don't redirect to ensure the loop ends.
1705                 default:
1706                         t.Errorf("unexpected redirect cycle")
1707                         return
1708                 }
1709
1710                 if !reflect.DeepEqual(got, want) {
1711                         t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1712                 }
1713         }))
1714         defer ts.Close()
1715
1716         jar, _ := cookiejar.New(nil)
1717         c := ts.Client()
1718         c.Jar = jar
1719
1720         u, _ := url.Parse(ts.URL)
1721         req, _ := NewRequest("GET", ts.URL, nil)
1722         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1723         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1724         req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1725         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1726         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1727         jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1728         jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1729         res, err := c.Do(req)
1730         if err != nil {
1731                 t.Fatal(err)
1732         }
1733         defer res.Body.Close()
1734         if res.StatusCode != 200 {
1735                 t.Fatal(res.Status)
1736         }
1737 }
1738
1739 // Part of Issue 4800
1740 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1741         tests := []struct {
1742                 header     string
1743                 initialURL string
1744                 destURL    string
1745                 want       bool
1746         }{
1747                 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1748                 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1749
1750                 // Sensitive headers:
1751                 {"cookie", "http://foo.com/", "http://bar.com/", false},
1752                 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1753                 {"authorization", "http://foo.com/", "http://bar.com/", false},
1754                 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1755
1756                 // But subdomains should work:
1757                 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1758                 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1759                 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1760                 {"www-authenticate", "http://foo.com/", "https://foo.com/", false},
1761                 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1762                 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1763                 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1764                 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1765                 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false},
1766         }
1767         for i, tt := range tests {
1768                 u0, err := url.Parse(tt.initialURL)
1769                 if err != nil {
1770                         t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1771                         continue
1772                 }
1773                 u1, err := url.Parse(tt.destURL)
1774                 if err != nil {
1775                         t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1776                         continue
1777                 }
1778                 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1779                 if got != tt.want {
1780                         t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1781                                 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1782                 }
1783         }
1784 }
1785
1786 func TestClientRedirectTypes(t *testing.T) {
1787         setParallel(t)
1788         defer afterTest(t)
1789
1790         tests := [...]struct {
1791                 method       string
1792                 serverStatus int
1793                 wantMethod   string // desired subsequent client method
1794         }{
1795                 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1796                 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1797                 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1798                 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1799                 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1800
1801                 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1802                 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1803                 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1804                 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1805                 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1806
1807                 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1808                 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1809                 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1810                 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1811                 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1812
1813                 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1814                 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1815                 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1816                 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1817                 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1818
1819                 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1820                 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1821                 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1822                 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1823                 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1824
1825                 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1826                 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1827                 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1828                 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1829                 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1830         }
1831
1832         handlerc := make(chan HandlerFunc, 1)
1833
1834         ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
1835                 h := <-handlerc
1836                 h(rw, req)
1837         }))
1838         defer ts.Close()
1839
1840         c := ts.Client()
1841         for i, tt := range tests {
1842                 handlerc <- func(w ResponseWriter, r *Request) {
1843                         w.Header().Set("Location", ts.URL)
1844                         w.WriteHeader(tt.serverStatus)
1845                 }
1846
1847                 req, err := NewRequest(tt.method, ts.URL, nil)
1848                 if err != nil {
1849                         t.Errorf("#%d: NewRequest: %v", i, err)
1850                         continue
1851                 }
1852
1853                 c.CheckRedirect = func(req *Request, via []*Request) error {
1854                         if got, want := req.Method, tt.wantMethod; got != want {
1855                                 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1856                         }
1857                         handlerc <- func(rw ResponseWriter, req *Request) {
1858                                 // TODO: Check that the body is valid when we do 307 and 308 support
1859                         }
1860                         return nil
1861                 }
1862
1863                 res, err := c.Do(req)
1864                 if err != nil {
1865                         t.Errorf("#%d: Response: %v", i, err)
1866                         continue
1867                 }
1868
1869                 res.Body.Close()
1870         }
1871 }
1872
1873 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1874 // Its Read returns readErr and increments *readCalls atomically.
1875 // Its Close returns nil and increments *closeCalls atomically.
1876 type issue18239Body struct {
1877         readCalls  *int32
1878         closeCalls *int32
1879         readErr    error
1880 }
1881
1882 func (b issue18239Body) Read([]byte) (int, error) {
1883         atomic.AddInt32(b.readCalls, 1)
1884         return 0, b.readErr
1885 }
1886
1887 func (b issue18239Body) Close() error {
1888         atomic.AddInt32(b.closeCalls, 1)
1889         return nil
1890 }
1891
1892 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1893 // if Request.GetBody is not defined.
1894 func TestTransportBodyReadError(t *testing.T) {
1895         setParallel(t)
1896         defer afterTest(t)
1897         ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
1898                 if r.URL.Path == "/ping" {
1899                         return
1900                 }
1901                 buf := make([]byte, 1)
1902                 n, err := r.Body.Read(buf)
1903                 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1904         }))
1905         defer ts.Close()
1906         c := ts.Client()
1907         tr := c.Transport.(*Transport)
1908
1909         // Do one initial successful request to create an idle TCP connection
1910         // for the subsequent request to reuse. (The Transport only retries
1911         // requests on reused connections.)
1912         res, err := c.Get(ts.URL + "/ping")
1913         if err != nil {
1914                 t.Fatal(err)
1915         }
1916         res.Body.Close()
1917
1918         var readCallsAtomic int32
1919         var closeCallsAtomic int32 // atomic
1920         someErr := errors.New("some body read error")
1921         body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1922
1923         req, err := NewRequest("POST", ts.URL, body)
1924         if err != nil {
1925                 t.Fatal(err)
1926         }
1927         req = req.WithT(t)
1928         _, err = tr.RoundTrip(req)
1929         if err != someErr {
1930                 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1931         }
1932
1933         // And verify that our Body wasn't used multiple times, which
1934         // would indicate retries. (as it buggily was during part of
1935         // Go 1.8's dev cycle)
1936         readCalls := atomic.LoadInt32(&readCallsAtomic)
1937         closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1938         if readCalls != 1 {
1939                 t.Errorf("read calls = %d; want 1", readCalls)
1940         }
1941         if closeCalls != 1 {
1942                 t.Errorf("close calls = %d; want 1", closeCalls)
1943         }
1944 }
1945
1946 type roundTripperWithoutCloseIdle struct{}
1947
1948 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1949
1950 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1951
1952 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1953 func (f roundTripperWithCloseIdle) CloseIdleConnections()               { f() }
1954
1955 func TestClientCloseIdleConnections(t *testing.T) {
1956         c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1957         c.CloseIdleConnections() // verify we don't crash at least
1958
1959         closed := false
1960         var tr RoundTripper = roundTripperWithCloseIdle(func() {
1961                 closed = true
1962         })
1963         c = &Client{Transport: tr}
1964         c.CloseIdleConnections()
1965         if !closed {
1966                 t.Error("not closed")
1967         }
1968 }
1969
1970 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1971         errDial := errors.New("not actually dialing")
1972         c := &Client{
1973                 Timeout: 5 * time.Second,
1974                 Transport: &Transport{
1975                         DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1976                                 deadline, ok := ctx.Deadline()
1977                                 if !ok {
1978                                         t.Error("no deadline")
1979                                 } else {
1980                                         t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1981                                 }
1982                                 return nil, errDial
1983                         },
1984                 },
1985         }
1986         c.Get("https://example.tld/")
1987 }
1988
1989 func TestClientDoCanceledVsTimeout_h1(t *testing.T) {
1990         testClientDoCanceledVsTimeout(t, h1Mode)
1991 }
1992
1993 func TestClientDoCanceledVsTimeout_h2(t *testing.T) {
1994         testClientDoCanceledVsTimeout(t, h2Mode)
1995 }
1996
1997 // Issue 33545: lock-in the behavior promised by Client.Do's
1998 // docs about request cancellation vs timing out.
1999 func testClientDoCanceledVsTimeout(t *testing.T, h2 bool) {
2000         defer afterTest(t)
2001         cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
2002                 w.Write([]byte("Hello, World!"))
2003         }))
2004         defer cst.close()
2005
2006         cases := []string{"timeout", "canceled"}
2007
2008         for _, name := range cases {
2009                 t.Run(name, func(t *testing.T) {
2010                         var ctx context.Context
2011                         var cancel func()
2012                         if name == "timeout" {
2013                                 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
2014                         } else {
2015                                 ctx, cancel = context.WithCancel(context.Background())
2016                                 cancel()
2017                         }
2018                         defer cancel()
2019
2020                         req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
2021                         _, err := cst.c.Do(req)
2022                         if err == nil {
2023                                 t.Fatal("Unexpectedly got a nil error")
2024                         }
2025
2026                         ue := err.(*url.Error)
2027
2028                         var wantIsTimeout bool
2029                         var wantErr error = context.Canceled
2030                         if name == "timeout" {
2031                                 wantErr = context.DeadlineExceeded
2032                                 wantIsTimeout = true
2033                         }
2034                         if g, w := ue.Timeout(), wantIsTimeout; g != w {
2035                                 t.Fatalf("url.Timeout() = %t, want %t", g, w)
2036                         }
2037                         if g, w := ue.Err, wantErr; g != w {
2038                                 t.Errorf("url.Error.Err = %v; want %v", g, w)
2039                         }
2040                 })
2041         }
2042 }
2043
2044 type nilBodyRoundTripper struct{}
2045
2046 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
2047         return &Response{
2048                 StatusCode: StatusOK,
2049                 Status:     StatusText(StatusOK),
2050                 Body:       nil,
2051                 Request:    req,
2052         }, nil
2053 }
2054
2055 func TestClientPopulatesNilResponseBody(t *testing.T) {
2056         c := &Client{Transport: nilBodyRoundTripper{}}
2057
2058         resp, err := c.Get("http://localhost/anything")
2059         if err != nil {
2060                 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2061         }
2062
2063         if resp.Body == nil {
2064                 t.Fatalf("Client failed to provide a non-nil Body as documented")
2065         }
2066         defer func() {
2067                 if err := resp.Body.Close(); err != nil {
2068                         t.Fatalf("error from Close on substitute Response.Body: %v", err)
2069                 }
2070         }()
2071
2072         if b, err := io.ReadAll(resp.Body); err != nil {
2073                 t.Errorf("read error from substitute Response.Body: %v", err)
2074         } else if len(b) != 0 {
2075                 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2076         }
2077 }
2078
2079 // Issue 40382: Client calls Close multiple times on Request.Body.
2080 func TestClientCallsCloseOnlyOnce(t *testing.T) {
2081         setParallel(t)
2082         defer afterTest(t)
2083         cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2084                 w.WriteHeader(StatusNoContent)
2085         }))
2086         defer cst.close()
2087
2088         // Issue occurred non-deterministically: needed to occur after a successful
2089         // write (into TCP buffer) but before end of body.
2090         for i := 0; i < 50 && !t.Failed(); i++ {
2091                 body := &issue40382Body{t: t, n: 300000}
2092                 req, err := NewRequest(MethodPost, cst.ts.URL, body)
2093                 if err != nil {
2094                         t.Fatal(err)
2095                 }
2096                 resp, err := cst.tr.RoundTrip(req)
2097                 if err != nil {
2098                         t.Fatal(err)
2099                 }
2100                 resp.Body.Close()
2101         }
2102 }
2103
2104 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2105 // Its Read reads n bytes before returning io.EOF.
2106 // Its Close returns nil but fails the test if called more than once.
2107 type issue40382Body struct {
2108         t                *testing.T
2109         n                int
2110         closeCallsAtomic int32
2111 }
2112
2113 func (b *issue40382Body) Read(p []byte) (int, error) {
2114         switch {
2115         case b.n == 0:
2116                 return 0, io.EOF
2117         case b.n < len(p):
2118                 p = p[:b.n]
2119                 fallthrough
2120         default:
2121                 for i := range p {
2122                         p[i] = 'x'
2123                 }
2124                 b.n -= len(p)
2125                 return len(p), nil
2126         }
2127 }
2128
2129 func (b *issue40382Body) Close() error {
2130         if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2131                 b.t.Error("Body closed more than once")
2132         }
2133         return nil
2134 }
2135
2136 func TestProbeZeroLengthBody(t *testing.T) {
2137         setParallel(t)
2138         defer afterTest(t)
2139         reqc := make(chan struct{})
2140         cst := newClientServerTest(t, false, HandlerFunc(func(w ResponseWriter, r *Request) {
2141                 close(reqc)
2142                 if _, err := io.Copy(w, r.Body); err != nil {
2143                         t.Errorf("error copying request body: %v", err)
2144                 }
2145         }))
2146         defer cst.close()
2147
2148         bodyr, bodyw := io.Pipe()
2149         var gotBody string
2150         var wg sync.WaitGroup
2151         wg.Add(1)
2152         go func() {
2153                 defer wg.Done()
2154                 req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2155                 res, err := cst.c.Do(req)
2156                 b, err := io.ReadAll(res.Body)
2157                 if err != nil {
2158                         t.Error(err)
2159                 }
2160                 gotBody = string(b)
2161         }()
2162
2163         select {
2164         case <-reqc:
2165                 // Request should be sent after trying to probe the request body for 200ms.
2166         case <-time.After(60 * time.Second):
2167                 t.Errorf("request not sent after 60s")
2168         }
2169
2170         // Write the request body and wait for the request to complete.
2171         const content = "body"
2172         bodyw.Write([]byte(content))
2173         bodyw.Close()
2174         wg.Wait()
2175         if gotBody != content {
2176                 t.Fatalf("server got body %q, want %q", gotBody, content)
2177         }
2178 }