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

View as plain text