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
7package http_test
8
9import (
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
34var 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.
41func 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
63func TestClient(t *testing.T) { run(t, testClient) }
64func 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
81func TestClientHead(t *testing.T) { run(t, testClientHead) }
82func 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
93type recordingTransport struct {
94	req *Request
95}
96
97func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
98	t.req = req
99	return nil, errors.New("dummy impl")
100}
101
102func 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
120func 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
147func 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
189func TestClientRedirects(t *testing.T) { run(t, testClientRedirects) }
190func 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.
286func TestClientRedirectsContext(t *testing.T) { run(t, testClientRedirectsContext) }
287func 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
314type redirectTest struct {
315	suffix       string
316	want         int // response code
317	redirectBody string
318}
319
320func 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
363func 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
402func 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
462func 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
478func TestClientRedirectUseResponse(t *testing.T) { run(t, testClientRedirectUseResponse) }
479func 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.
518func TestClientRedirectNoLocation(t *testing.T) { run(t, testClientRedirectNoLocation) }
519func 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.
543func TestClientRedirect308NoGetBody(t *testing.T) { run(t, testClientRedirect308NoGetBody) }
544func 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
569var expectedCookies = []*Cookie{
570	{Name: "ChocolateChip", Value: "tasty"},
571	{Name: "First", Value: "Hit"},
572	{Name: "Second", Value: "Hit"},
573}
574
575var 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
588func 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.
620type TestJar struct {
621	m      sync.Mutex
622	perURL map[string][]*Cookie
623}
624
625func (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
634func (j *TestJar) Cookies(u *url.URL) []*Cookie {
635	j.m.Lock()
636	defer j.m.Unlock()
637	return j.perURL[u.Host]
638}
639
640func TestRedirectCookiesJar(t *testing.T) { run(t, testRedirectCookiesJar) }
641func 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
656func 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
675func TestJarCalls(t *testing.T) { run(t, testJarCalls, []testMode{http1Mode}) }
676func 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/")
703SetCookie("http://firsthost.fake/", [name=val])
704Cookies("http://secondhost.fake/secondpath")
705SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
706Cookies("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.
715type RecordingJar struct {
716	mu  sync.Mutex
717	log bytes.Buffer
718}
719
720func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
721	j.logf("SetCookie(%q, %v)\n", u, cookies)
722}
723
724func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
725	j.logf("Cookies(%q)\n", u)
726	return nil
727}
728
729func (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
735func TestStreamingGet(t *testing.T) { run(t, testStreamingGet) }
736func 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
773type writeCountingConn struct {
774	net.Conn
775	count *int
776}
777
778func (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.
785func TestClientWrites(t *testing.T) { run(t, testClientWrites, []testMode{http1Mode}) }
786func 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
819func TestClientInsecureTransport(t *testing.T) {
820	run(t, testClientInsecureTransport, []testMode{https1Mode, http2Mode})
821}
822func 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
853func 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
866func TestClientWithCorrectTLSServerName(t *testing.T) {
867	run(t, testClientWithCorrectTLSServerName, []testMode{https1Mode, http2Mode})
868}
869func 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
884func TestClientWithIncorrectTLSServerName(t *testing.T) {
885	run(t, testClientWithIncorrectTLSServerName, []testMode{https1Mode, http2Mode})
886}
887func 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.
918func TestTransportUsesTLSConfigServerName(t *testing.T) {
919	run(t, testTransportUsesTLSConfigServerName, []testMode{https1Mode, http2Mode})
920}
921func 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
939func TestResponseSetsTLSConnectionState(t *testing.T) {
940	run(t, testResponseSetsTLSConnectionState, []testMode{https1Mode})
941}
942func 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_ECDHE_RSA_WITH_AES_128_GCM_SHA256}
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_ECDHE_RSA_WITH_AES_128_GCM_SHA256; 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.
970func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
971	run(t, testHTTPSClientDetectsHTTPServer, []testMode{http1Mode})
972}
973func 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
984func TestClientHeadContentLength(t *testing.T) { run(t, testClientHeadContentLength) }
985func 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
1018func TestEmptyPasswordAuth(t *testing.T) { run(t, testEmptyPasswordAuth) }
1019func 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
1052func TestBasicAuth(t *testing.T) {
1053	defer afterTest(t)
1054	tr := &recordingTransport{}
1055	client := &Client{Transport: tr}
1056
1057	url := "http://My%20User:My%[email protected]/"
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
1086func 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%[email protected]/"
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
1127func 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:[email protected]/",
1137			out:  `Get "http://user:***@dummy.faketld/": dummy impl`,
1138		},
1139		{
1140			desc: "Don't Strip password from domain name",
1141			in:   "http://user:[email protected]/",
1142			out:  `Get "http://user:***@password.faketld/": dummy impl`,
1143		},
1144		{
1145			desc: "Don't Strip password from path",
1146			in:   "http://user:[email protected]/password",
1147			out:  `Get "http://user:***@dummy.faketld/password": dummy impl`,
1148		},
1149		{
1150			desc: "Strip escaped password",
1151			in:   "http://user:pa%[email protected]/",
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
1166func TestClientTimeout(t *testing.T) { run(t, testClientTimeout) }
1167func 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 !errors.Is(err, context.DeadlineExceeded) {
1253			t.Errorf("ReadAll error = %q; expected some context.DeadlineExceeded", err)
1254		}
1255		if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1256			if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1257				testenv.SkipFlaky(t, 43120)
1258			}
1259			t.Errorf("error string = %q; missing timeout substring", got)
1260		}
1261
1262		break
1263	}
1264}
1265
1266// Client.Timeout firing before getting to the body
1267func TestClientTimeout_Headers(t *testing.T) { run(t, testClientTimeout_Headers) }
1268func testClientTimeout_Headers(t *testing.T, mode testMode) {
1269	donec := make(chan bool, 1)
1270	cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1271		<-donec
1272	}), optQuietLog)
1273	// Note that we use a channel send here and not a close.
1274	// The race detector doesn't know that we're waiting for a timeout
1275	// and thinks that the waitgroup inside httptest.Server is added to concurrently
1276	// with us closing it. If we timed out immediately, we could close the testserver
1277	// before we entered the handler. We're not timing out immediately and there's
1278	// no way we would be done before we entered the handler, but the race detector
1279	// doesn't know this, so synchronize explicitly.
1280	defer func() { donec <- true }()
1281
1282	cst.c.Timeout = 5 * time.Millisecond
1283	res, err := cst.c.Get(cst.ts.URL)
1284	if err == nil {
1285		res.Body.Close()
1286		t.Fatal("got response from Get; expected error")
1287	}
1288	if _, ok := err.(*url.Error); !ok {
1289		t.Fatalf("Got error of type %T; want *url.Error", err)
1290	}
1291	ne, ok := err.(net.Error)
1292	if !ok {
1293		t.Fatalf("Got error of type %T; want some net.Error", err)
1294	}
1295	if !ne.Timeout() {
1296		t.Error("net.Error.Timeout = false; want true")
1297	}
1298	if !errors.Is(err, context.DeadlineExceeded) {
1299		t.Errorf("ReadAll error = %q; expected some context.DeadlineExceeded", err)
1300	}
1301	if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1302		if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1303			testenv.SkipFlaky(t, 43120)
1304		}
1305		t.Errorf("error string = %q; missing timeout substring", got)
1306	}
1307}
1308
1309// Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1310// returned.
1311func TestClientTimeoutCancel(t *testing.T) { run(t, testClientTimeoutCancel) }
1312func testClientTimeoutCancel(t *testing.T, mode testMode) {
1313	testDone := make(chan struct{})
1314	ctx, cancel := context.WithCancel(context.Background())
1315
1316	cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1317		w.(Flusher).Flush()
1318		<-testDone
1319	}))
1320	defer close(testDone)
1321
1322	cst.c.Timeout = 1 * time.Hour
1323	req, _ := NewRequest("GET", cst.ts.URL, nil)
1324	req.Cancel = ctx.Done()
1325	res, err := cst.c.Do(req)
1326	if err != nil {
1327		t.Fatal(err)
1328	}
1329	cancel()
1330	_, err = io.Copy(io.Discard, res.Body)
1331	if err != ExportErrRequestCanceled {
1332		t.Fatalf("error = %v; want errRequestCanceled", err)
1333	}
1334}
1335
1336// Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1337func TestClientTimeoutDoesNotExpire(t *testing.T) { run(t, testClientTimeoutDoesNotExpire) }
1338func testClientTimeoutDoesNotExpire(t *testing.T, mode testMode) {
1339	cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1340		w.Write([]byte("body"))
1341	}))
1342
1343	cst.c.Timeout = 1 * time.Hour
1344	req, _ := NewRequest("GET", cst.ts.URL, nil)
1345	res, err := cst.c.Do(req)
1346	if err != nil {
1347		t.Fatal(err)
1348	}
1349	if _, err = io.Copy(io.Discard, res.Body); err != nil {
1350		t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1351	}
1352	if err = res.Body.Close(); err != nil {
1353		t.Fatalf("res.Body.Close() = %v, want nil", err)
1354	}
1355}
1356
1357func TestClientRedirectEatsBody_h1(t *testing.T) { run(t, testClientRedirectEatsBody) }
1358func testClientRedirectEatsBody(t *testing.T, mode testMode) {
1359	saw := make(chan string, 2)
1360	cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1361		saw <- r.RemoteAddr
1362		if r.URL.Path == "/" {
1363			Redirect(w, r, "/foo", StatusFound) // which includes a body
1364		}
1365	}))
1366
1367	res, err := cst.c.Get(cst.ts.URL)
1368	if err != nil {
1369		t.Fatal(err)
1370	}
1371	_, err = io.ReadAll(res.Body)
1372	res.Body.Close()
1373	if err != nil {
1374		t.Fatal(err)
1375	}
1376
1377	var first string
1378	select {
1379	case first = <-saw:
1380	default:
1381		t.Fatal("server didn't see a request")
1382	}
1383
1384	var second string
1385	select {
1386	case second = <-saw:
1387	default:
1388		t.Fatal("server didn't see a second request")
1389	}
1390
1391	if first != second {
1392		t.Fatal("server saw different client ports before & after the redirect")
1393	}
1394}
1395
1396// eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1397type eofReaderFunc func()
1398
1399func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1400	f()
1401	return 0, io.EOF
1402}
1403
1404func TestReferer(t *testing.T) {
1405	tests := []struct {
1406		lastReq, newReq, explicitRef string // from -> to URLs, explicitly set Referer value
1407		want                         string
1408	}{
1409		// don't send user:
1410		{lastReq: "http://[email protected]", newReq: "http://link.com", want: "http://test.com"},
1411		{lastReq: "https://[email protected]", newReq: "https://link.com", want: "https://test.com"},
1412
1413		// don't send a user and password:
1414		{lastReq: "http://gopher:[email protected]", newReq: "http://link.com", want: "http://test.com"},
1415		{lastReq: "https://gopher:[email protected]", newReq: "https://link.com", want: "https://test.com"},
1416
1417		// nothing to do:
1418		{lastReq: "http://test.com", newReq: "http://link.com", want: "http://test.com"},
1419		{lastReq: "https://test.com", newReq: "https://link.com", want: "https://test.com"},
1420
1421		// https to http doesn't send a referer:
1422		{lastReq: "https://test.com", newReq: "http://link.com", want: ""},
1423		{lastReq: "https://gopher:[email protected]", newReq: "http://link.com", want: ""},
1424
1425		// https to http should remove an existing referer:
1426		{lastReq: "https://test.com", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
1427		{lastReq: "https://gopher:[email protected]", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
1428
1429		// don't override an existing referer:
1430		{lastReq: "https://test.com", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
1431		{lastReq: "https://gopher:[email protected]", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
1432	}
1433	for _, tt := range tests {
1434		l, err := url.Parse(tt.lastReq)
1435		if err != nil {
1436			t.Fatal(err)
1437		}
1438		n, err := url.Parse(tt.newReq)
1439		if err != nil {
1440			t.Fatal(err)
1441		}
1442		r := ExportRefererForURL(l, n, tt.explicitRef)
1443		if r != tt.want {
1444			t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1445		}
1446	}
1447}
1448
1449// issue15577Tripper returns a Response with a redirect response
1450// header and doesn't populate its Response.Request field.
1451type issue15577Tripper struct{}
1452
1453func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1454	resp := &Response{
1455		StatusCode: 303,
1456		Header:     map[string][]string{"Location": {"http://www.example.com/"}},
1457		Body:       io.NopCloser(strings.NewReader("")),
1458	}
1459	return resp, nil
1460}
1461
1462// Issue 15577: don't assume the roundtripper's response populates its Request field.
1463func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1464	c := &Client{
1465		CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1466		Transport:     issue15577Tripper{},
1467	}
1468	// Check that this doesn't crash:
1469	c.Get("http://dummy.tld")
1470}
1471
1472// Issue 4800: copy (some) headers when Client follows a redirect.
1473// Issue 35104: Since both URLs have the same host (localhost)
1474// but different ports, sensitive headers like Cookie and Authorization
1475// are preserved.
1476func TestClientCopyHeadersOnRedirect(t *testing.T) { run(t, testClientCopyHeadersOnRedirect) }
1477func testClientCopyHeadersOnRedirect(t *testing.T, mode testMode) {
1478	const (
1479		ua   = "some-agent/1.2"
1480		xfoo = "foo-val"
1481	)
1482	var ts2URL string
1483	ts1 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1484		want := Header{
1485			"User-Agent":      []string{ua},
1486			"X-Foo":           []string{xfoo},
1487			"Referer":         []string{ts2URL},
1488			"Accept-Encoding": []string{"gzip"},
1489			"Cookie":          []string{"foo=bar"},
1490			"Authorization":   []string{"secretpassword"},
1491		}
1492		if !reflect.DeepEqual(r.Header, want) {
1493			t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1494		}
1495		if t.Failed() {
1496			w.Header().Set("Result", "got errors")
1497		} else {
1498			w.Header().Set("Result", "ok")
1499		}
1500	})).ts
1501	ts2 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1502		Redirect(w, r, ts1.URL, StatusFound)
1503	})).ts
1504	ts2URL = ts2.URL
1505
1506	c := ts1.Client()
1507	c.CheckRedirect = func(r *Request, via []*Request) error {
1508		want := Header{
1509			"User-Agent":    []string{ua},
1510			"X-Foo":         []string{xfoo},
1511			"Referer":       []string{ts2URL},
1512			"Cookie":        []string{"foo=bar"},
1513			"Authorization": []string{"secretpassword"},
1514		}
1515		if !reflect.DeepEqual(r.Header, want) {
1516			t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1517		}
1518		return nil
1519	}
1520
1521	req, _ := NewRequest("GET", ts2.URL, nil)
1522	req.Header.Add("User-Agent", ua)
1523	req.Header.Add("X-Foo", xfoo)
1524	req.Header.Add("Cookie", "foo=bar")
1525	req.Header.Add("Authorization", "secretpassword")
1526	res, err := c.Do(req)
1527	if err != nil {
1528		t.Fatal(err)
1529	}
1530	defer res.Body.Close()
1531	if res.StatusCode != 200 {
1532		t.Fatal(res.Status)
1533	}
1534	if got := res.Header.Get("Result"); got != "ok" {
1535		t.Errorf("result = %q; want ok", got)
1536	}
1537}
1538
1539// Issue 22233: copy host when Client follows a relative redirect.
1540func TestClientCopyHostOnRedirect(t *testing.T) { run(t, testClientCopyHostOnRedirect) }
1541func testClientCopyHostOnRedirect(t *testing.T, mode testMode) {
1542	// Virtual hostname: should not receive any request.
1543	virtual := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1544		t.Errorf("Virtual host received request %v", r.URL)
1545		w.WriteHeader(403)
1546		io.WriteString(w, "should not see this response")
1547	})).ts
1548	defer virtual.Close()
1549	virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1550	virtualHost = strings.TrimPrefix(virtualHost, "https://")
1551	t.Logf("Virtual host is %v", virtualHost)
1552
1553	// Actual hostname: should not receive any request.
1554	const wantBody = "response body"
1555	var tsURL string
1556	var tsHost string
1557	ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1558		switch r.URL.Path {
1559		case "/":
1560			// Relative redirect.
1561			if r.Host != virtualHost {
1562				t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1563				w.WriteHeader(404)
1564				return
1565			}
1566			w.Header().Set("Location", "/hop")
1567			w.WriteHeader(302)
1568		case "/hop":
1569			// Absolute redirect.
1570			if r.Host != virtualHost {
1571				t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1572				w.WriteHeader(404)
1573				return
1574			}
1575			w.Header().Set("Location", tsURL+"/final")
1576			w.WriteHeader(302)
1577		case "/final":
1578			if r.Host != tsHost {
1579				t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1580				w.WriteHeader(404)
1581				return
1582			}
1583			w.WriteHeader(200)
1584			io.WriteString(w, wantBody)
1585		default:
1586			t.Errorf("Serving unexpected path %q", r.URL.Path)
1587			w.WriteHeader(404)
1588		}
1589	})).ts
1590	tsURL = ts.URL
1591	tsHost = strings.TrimPrefix(ts.URL, "http://")
1592	tsHost = strings.TrimPrefix(tsHost, "https://")
1593	t.Logf("Server host is %v", tsHost)
1594
1595	c := ts.Client()
1596	req, _ := NewRequest("GET", ts.URL, nil)
1597	req.Host = virtualHost
1598	resp, err := c.Do(req)
1599	if err != nil {
1600		t.Fatal(err)
1601	}
1602	defer resp.Body.Close()
1603	if resp.StatusCode != 200 {
1604		t.Fatal(resp.Status)
1605	}
1606	if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1607		t.Errorf("body = %q; want %q", got, wantBody)
1608	}
1609}
1610
1611// Issue 17494: cookies should be altered when Client follows redirects.
1612func TestClientAltersCookiesOnRedirect(t *testing.T) { run(t, testClientAltersCookiesOnRedirect) }
1613func testClientAltersCookiesOnRedirect(t *testing.T, mode testMode) {
1614	cookieMap := func(cs []*Cookie) map[string][]string {
1615		m := make(map[string][]string)
1616		for _, c := range cs {
1617			m[c.Name] = append(m[c.Name], c.Value)
1618		}
1619		return m
1620	}
1621
1622	ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1623		var want map[string][]string
1624		got := cookieMap(r.Cookies())
1625
1626		c, _ := r.Cookie("Cycle")
1627		switch c.Value {
1628		case "0":
1629			want = map[string][]string{
1630				"Cookie1": {"OldValue1a", "OldValue1b"},
1631				"Cookie2": {"OldValue2"},
1632				"Cookie3": {"OldValue3a", "OldValue3b"},
1633				"Cookie4": {"OldValue4"},
1634				"Cycle":   {"0"},
1635			}
1636			SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1637			SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1638			Redirect(w, r, "/", StatusFound)
1639		case "1":
1640			want = map[string][]string{
1641				"Cookie1": {"OldValue1a", "OldValue1b"},
1642				"Cookie3": {"OldValue3a", "OldValue3b"},
1643				"Cookie4": {"OldValue4"},
1644				"Cycle":   {"1"},
1645			}
1646			SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1647			SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1648			SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1649			Redirect(w, r, "/", StatusFound)
1650		case "2":
1651			want = map[string][]string{
1652				"Cookie1": {"OldValue1a", "OldValue1b"},
1653				"Cookie3": {"NewValue3"},
1654				"Cookie4": {"NewValue4"},
1655				"Cycle":   {"2"},
1656			}
1657			SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1658			SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1659			Redirect(w, r, "/", StatusFound)
1660		case "3":
1661			want = map[string][]string{
1662				"Cookie1": {"OldValue1a", "OldValue1b"},
1663				"Cookie3": {"NewValue3"},
1664				"Cookie4": {"NewValue4"},
1665				"Cookie5": {"NewValue5"},
1666				"Cycle":   {"3"},
1667			}
1668			// Don't redirect to ensure the loop ends.
1669		default:
1670			t.Errorf("unexpected redirect cycle")
1671			return
1672		}
1673
1674		if !reflect.DeepEqual(got, want) {
1675			t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1676		}
1677	})).ts
1678
1679	jar, _ := cookiejar.New(nil)
1680	c := ts.Client()
1681	c.Jar = jar
1682
1683	u, _ := url.Parse(ts.URL)
1684	req, _ := NewRequest("GET", ts.URL, nil)
1685	req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1686	req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1687	req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1688	req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1689	req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1690	jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1691	jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1692	res, err := c.Do(req)
1693	if err != nil {
1694		t.Fatal(err)
1695	}
1696	defer res.Body.Close()
1697	if res.StatusCode != 200 {
1698		t.Fatal(res.Status)
1699	}
1700}
1701
1702// Part of Issue 4800
1703func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1704	tests := []struct {
1705		header     string
1706		initialURL string
1707		destURL    string
1708		want       bool
1709	}{
1710		{"User-Agent", "http://foo.com/", "http://bar.com/", true},
1711		{"X-Foo", "http://foo.com/", "http://bar.com/", true},
1712
1713		// Sensitive headers:
1714		{"cookie", "http://foo.com/", "http://bar.com/", false},
1715		{"cookie2", "http://foo.com/", "http://bar.com/", false},
1716		{"authorization", "http://foo.com/", "http://bar.com/", false},
1717		{"authorization", "http://foo.com/", "https://foo.com/", true},
1718		{"authorization", "http://foo.com:1234/", "http://foo.com:4321/", true},
1719		{"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1720		{"authorization", "http://foo.com/", "http://[::1%25.foo.com]/", false},
1721
1722		// But subdomains should work:
1723		{"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1724		{"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1725		{"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1726		{"www-authenticate", "http://foo.com/", "https://foo.com/", true},
1727		{"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1728		{"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1729		{"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1730		{"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1731		{"www-authenticate", "http://foo.com:1234/", "http://foo.com/", true},
1732
1733		{"authorization", "http://foo.com/", "http://foo.com/", true},
1734		{"authorization", "http://foo.com/", "http://sub.foo.com/", true},
1735		{"authorization", "http://foo.com/", "http://notfoo.com/", false},
1736		{"authorization", "http://foo.com/", "https://foo.com/", true},
1737		{"authorization", "http://foo.com:80/", "http://foo.com/", true},
1738		{"authorization", "http://foo.com:80/", "http://sub.foo.com/", true},
1739		{"authorization", "http://foo.com:443/", "https://foo.com/", true},
1740		{"authorization", "http://foo.com:443/", "https://sub.foo.com/", true},
1741		{"authorization", "http://foo.com:1234/", "http://foo.com/", true},
1742	}
1743	for i, tt := range tests {
1744		u0, err := url.Parse(tt.initialURL)
1745		if err != nil {
1746			t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1747			continue
1748		}
1749		u1, err := url.Parse(tt.destURL)
1750		if err != nil {
1751			t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1752			continue
1753		}
1754		got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1755		if got != tt.want {
1756			t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1757				i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1758		}
1759	}
1760}
1761
1762func TestClientRedirectTypes(t *testing.T) { run(t, testClientRedirectTypes) }
1763func testClientRedirectTypes(t *testing.T, mode testMode) {
1764	tests := [...]struct {
1765		method       string
1766		serverStatus int
1767		wantMethod   string // desired subsequent client method
1768	}{
1769		0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1770		1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1771		2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1772		3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1773		4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1774
1775		5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1776		6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1777		7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1778		8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1779		9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1780
1781		10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1782		11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1783		12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1784		13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1785		14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1786
1787		15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1788		16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1789		17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1790		18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1791		19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1792
1793		20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1794		21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1795		22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1796		23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1797		24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1798
1799		25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1800		26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1801		27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1802		28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1803		29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1804	}
1805
1806	handlerc := make(chan HandlerFunc, 1)
1807
1808	ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
1809		h := <-handlerc
1810		h(rw, req)
1811	})).ts
1812
1813	c := ts.Client()
1814	for i, tt := range tests {
1815		handlerc <- func(w ResponseWriter, r *Request) {
1816			w.Header().Set("Location", ts.URL)
1817			w.WriteHeader(tt.serverStatus)
1818		}
1819
1820		req, err := NewRequest(tt.method, ts.URL, nil)
1821		if err != nil {
1822			t.Errorf("#%d: NewRequest: %v", i, err)
1823			continue
1824		}
1825
1826		c.CheckRedirect = func(req *Request, via []*Request) error {
1827			if got, want := req.Method, tt.wantMethod; got != want {
1828				return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1829			}
1830			handlerc <- func(rw ResponseWriter, req *Request) {
1831				// TODO: Check that the body is valid when we do 307 and 308 support
1832			}
1833			return nil
1834		}
1835
1836		res, err := c.Do(req)
1837		if err != nil {
1838			t.Errorf("#%d: Response: %v", i, err)
1839			continue
1840		}
1841
1842		res.Body.Close()
1843	}
1844}
1845
1846// issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1847// Its Read returns readErr and increments *readCalls atomically.
1848// Its Close returns nil and increments *closeCalls atomically.
1849type issue18239Body struct {
1850	readCalls  *int32
1851	closeCalls *int32
1852	readErr    error
1853}
1854
1855func (b issue18239Body) Read([]byte) (int, error) {
1856	atomic.AddInt32(b.readCalls, 1)
1857	return 0, b.readErr
1858}
1859
1860func (b issue18239Body) Close() error {
1861	atomic.AddInt32(b.closeCalls, 1)
1862	return nil
1863}
1864
1865// Issue 18239: make sure the Transport doesn't retry requests with bodies
1866// if Request.GetBody is not defined.
1867func TestTransportBodyReadError(t *testing.T) { run(t, testTransportBodyReadError) }
1868func testTransportBodyReadError(t *testing.T, mode testMode) {
1869	ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1870		if r.URL.Path == "/ping" {
1871			return
1872		}
1873		buf := make([]byte, 1)
1874		n, err := r.Body.Read(buf)
1875		w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1876	})).ts
1877	c := ts.Client()
1878	tr := c.Transport.(*Transport)
1879
1880	// Do one initial successful request to create an idle TCP connection
1881	// for the subsequent request to reuse. (The Transport only retries
1882	// requests on reused connections.)
1883	res, err := c.Get(ts.URL + "/ping")
1884	if err != nil {
1885		t.Fatal(err)
1886	}
1887	res.Body.Close()
1888
1889	var readCallsAtomic int32
1890	var closeCallsAtomic int32 // atomic
1891	someErr := errors.New("some body read error")
1892	body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1893
1894	req, err := NewRequest("POST", ts.URL, body)
1895	if err != nil {
1896		t.Fatal(err)
1897	}
1898	req = req.WithT(t)
1899	_, err = tr.RoundTrip(req)
1900	if err != someErr {
1901		t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1902	}
1903
1904	// And verify that our Body wasn't used multiple times, which
1905	// would indicate retries. (as it buggily was during part of
1906	// Go 1.8's dev cycle)
1907	readCalls := atomic.LoadInt32(&readCallsAtomic)
1908	closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1909	if readCalls != 1 {
1910		t.Errorf("read calls = %d; want 1", readCalls)
1911	}
1912	if closeCalls != 1 {
1913		t.Errorf("close calls = %d; want 1", closeCalls)
1914	}
1915}
1916
1917type roundTripperWithoutCloseIdle struct{}
1918
1919func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1920
1921type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1922
1923func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1924func (f roundTripperWithCloseIdle) CloseIdleConnections()               { f() }
1925
1926func TestClientCloseIdleConnections(t *testing.T) {
1927	c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1928	c.CloseIdleConnections() // verify we don't crash at least
1929
1930	closed := false
1931	var tr RoundTripper = roundTripperWithCloseIdle(func() {
1932		closed = true
1933	})
1934	c = &Client{Transport: tr}
1935	c.CloseIdleConnections()
1936	if !closed {
1937		t.Error("not closed")
1938	}
1939}
1940
1941type testRoundTripper func(*Request) (*Response, error)
1942
1943func (t testRoundTripper) RoundTrip(req *Request) (*Response, error) {
1944	return t(req)
1945}
1946
1947func TestClientPropagatesTimeoutToContext(t *testing.T) {
1948	c := &Client{
1949		Timeout: 5 * time.Second,
1950		Transport: testRoundTripper(func(req *Request) (*Response, error) {
1951			ctx := req.Context()
1952			deadline, ok := ctx.Deadline()
1953			if !ok {
1954				t.Error("no deadline")
1955			} else {
1956				t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1957			}
1958			return nil, errors.New("not actually making a request")
1959		}),
1960	}
1961	c.Get("https://example.tld/")
1962}
1963
1964// Issue 33545: lock-in the behavior promised by Client.Do's
1965// docs about request cancellation vs timing out.
1966func TestClientDoCanceledVsTimeout(t *testing.T) { run(t, testClientDoCanceledVsTimeout) }
1967func testClientDoCanceledVsTimeout(t *testing.T, mode testMode) {
1968	cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1969		w.Write([]byte("Hello, World!"))
1970	}))
1971
1972	cases := []string{"timeout", "canceled"}
1973
1974	for _, name := range cases {
1975		t.Run(name, func(t *testing.T) {
1976			var ctx context.Context
1977			var cancel func()
1978			if name == "timeout" {
1979				ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
1980			} else {
1981				ctx, cancel = context.WithCancel(context.Background())
1982				cancel()
1983			}
1984			defer cancel()
1985
1986			req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
1987			_, err := cst.c.Do(req)
1988			if err == nil {
1989				t.Fatal("Unexpectedly got a nil error")
1990			}
1991
1992			ue := err.(*url.Error)
1993
1994			var wantIsTimeout bool
1995			var wantErr error = context.Canceled
1996			if name == "timeout" {
1997				wantErr = context.DeadlineExceeded
1998				wantIsTimeout = true
1999			}
2000			if g, w := ue.Timeout(), wantIsTimeout; g != w {
2001				t.Fatalf("url.Timeout() = %t, want %t", g, w)
2002			}
2003			if g, w := ue.Err, wantErr; g != w {
2004				t.Errorf("url.Error.Err = %v; want %v", g, w)
2005			}
2006			if got := errors.Is(err, context.DeadlineExceeded); got != wantIsTimeout {
2007				t.Errorf("errors.Is(err, context.DeadlineExceeded) = %v, want %v", got, wantIsTimeout)
2008			}
2009		})
2010	}
2011}
2012
2013type nilBodyRoundTripper struct{}
2014
2015func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
2016	return &Response{
2017		StatusCode: StatusOK,
2018		Status:     StatusText(StatusOK),
2019		Body:       nil,
2020		Request:    req,
2021	}, nil
2022}
2023
2024func TestClientPopulatesNilResponseBody(t *testing.T) {
2025	c := &Client{Transport: nilBodyRoundTripper{}}
2026
2027	resp, err := c.Get("http://localhost/anything")
2028	if err != nil {
2029		t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2030	}
2031
2032	if resp.Body == nil {
2033		t.Fatalf("Client failed to provide a non-nil Body as documented")
2034	}
2035	defer func() {
2036		if err := resp.Body.Close(); err != nil {
2037			t.Fatalf("error from Close on substitute Response.Body: %v", err)
2038		}
2039	}()
2040
2041	if b, err := io.ReadAll(resp.Body); err != nil {
2042		t.Errorf("read error from substitute Response.Body: %v", err)
2043	} else if len(b) != 0 {
2044		t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2045	}
2046}
2047
2048// Issue 40382: Client calls Close multiple times on Request.Body.
2049func TestClientCallsCloseOnlyOnce(t *testing.T) { run(t, testClientCallsCloseOnlyOnce) }
2050func testClientCallsCloseOnlyOnce(t *testing.T, mode testMode) {
2051	cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2052		w.WriteHeader(StatusNoContent)
2053	}))
2054
2055	// Issue occurred non-deterministically: needed to occur after a successful
2056	// write (into TCP buffer) but before end of body.
2057	for i := 0; i < 50 && !t.Failed(); i++ {
2058		body := &issue40382Body{t: t, n: 300000}
2059		req, err := NewRequest(MethodPost, cst.ts.URL, body)
2060		if err != nil {
2061			t.Fatal(err)
2062		}
2063		resp, err := cst.tr.RoundTrip(req)
2064		if err != nil {
2065			t.Fatal(err)
2066		}
2067		resp.Body.Close()
2068	}
2069}
2070
2071// issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2072// Its Read reads n bytes before returning io.EOF.
2073// Its Close returns nil but fails the test if called more than once.
2074type issue40382Body struct {
2075	t                *testing.T
2076	n                int
2077	closeCallsAtomic int32
2078}
2079
2080func (b *issue40382Body) Read(p []byte) (int, error) {
2081	switch {
2082	case b.n == 0:
2083		return 0, io.EOF
2084	case b.n < len(p):
2085		p = p[:b.n]
2086		fallthrough
2087	default:
2088		for i := range p {
2089			p[i] = 'x'
2090		}
2091		b.n -= len(p)
2092		return len(p), nil
2093	}
2094}
2095
2096func (b *issue40382Body) Close() error {
2097	if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2098		b.t.Error("Body closed more than once")
2099	}
2100	return nil
2101}
2102
2103func TestProbeZeroLengthBody(t *testing.T) { run(t, testProbeZeroLengthBody) }
2104func testProbeZeroLengthBody(t *testing.T, mode testMode) {
2105	reqc := make(chan struct{})
2106	cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2107		close(reqc)
2108		if _, err := io.Copy(w, r.Body); err != nil {
2109			t.Errorf("error copying request body: %v", err)
2110		}
2111	}))
2112
2113	bodyr, bodyw := io.Pipe()
2114	var gotBody string
2115	var wg sync.WaitGroup
2116	wg.Add(1)
2117	go func() {
2118		defer wg.Done()
2119		req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2120		res, err := cst.c.Do(req)
2121		b, err := io.ReadAll(res.Body)
2122		if err != nil {
2123			t.Error(err)
2124		}
2125		gotBody = string(b)
2126	}()
2127
2128	select {
2129	case <-reqc:
2130		// Request should be sent after trying to probe the request body for 200ms.
2131	case <-time.After(60 * time.Second):
2132		t.Errorf("request not sent after 60s")
2133	}
2134
2135	// Write the request body and wait for the request to complete.
2136	const content = "body"
2137	bodyw.Write([]byte(content))
2138	bodyw.Close()
2139	wg.Wait()
2140	if gotBody != content {
2141		t.Fatalf("server got body %q, want %q", gotBody, content)
2142	}
2143}
2144