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