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

View as plain text