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

View as plain text