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