Source file src/net/http/client_test.go

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

View as plain text