github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/net/http/request_test.go (about)

     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  package http_test
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"context"
    11  	"crypto/rand"
    12  	"encoding/base64"
    13  	"fmt"
    14  	"io"
    15  	"math"
    16  	"mime/multipart"
    17  	. "net/http"
    18  	"net/http/httptest"
    19  	"net/url"
    20  	"os"
    21  	"reflect"
    22  	"regexp"
    23  	"strings"
    24  	"testing"
    25  )
    26  
    27  func TestQuery(t *testing.T) {
    28  	req := &Request{Method: "GET"}
    29  	req.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar")
    30  	if q := req.FormValue("q"); q != "foo" {
    31  		t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
    32  	}
    33  }
    34  
    35  func TestParseFormQuery(t *testing.T) {
    36  	req, _ := NewRequest("POST", "http://www.google.com/search?q=foo&q=bar&both=x&prio=1&orphan=nope&empty=not",
    37  		strings.NewReader("z=post&both=y&prio=2&=nokey&orphan;empty=&"))
    38  	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
    39  
    40  	if q := req.FormValue("q"); q != "foo" {
    41  		t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
    42  	}
    43  	if z := req.FormValue("z"); z != "post" {
    44  		t.Errorf(`req.FormValue("z") = %q, want "post"`, z)
    45  	}
    46  	if bq, found := req.PostForm["q"]; found {
    47  		t.Errorf(`req.PostForm["q"] = %q, want no entry in map`, bq)
    48  	}
    49  	if bz := req.PostFormValue("z"); bz != "post" {
    50  		t.Errorf(`req.PostFormValue("z") = %q, want "post"`, bz)
    51  	}
    52  	if qs := req.Form["q"]; !reflect.DeepEqual(qs, []string{"foo", "bar"}) {
    53  		t.Errorf(`req.Form["q"] = %q, want ["foo", "bar"]`, qs)
    54  	}
    55  	if both := req.Form["both"]; !reflect.DeepEqual(both, []string{"y", "x"}) {
    56  		t.Errorf(`req.Form["both"] = %q, want ["y", "x"]`, both)
    57  	}
    58  	if prio := req.FormValue("prio"); prio != "2" {
    59  		t.Errorf(`req.FormValue("prio") = %q, want "2" (from body)`, prio)
    60  	}
    61  	if orphan := req.Form["orphan"]; !reflect.DeepEqual(orphan, []string{"", "nope"}) {
    62  		t.Errorf(`req.FormValue("orphan") = %q, want "" (from body)`, orphan)
    63  	}
    64  	if empty := req.Form["empty"]; !reflect.DeepEqual(empty, []string{"", "not"}) {
    65  		t.Errorf(`req.FormValue("empty") = %q, want "" (from body)`, empty)
    66  	}
    67  	if nokey := req.Form[""]; !reflect.DeepEqual(nokey, []string{"nokey"}) {
    68  		t.Errorf(`req.FormValue("nokey") = %q, want "nokey" (from body)`, nokey)
    69  	}
    70  }
    71  
    72  // Tests that we only parse the form automatically for certain methods.
    73  func TestParseFormQueryMethods(t *testing.T) {
    74  	for _, method := range []string{"POST", "PATCH", "PUT", "FOO"} {
    75  		req, _ := NewRequest(method, "http://www.google.com/search",
    76  			strings.NewReader("foo=bar"))
    77  		req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
    78  		want := "bar"
    79  		if method == "FOO" {
    80  			want = ""
    81  		}
    82  		if got := req.FormValue("foo"); got != want {
    83  			t.Errorf(`for method %s, FormValue("foo") = %q; want %q`, method, got, want)
    84  		}
    85  	}
    86  }
    87  
    88  func TestParseFormUnknownContentType(t *testing.T) {
    89  	for _, test := range []struct {
    90  		name        string
    91  		wantErr     string
    92  		contentType Header
    93  	}{
    94  		{"text", "", Header{"Content-Type": {"text/plain"}}},
    95  		// Empty content type is legal - may be treated as
    96  		// application/octet-stream (RFC 7231, section 3.1.1.5)
    97  		{"empty", "", Header{}},
    98  		{"boundary", "mime: invalid media parameter", Header{"Content-Type": {"text/plain; boundary="}}},
    99  		{"unknown", "", Header{"Content-Type": {"application/unknown"}}},
   100  	} {
   101  		t.Run(test.name,
   102  			func(t *testing.T) {
   103  				req := &Request{
   104  					Method: "POST",
   105  					Header: test.contentType,
   106  					Body:   io.NopCloser(strings.NewReader("body")),
   107  				}
   108  				err := req.ParseForm()
   109  				switch {
   110  				case err == nil && test.wantErr != "":
   111  					t.Errorf("unexpected success; want error %q", test.wantErr)
   112  				case err != nil && test.wantErr == "":
   113  					t.Errorf("want success, got error: %v", err)
   114  				case test.wantErr != "" && test.wantErr != fmt.Sprint(err):
   115  					t.Errorf("got error %q; want %q", err, test.wantErr)
   116  				}
   117  			},
   118  		)
   119  	}
   120  }
   121  
   122  func TestParseFormInitializeOnError(t *testing.T) {
   123  	nilBody, _ := NewRequest("POST", "http://www.google.com/search?q=foo", nil)
   124  	tests := []*Request{
   125  		nilBody,
   126  		{Method: "GET", URL: nil},
   127  	}
   128  	for i, req := range tests {
   129  		err := req.ParseForm()
   130  		if req.Form == nil {
   131  			t.Errorf("%d. Form not initialized, error %v", i, err)
   132  		}
   133  		if req.PostForm == nil {
   134  			t.Errorf("%d. PostForm not initialized, error %v", i, err)
   135  		}
   136  	}
   137  }
   138  
   139  func TestMultipartReader(t *testing.T) {
   140  	tests := []struct {
   141  		shouldError bool
   142  		contentType string
   143  	}{
   144  		{false, `multipart/form-data; boundary="foo123"`},
   145  		{false, `multipart/mixed; boundary="foo123"`},
   146  		{true, `text/plain`},
   147  	}
   148  
   149  	for i, test := range tests {
   150  		req := &Request{
   151  			Method: "POST",
   152  			Header: Header{"Content-Type": {test.contentType}},
   153  			Body:   io.NopCloser(new(bytes.Buffer)),
   154  		}
   155  		multipart, err := req.MultipartReader()
   156  		if test.shouldError {
   157  			if err == nil || multipart != nil {
   158  				t.Errorf("test %d: unexpectedly got nil-error (%v) or non-nil-multipart (%v)", i, err, multipart)
   159  			}
   160  			continue
   161  		}
   162  		if err != nil || multipart == nil {
   163  			t.Errorf("test %d: unexpectedly got error (%v) or nil-multipart (%v)", i, err, multipart)
   164  		}
   165  	}
   166  }
   167  
   168  // Issue 9305: ParseMultipartForm should populate PostForm too
   169  func TestParseMultipartFormPopulatesPostForm(t *testing.T) {
   170  	postData :=
   171  		`--xxx
   172  Content-Disposition: form-data; name="field1"
   173  
   174  value1
   175  --xxx
   176  Content-Disposition: form-data; name="field2"
   177  
   178  value2
   179  --xxx
   180  Content-Disposition: form-data; name="file"; filename="file"
   181  Content-Type: application/octet-stream
   182  Content-Transfer-Encoding: binary
   183  
   184  binary data
   185  --xxx--
   186  `
   187  	req := &Request{
   188  		Method: "POST",
   189  		Header: Header{"Content-Type": {`multipart/form-data; boundary=xxx`}},
   190  		Body:   io.NopCloser(strings.NewReader(postData)),
   191  	}
   192  
   193  	initialFormItems := map[string]string{
   194  		"language": "Go",
   195  		"name":     "gopher",
   196  		"skill":    "go-ing",
   197  		"field2":   "initial-value2",
   198  	}
   199  
   200  	req.Form = make(url.Values)
   201  	for k, v := range initialFormItems {
   202  		req.Form.Add(k, v)
   203  	}
   204  
   205  	err := req.ParseMultipartForm(10000)
   206  	if err != nil {
   207  		t.Fatalf("unexpected multipart error %v", err)
   208  	}
   209  
   210  	wantForm := url.Values{
   211  		"language": []string{"Go"},
   212  		"name":     []string{"gopher"},
   213  		"skill":    []string{"go-ing"},
   214  		"field1":   []string{"value1"},
   215  		"field2":   []string{"initial-value2", "value2"},
   216  	}
   217  	if !reflect.DeepEqual(req.Form, wantForm) {
   218  		t.Fatalf("req.Form = %v, want %v", req.Form, wantForm)
   219  	}
   220  
   221  	wantPostForm := url.Values{
   222  		"field1": []string{"value1"},
   223  		"field2": []string{"value2"},
   224  	}
   225  	if !reflect.DeepEqual(req.PostForm, wantPostForm) {
   226  		t.Fatalf("req.PostForm = %v, want %v", req.PostForm, wantPostForm)
   227  	}
   228  }
   229  
   230  func TestParseMultipartForm(t *testing.T) {
   231  	req := &Request{
   232  		Method: "POST",
   233  		Header: Header{"Content-Type": {`multipart/form-data; boundary="foo123"`}},
   234  		Body:   io.NopCloser(new(bytes.Buffer)),
   235  	}
   236  	err := req.ParseMultipartForm(25)
   237  	if err == nil {
   238  		t.Error("expected multipart EOF, got nil")
   239  	}
   240  
   241  	req.Header = Header{"Content-Type": {"text/plain"}}
   242  	err = req.ParseMultipartForm(25)
   243  	if err != ErrNotMultipart {
   244  		t.Error("expected ErrNotMultipart for text/plain")
   245  	}
   246  }
   247  
   248  // Issue #40430: Test that if maxMemory for ParseMultipartForm when combined with
   249  // the payload size and the internal leeway buffer size of 10MiB overflows, that we
   250  // correctly return an error.
   251  func TestMaxInt64ForMultipartFormMaxMemoryOverflow(t *testing.T) {
   252  	defer afterTest(t)
   253  
   254  	payloadSize := 1 << 10
   255  	cst := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
   256  		// The combination of:
   257  		//      MaxInt64 + payloadSize + (internal spare of 10MiB)
   258  		// triggers the overflow. See issue https://golang.org/issue/40430/
   259  		if err := req.ParseMultipartForm(math.MaxInt64); err != nil {
   260  			Error(rw, err.Error(), StatusBadRequest)
   261  			return
   262  		}
   263  	}))
   264  	defer cst.Close()
   265  	fBuf := new(bytes.Buffer)
   266  	mw := multipart.NewWriter(fBuf)
   267  	mf, err := mw.CreateFormFile("file", "myfile.txt")
   268  	if err != nil {
   269  		t.Fatal(err)
   270  	}
   271  	if _, err := mf.Write(bytes.Repeat([]byte("abc"), payloadSize)); err != nil {
   272  		t.Fatal(err)
   273  	}
   274  	if err := mw.Close(); err != nil {
   275  		t.Fatal(err)
   276  	}
   277  	req, err := NewRequest("POST", cst.URL, fBuf)
   278  	if err != nil {
   279  		t.Fatal(err)
   280  	}
   281  	req.Header.Set("Content-Type", mw.FormDataContentType())
   282  	res, err := cst.Client().Do(req)
   283  	if err != nil {
   284  		t.Fatal(err)
   285  	}
   286  	res.Body.Close()
   287  	if g, w := res.StatusCode, StatusOK; g != w {
   288  		t.Fatalf("Status code mismatch: got %d, want %d", g, w)
   289  	}
   290  }
   291  
   292  func TestRedirect_h1(t *testing.T) { testRedirect(t, h1Mode) }
   293  func TestRedirect_h2(t *testing.T) { testRedirect(t, h2Mode) }
   294  func testRedirect(t *testing.T, h2 bool) {
   295  	defer afterTest(t)
   296  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
   297  		switch r.URL.Path {
   298  		case "/":
   299  			w.Header().Set("Location", "/foo/")
   300  			w.WriteHeader(StatusSeeOther)
   301  		case "/foo/":
   302  			fmt.Fprintf(w, "foo")
   303  		default:
   304  			w.WriteHeader(StatusBadRequest)
   305  		}
   306  	}))
   307  	defer cst.close()
   308  
   309  	var end = regexp.MustCompile("/foo/$")
   310  	r, err := cst.c.Get(cst.ts.URL)
   311  	if err != nil {
   312  		t.Fatal(err)
   313  	}
   314  	r.Body.Close()
   315  	url := r.Request.URL.String()
   316  	if r.StatusCode != 200 || !end.MatchString(url) {
   317  		t.Fatalf("Get got status %d at %q, want 200 matching /foo/$", r.StatusCode, url)
   318  	}
   319  }
   320  
   321  func TestSetBasicAuth(t *testing.T) {
   322  	r, _ := NewRequest("GET", "http://example.com/", nil)
   323  	r.SetBasicAuth("Aladdin", "open sesame")
   324  	if g, e := r.Header.Get("Authorization"), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; g != e {
   325  		t.Errorf("got header %q, want %q", g, e)
   326  	}
   327  }
   328  
   329  func TestMultipartRequest(t *testing.T) {
   330  	// Test that we can read the values and files of a
   331  	// multipart request with FormValue and FormFile,
   332  	// and that ParseMultipartForm can be called multiple times.
   333  	req := newTestMultipartRequest(t)
   334  	if err := req.ParseMultipartForm(25); err != nil {
   335  		t.Fatal("ParseMultipartForm first call:", err)
   336  	}
   337  	defer req.MultipartForm.RemoveAll()
   338  	validateTestMultipartContents(t, req, false)
   339  	if err := req.ParseMultipartForm(25); err != nil {
   340  		t.Fatal("ParseMultipartForm second call:", err)
   341  	}
   342  	validateTestMultipartContents(t, req, false)
   343  }
   344  
   345  func TestMultipartRequestAuto(t *testing.T) {
   346  	// Test that FormValue and FormFile automatically invoke
   347  	// ParseMultipartForm and return the right values.
   348  	req := newTestMultipartRequest(t)
   349  	defer func() {
   350  		if req.MultipartForm != nil {
   351  			req.MultipartForm.RemoveAll()
   352  		}
   353  	}()
   354  	validateTestMultipartContents(t, req, true)
   355  }
   356  
   357  func TestMissingFileMultipartRequest(t *testing.T) {
   358  	// Test that FormFile returns an error if
   359  	// the named file is missing.
   360  	req := newTestMultipartRequest(t)
   361  	testMissingFile(t, req)
   362  }
   363  
   364  // Test that FormValue invokes ParseMultipartForm.
   365  func TestFormValueCallsParseMultipartForm(t *testing.T) {
   366  	req, _ := NewRequest("POST", "http://www.google.com/", strings.NewReader("z=post"))
   367  	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
   368  	if req.Form != nil {
   369  		t.Fatal("Unexpected request Form, want nil")
   370  	}
   371  	req.FormValue("z")
   372  	if req.Form == nil {
   373  		t.Fatal("ParseMultipartForm not called by FormValue")
   374  	}
   375  }
   376  
   377  // Test that FormFile invokes ParseMultipartForm.
   378  func TestFormFileCallsParseMultipartForm(t *testing.T) {
   379  	req := newTestMultipartRequest(t)
   380  	if req.Form != nil {
   381  		t.Fatal("Unexpected request Form, want nil")
   382  	}
   383  	req.FormFile("")
   384  	if req.Form == nil {
   385  		t.Fatal("ParseMultipartForm not called by FormFile")
   386  	}
   387  }
   388  
   389  // Test that ParseMultipartForm errors if called
   390  // after MultipartReader on the same request.
   391  func TestParseMultipartFormOrder(t *testing.T) {
   392  	req := newTestMultipartRequest(t)
   393  	if _, err := req.MultipartReader(); err != nil {
   394  		t.Fatalf("MultipartReader: %v", err)
   395  	}
   396  	if err := req.ParseMultipartForm(1024); err == nil {
   397  		t.Fatal("expected an error from ParseMultipartForm after call to MultipartReader")
   398  	}
   399  }
   400  
   401  // Test that MultipartReader errors if called
   402  // after ParseMultipartForm on the same request.
   403  func TestMultipartReaderOrder(t *testing.T) {
   404  	req := newTestMultipartRequest(t)
   405  	if err := req.ParseMultipartForm(25); err != nil {
   406  		t.Fatalf("ParseMultipartForm: %v", err)
   407  	}
   408  	defer req.MultipartForm.RemoveAll()
   409  	if _, err := req.MultipartReader(); err == nil {
   410  		t.Fatal("expected an error from MultipartReader after call to ParseMultipartForm")
   411  	}
   412  }
   413  
   414  // Test that FormFile errors if called after
   415  // MultipartReader on the same request.
   416  func TestFormFileOrder(t *testing.T) {
   417  	req := newTestMultipartRequest(t)
   418  	if _, err := req.MultipartReader(); err != nil {
   419  		t.Fatalf("MultipartReader: %v", err)
   420  	}
   421  	if _, _, err := req.FormFile(""); err == nil {
   422  		t.Fatal("expected an error from FormFile after call to MultipartReader")
   423  	}
   424  }
   425  
   426  var readRequestErrorTests = []struct {
   427  	in  string
   428  	err string
   429  
   430  	header Header
   431  }{
   432  	0: {"GET / HTTP/1.1\r\nheader:foo\r\n\r\n", "", Header{"Header": {"foo"}}},
   433  	1: {"GET / HTTP/1.1\r\nheader:foo\r\n", io.ErrUnexpectedEOF.Error(), nil},
   434  	2: {"", io.EOF.Error(), nil},
   435  	3: {
   436  		in:  "HEAD / HTTP/1.1\r\nContent-Length:4\r\n\r\n",
   437  		err: "http: method cannot contain a Content-Length",
   438  	},
   439  	4: {
   440  		in:     "HEAD / HTTP/1.1\r\n\r\n",
   441  		header: Header{},
   442  	},
   443  
   444  	// Multiple Content-Length values should either be
   445  	// deduplicated if same or reject otherwise
   446  	// See Issue 16490.
   447  	5: {
   448  		in:  "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 0\r\n\r\nGopher hey\r\n",
   449  		err: "cannot contain multiple Content-Length headers",
   450  	},
   451  	6: {
   452  		in:  "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 6\r\n\r\nGopher\r\n",
   453  		err: "cannot contain multiple Content-Length headers",
   454  	},
   455  	7: {
   456  		in:     "PUT / HTTP/1.1\r\nContent-Length: 6 \r\nContent-Length: 6\r\nContent-Length:6\r\n\r\nGopher\r\n",
   457  		err:    "",
   458  		header: Header{"Content-Length": {"6"}},
   459  	},
   460  	8: {
   461  		in:  "PUT / HTTP/1.1\r\nContent-Length: 1\r\nContent-Length: 6 \r\n\r\n",
   462  		err: "cannot contain multiple Content-Length headers",
   463  	},
   464  	9: {
   465  		in:  "POST / HTTP/1.1\r\nContent-Length:\r\nContent-Length: 3\r\n\r\n",
   466  		err: "cannot contain multiple Content-Length headers",
   467  	},
   468  	10: {
   469  		in:     "HEAD / HTTP/1.1\r\nContent-Length:0\r\nContent-Length: 0\r\n\r\n",
   470  		header: Header{"Content-Length": {"0"}},
   471  	},
   472  }
   473  
   474  func TestReadRequestErrors(t *testing.T) {
   475  	for i, tt := range readRequestErrorTests {
   476  		req, err := ReadRequest(bufio.NewReader(strings.NewReader(tt.in)))
   477  		if err == nil {
   478  			if tt.err != "" {
   479  				t.Errorf("#%d: got nil err; want %q", i, tt.err)
   480  			}
   481  
   482  			if !reflect.DeepEqual(tt.header, req.Header) {
   483  				t.Errorf("#%d: gotHeader: %q wantHeader: %q", i, req.Header, tt.header)
   484  			}
   485  			continue
   486  		}
   487  
   488  		if tt.err == "" || !strings.Contains(err.Error(), tt.err) {
   489  			t.Errorf("%d: got error = %v; want %v", i, err, tt.err)
   490  		}
   491  	}
   492  }
   493  
   494  var newRequestHostTests = []struct {
   495  	in, out string
   496  }{
   497  	{"http://www.example.com/", "www.example.com"},
   498  	{"http://www.example.com:8080/", "www.example.com:8080"},
   499  
   500  	{"http://192.168.0.1/", "192.168.0.1"},
   501  	{"http://192.168.0.1:8080/", "192.168.0.1:8080"},
   502  	{"http://192.168.0.1:/", "192.168.0.1"},
   503  
   504  	{"http://[fe80::1]/", "[fe80::1]"},
   505  	{"http://[fe80::1]:8080/", "[fe80::1]:8080"},
   506  	{"http://[fe80::1%25en0]/", "[fe80::1%en0]"},
   507  	{"http://[fe80::1%25en0]:8080/", "[fe80::1%en0]:8080"},
   508  	{"http://[fe80::1%25en0]:/", "[fe80::1%en0]"},
   509  }
   510  
   511  func TestNewRequestHost(t *testing.T) {
   512  	for i, tt := range newRequestHostTests {
   513  		req, err := NewRequest("GET", tt.in, nil)
   514  		if err != nil {
   515  			t.Errorf("#%v: %v", i, err)
   516  			continue
   517  		}
   518  		if req.Host != tt.out {
   519  			t.Errorf("got %q; want %q", req.Host, tt.out)
   520  		}
   521  	}
   522  }
   523  
   524  func TestRequestInvalidMethod(t *testing.T) {
   525  	_, err := NewRequest("bad method", "http://foo.com/", nil)
   526  	if err == nil {
   527  		t.Error("expected error from NewRequest with invalid method")
   528  	}
   529  	req, err := NewRequest("GET", "http://foo.example/", nil)
   530  	if err != nil {
   531  		t.Fatal(err)
   532  	}
   533  	req.Method = "bad method"
   534  	_, err = DefaultClient.Do(req)
   535  	if err == nil || !strings.Contains(err.Error(), "invalid method") {
   536  		t.Errorf("Transport error = %v; want invalid method", err)
   537  	}
   538  
   539  	req, err = NewRequest("", "http://foo.com/", nil)
   540  	if err != nil {
   541  		t.Errorf("NewRequest(empty method) = %v; want nil", err)
   542  	} else if req.Method != "GET" {
   543  		t.Errorf("NewRequest(empty method) has method %q; want GET", req.Method)
   544  	}
   545  }
   546  
   547  func TestNewRequestContentLength(t *testing.T) {
   548  	readByte := func(r io.Reader) io.Reader {
   549  		var b [1]byte
   550  		r.Read(b[:])
   551  		return r
   552  	}
   553  	tests := []struct {
   554  		r    io.Reader
   555  		want int64
   556  	}{
   557  		{bytes.NewReader([]byte("123")), 3},
   558  		{bytes.NewBuffer([]byte("1234")), 4},
   559  		{strings.NewReader("12345"), 5},
   560  		{strings.NewReader(""), 0},
   561  		{NoBody, 0},
   562  
   563  		// Not detected. During Go 1.8 we tried to make these set to -1, but
   564  		// due to Issue 18117, we keep these returning 0, even though they're
   565  		// unknown.
   566  		{struct{ io.Reader }{strings.NewReader("xyz")}, 0},
   567  		{io.NewSectionReader(strings.NewReader("x"), 0, 6), 0},
   568  		{readByte(io.NewSectionReader(strings.NewReader("xy"), 0, 6)), 0},
   569  	}
   570  	for i, tt := range tests {
   571  		req, err := NewRequest("POST", "http://localhost/", tt.r)
   572  		if err != nil {
   573  			t.Fatal(err)
   574  		}
   575  		if req.ContentLength != tt.want {
   576  			t.Errorf("test[%d]: ContentLength(%T) = %d; want %d", i, tt.r, req.ContentLength, tt.want)
   577  		}
   578  	}
   579  }
   580  
   581  var parseHTTPVersionTests = []struct {
   582  	vers         string
   583  	major, minor int
   584  	ok           bool
   585  }{
   586  	{"HTTP/0.9", 0, 9, true},
   587  	{"HTTP/1.0", 1, 0, true},
   588  	{"HTTP/1.1", 1, 1, true},
   589  	{"HTTP/3.14", 3, 14, true},
   590  
   591  	{"HTTP", 0, 0, false},
   592  	{"HTTP/one.one", 0, 0, false},
   593  	{"HTTP/1.1/", 0, 0, false},
   594  	{"HTTP/-1,0", 0, 0, false},
   595  	{"HTTP/0,-1", 0, 0, false},
   596  	{"HTTP/", 0, 0, false},
   597  	{"HTTP/1,1", 0, 0, false},
   598  }
   599  
   600  func TestParseHTTPVersion(t *testing.T) {
   601  	for _, tt := range parseHTTPVersionTests {
   602  		major, minor, ok := ParseHTTPVersion(tt.vers)
   603  		if ok != tt.ok || major != tt.major || minor != tt.minor {
   604  			type version struct {
   605  				major, minor int
   606  				ok           bool
   607  			}
   608  			t.Errorf("failed to parse %q, expected: %#v, got %#v", tt.vers, version{tt.major, tt.minor, tt.ok}, version{major, minor, ok})
   609  		}
   610  	}
   611  }
   612  
   613  type getBasicAuthTest struct {
   614  	username, password string
   615  	ok                 bool
   616  }
   617  
   618  type basicAuthCredentialsTest struct {
   619  	username, password string
   620  }
   621  
   622  var getBasicAuthTests = []struct {
   623  	username, password string
   624  	ok                 bool
   625  }{
   626  	{"Aladdin", "open sesame", true},
   627  	{"Aladdin", "open:sesame", true},
   628  	{"", "", true},
   629  }
   630  
   631  func TestGetBasicAuth(t *testing.T) {
   632  	for _, tt := range getBasicAuthTests {
   633  		r, _ := NewRequest("GET", "http://example.com/", nil)
   634  		r.SetBasicAuth(tt.username, tt.password)
   635  		username, password, ok := r.BasicAuth()
   636  		if ok != tt.ok || username != tt.username || password != tt.password {
   637  			t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok},
   638  				getBasicAuthTest{tt.username, tt.password, tt.ok})
   639  		}
   640  	}
   641  	// Unauthenticated request.
   642  	r, _ := NewRequest("GET", "http://example.com/", nil)
   643  	username, password, ok := r.BasicAuth()
   644  	if ok {
   645  		t.Errorf("expected false from BasicAuth when the request is unauthenticated")
   646  	}
   647  	want := basicAuthCredentialsTest{"", ""}
   648  	if username != want.username || password != want.password {
   649  		t.Errorf("expected credentials: %#v when the request is unauthenticated, got %#v",
   650  			want, basicAuthCredentialsTest{username, password})
   651  	}
   652  }
   653  
   654  var parseBasicAuthTests = []struct {
   655  	header, username, password string
   656  	ok                         bool
   657  }{
   658  	{"Basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "Aladdin", "open sesame", true},
   659  
   660  	// Case doesn't matter:
   661  	{"BASIC " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "Aladdin", "open sesame", true},
   662  	{"basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "Aladdin", "open sesame", true},
   663  
   664  	{"Basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open:sesame")), "Aladdin", "open:sesame", true},
   665  	{"Basic " + base64.StdEncoding.EncodeToString([]byte(":")), "", "", true},
   666  	{"Basic" + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "", "", false},
   667  	{base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "", "", false},
   668  	{"Basic ", "", "", false},
   669  	{"Basic Aladdin:open sesame", "", "", false},
   670  	{`Digest username="Aladdin"`, "", "", false},
   671  }
   672  
   673  func TestParseBasicAuth(t *testing.T) {
   674  	for _, tt := range parseBasicAuthTests {
   675  		r, _ := NewRequest("GET", "http://example.com/", nil)
   676  		r.Header.Set("Authorization", tt.header)
   677  		username, password, ok := r.BasicAuth()
   678  		if ok != tt.ok || username != tt.username || password != tt.password {
   679  			t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok},
   680  				getBasicAuthTest{tt.username, tt.password, tt.ok})
   681  		}
   682  	}
   683  }
   684  
   685  type logWrites struct {
   686  	t   *testing.T
   687  	dst *[]string
   688  }
   689  
   690  func (l logWrites) WriteByte(c byte) error {
   691  	l.t.Fatalf("unexpected WriteByte call")
   692  	return nil
   693  }
   694  
   695  func (l logWrites) Write(p []byte) (n int, err error) {
   696  	*l.dst = append(*l.dst, string(p))
   697  	return len(p), nil
   698  }
   699  
   700  func TestRequestWriteBufferedWriter(t *testing.T) {
   701  	got := []string{}
   702  	req, _ := NewRequest("GET", "http://foo.com/", nil)
   703  	req.Write(logWrites{t, &got})
   704  	want := []string{
   705  		"GET / HTTP/1.1\r\n",
   706  		"Host: foo.com\r\n",
   707  		"User-Agent: " + DefaultUserAgent + "\r\n",
   708  		"\r\n",
   709  	}
   710  	if !reflect.DeepEqual(got, want) {
   711  		t.Errorf("Writes = %q\n  Want = %q", got, want)
   712  	}
   713  }
   714  
   715  func TestRequestBadHost(t *testing.T) {
   716  	got := []string{}
   717  	req, err := NewRequest("GET", "http://foo/after", nil)
   718  	if err != nil {
   719  		t.Fatal(err)
   720  	}
   721  	req.Host = "foo.com with spaces"
   722  	req.URL.Host = "foo.com with spaces"
   723  	req.Write(logWrites{t, &got})
   724  	want := []string{
   725  		"GET /after HTTP/1.1\r\n",
   726  		"Host: foo.com\r\n",
   727  		"User-Agent: " + DefaultUserAgent + "\r\n",
   728  		"\r\n",
   729  	}
   730  	if !reflect.DeepEqual(got, want) {
   731  		t.Errorf("Writes = %q\n  Want = %q", got, want)
   732  	}
   733  }
   734  
   735  func TestStarRequest(t *testing.T) {
   736  	req, err := ReadRequest(bufio.NewReader(strings.NewReader("M-SEARCH * HTTP/1.1\r\n\r\n")))
   737  	if err != nil {
   738  		return
   739  	}
   740  	if req.ContentLength != 0 {
   741  		t.Errorf("ContentLength = %d; want 0", req.ContentLength)
   742  	}
   743  	if req.Body == nil {
   744  		t.Errorf("Body = nil; want non-nil")
   745  	}
   746  
   747  	// Request.Write has Client semantics for Body/ContentLength,
   748  	// where ContentLength 0 means unknown if Body is non-nil, and
   749  	// thus chunking will happen unless we change semantics and
   750  	// signal that we want to serialize it as exactly zero.  The
   751  	// only way to do that for outbound requests is with a nil
   752  	// Body:
   753  	clientReq := *req
   754  	clientReq.Body = nil
   755  
   756  	var out bytes.Buffer
   757  	if err := clientReq.Write(&out); err != nil {
   758  		t.Fatal(err)
   759  	}
   760  
   761  	if strings.Contains(out.String(), "chunked") {
   762  		t.Error("wrote chunked request; want no body")
   763  	}
   764  	back, err := ReadRequest(bufio.NewReader(bytes.NewReader(out.Bytes())))
   765  	if err != nil {
   766  		t.Fatal(err)
   767  	}
   768  	// Ignore the Headers (the User-Agent breaks the deep equal,
   769  	// but we don't care about it)
   770  	req.Header = nil
   771  	back.Header = nil
   772  	if !reflect.DeepEqual(req, back) {
   773  		t.Errorf("Original request doesn't match Request read back.")
   774  		t.Logf("Original: %#v", req)
   775  		t.Logf("Original.URL: %#v", req.URL)
   776  		t.Logf("Wrote: %s", out.Bytes())
   777  		t.Logf("Read back (doesn't match Original): %#v", back)
   778  	}
   779  }
   780  
   781  type responseWriterJustWriter struct {
   782  	io.Writer
   783  }
   784  
   785  func (responseWriterJustWriter) Header() Header  { panic("should not be called") }
   786  func (responseWriterJustWriter) WriteHeader(int) { panic("should not be called") }
   787  
   788  // delayedEOFReader never returns (n > 0, io.EOF), instead putting
   789  // off the io.EOF until a subsequent Read call.
   790  type delayedEOFReader struct {
   791  	r io.Reader
   792  }
   793  
   794  func (dr delayedEOFReader) Read(p []byte) (n int, err error) {
   795  	n, err = dr.r.Read(p)
   796  	if n > 0 && err == io.EOF {
   797  		err = nil
   798  	}
   799  	return
   800  }
   801  
   802  func TestIssue10884_MaxBytesEOF(t *testing.T) {
   803  	dst := io.Discard
   804  	_, err := io.Copy(dst, MaxBytesReader(
   805  		responseWriterJustWriter{dst},
   806  		io.NopCloser(delayedEOFReader{strings.NewReader("12345")}),
   807  		5))
   808  	if err != nil {
   809  		t.Fatal(err)
   810  	}
   811  }
   812  
   813  // Issue 14981: MaxBytesReader's return error wasn't sticky. It
   814  // doesn't technically need to be, but people expected it to be.
   815  func TestMaxBytesReaderStickyError(t *testing.T) {
   816  	isSticky := func(r io.Reader) error {
   817  		var log bytes.Buffer
   818  		buf := make([]byte, 1000)
   819  		var firstErr error
   820  		for {
   821  			n, err := r.Read(buf)
   822  			fmt.Fprintf(&log, "Read(%d) = %d, %v\n", len(buf), n, err)
   823  			if err == nil {
   824  				continue
   825  			}
   826  			if firstErr == nil {
   827  				firstErr = err
   828  				continue
   829  			}
   830  			if !reflect.DeepEqual(err, firstErr) {
   831  				return fmt.Errorf("non-sticky error. got log:\n%s", log.Bytes())
   832  			}
   833  			t.Logf("Got log: %s", log.Bytes())
   834  			return nil
   835  		}
   836  	}
   837  	tests := [...]struct {
   838  		readable int
   839  		limit    int64
   840  	}{
   841  		0: {99, 100},
   842  		1: {100, 100},
   843  		2: {101, 100},
   844  	}
   845  	for i, tt := range tests {
   846  		rc := MaxBytesReader(nil, io.NopCloser(bytes.NewReader(make([]byte, tt.readable))), tt.limit)
   847  		if err := isSticky(rc); err != nil {
   848  			t.Errorf("%d. error: %v", i, err)
   849  		}
   850  	}
   851  }
   852  
   853  func TestWithContextDeepCopiesURL(t *testing.T) {
   854  	req, err := NewRequest("POST", "https://golang.org/", nil)
   855  	if err != nil {
   856  		t.Fatal(err)
   857  	}
   858  
   859  	reqCopy := req.WithContext(context.Background())
   860  	reqCopy.URL.Scheme = "http"
   861  
   862  	firstURL, secondURL := req.URL.String(), reqCopy.URL.String()
   863  	if firstURL == secondURL {
   864  		t.Errorf("unexpected change to original request's URL")
   865  	}
   866  
   867  	// And also check we don't crash on nil (Issue 20601)
   868  	req.URL = nil
   869  	reqCopy = req.WithContext(context.Background())
   870  	if reqCopy.URL != nil {
   871  		t.Error("expected nil URL in cloned request")
   872  	}
   873  }
   874  
   875  // Ensure that Request.Clone creates a deep copy of TransferEncoding.
   876  // See issue 41907.
   877  func TestRequestCloneTransferEncoding(t *testing.T) {
   878  	body := strings.NewReader("body")
   879  	req, _ := NewRequest("POST", "https://example.org/", body)
   880  	req.TransferEncoding = []string{
   881  		"encoding1",
   882  	}
   883  
   884  	clonedReq := req.Clone(context.Background())
   885  	// modify original after deep copy
   886  	req.TransferEncoding[0] = "encoding2"
   887  
   888  	if req.TransferEncoding[0] != "encoding2" {
   889  		t.Error("expected req.TransferEncoding to be changed")
   890  	}
   891  	if clonedReq.TransferEncoding[0] != "encoding1" {
   892  		t.Error("expected clonedReq.TransferEncoding to be unchanged")
   893  	}
   894  }
   895  
   896  func TestNoPanicOnRoundTripWithBasicAuth_h1(t *testing.T) {
   897  	testNoPanicWithBasicAuth(t, h1Mode)
   898  }
   899  
   900  func TestNoPanicOnRoundTripWithBasicAuth_h2(t *testing.T) {
   901  	testNoPanicWithBasicAuth(t, h2Mode)
   902  }
   903  
   904  // Issue 34878: verify we don't panic when including basic auth (Go 1.13 regression)
   905  func testNoPanicWithBasicAuth(t *testing.T, h2 bool) {
   906  	defer afterTest(t)
   907  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {}))
   908  	defer cst.close()
   909  
   910  	u, err := url.Parse(cst.ts.URL)
   911  	if err != nil {
   912  		t.Fatal(err)
   913  	}
   914  	u.User = url.UserPassword("foo", "bar")
   915  	req := &Request{
   916  		URL:    u,
   917  		Method: "GET",
   918  	}
   919  	if _, err := cst.c.Do(req); err != nil {
   920  		t.Fatalf("Unexpected error: %v", err)
   921  	}
   922  }
   923  
   924  // verify that NewRequest sets Request.GetBody and that it works
   925  func TestNewRequestGetBody(t *testing.T) {
   926  	tests := []struct {
   927  		r io.Reader
   928  	}{
   929  		{r: strings.NewReader("hello")},
   930  		{r: bytes.NewReader([]byte("hello"))},
   931  		{r: bytes.NewBuffer([]byte("hello"))},
   932  	}
   933  	for i, tt := range tests {
   934  		req, err := NewRequest("POST", "http://foo.tld/", tt.r)
   935  		if err != nil {
   936  			t.Errorf("test[%d]: %v", i, err)
   937  			continue
   938  		}
   939  		if req.Body == nil {
   940  			t.Errorf("test[%d]: Body = nil", i)
   941  			continue
   942  		}
   943  		if req.GetBody == nil {
   944  			t.Errorf("test[%d]: GetBody = nil", i)
   945  			continue
   946  		}
   947  		slurp1, err := io.ReadAll(req.Body)
   948  		if err != nil {
   949  			t.Errorf("test[%d]: ReadAll(Body) = %v", i, err)
   950  		}
   951  		newBody, err := req.GetBody()
   952  		if err != nil {
   953  			t.Errorf("test[%d]: GetBody = %v", i, err)
   954  		}
   955  		slurp2, err := io.ReadAll(newBody)
   956  		if err != nil {
   957  			t.Errorf("test[%d]: ReadAll(GetBody()) = %v", i, err)
   958  		}
   959  		if string(slurp1) != string(slurp2) {
   960  			t.Errorf("test[%d]: Body %q != GetBody %q", i, slurp1, slurp2)
   961  		}
   962  	}
   963  }
   964  
   965  func testMissingFile(t *testing.T, req *Request) {
   966  	f, fh, err := req.FormFile("missing")
   967  	if f != nil {
   968  		t.Errorf("FormFile file = %v, want nil", f)
   969  	}
   970  	if fh != nil {
   971  		t.Errorf("FormFile file header = %q, want nil", fh)
   972  	}
   973  	if err != ErrMissingFile {
   974  		t.Errorf("FormFile err = %q, want ErrMissingFile", err)
   975  	}
   976  }
   977  
   978  func newTestMultipartRequest(t *testing.T) *Request {
   979  	b := strings.NewReader(strings.ReplaceAll(message, "\n", "\r\n"))
   980  	req, err := NewRequest("POST", "/", b)
   981  	if err != nil {
   982  		t.Fatal("NewRequest:", err)
   983  	}
   984  	ctype := fmt.Sprintf(`multipart/form-data; boundary="%s"`, boundary)
   985  	req.Header.Set("Content-type", ctype)
   986  	return req
   987  }
   988  
   989  func validateTestMultipartContents(t *testing.T, req *Request, allMem bool) {
   990  	if g, e := req.FormValue("texta"), textaValue; g != e {
   991  		t.Errorf("texta value = %q, want %q", g, e)
   992  	}
   993  	if g, e := req.FormValue("textb"), textbValue; g != e {
   994  		t.Errorf("textb value = %q, want %q", g, e)
   995  	}
   996  	if g := req.FormValue("missing"); g != "" {
   997  		t.Errorf("missing value = %q, want empty string", g)
   998  	}
   999  
  1000  	assertMem := func(n string, fd multipart.File) {
  1001  		if _, ok := fd.(*os.File); ok {
  1002  			t.Error(n, " is *os.File, should not be")
  1003  		}
  1004  	}
  1005  	fda := testMultipartFile(t, req, "filea", "filea.txt", fileaContents)
  1006  	defer fda.Close()
  1007  	assertMem("filea", fda)
  1008  	fdb := testMultipartFile(t, req, "fileb", "fileb.txt", filebContents)
  1009  	defer fdb.Close()
  1010  	if allMem {
  1011  		assertMem("fileb", fdb)
  1012  	} else {
  1013  		if _, ok := fdb.(*os.File); !ok {
  1014  			t.Errorf("fileb has unexpected underlying type %T", fdb)
  1015  		}
  1016  	}
  1017  
  1018  	testMissingFile(t, req)
  1019  }
  1020  
  1021  func testMultipartFile(t *testing.T, req *Request, key, expectFilename, expectContent string) multipart.File {
  1022  	f, fh, err := req.FormFile(key)
  1023  	if err != nil {
  1024  		t.Fatalf("FormFile(%q): %q", key, err)
  1025  	}
  1026  	if fh.Filename != expectFilename {
  1027  		t.Errorf("filename = %q, want %q", fh.Filename, expectFilename)
  1028  	}
  1029  	var b bytes.Buffer
  1030  	_, err = io.Copy(&b, f)
  1031  	if err != nil {
  1032  		t.Fatal("copying contents:", err)
  1033  	}
  1034  	if g := b.String(); g != expectContent {
  1035  		t.Errorf("contents = %q, want %q", g, expectContent)
  1036  	}
  1037  	return f
  1038  }
  1039  
  1040  const (
  1041  	fileaContents = "This is a test file."
  1042  	filebContents = "Another test file."
  1043  	textaValue    = "foo"
  1044  	textbValue    = "bar"
  1045  	boundary      = `MyBoundary`
  1046  )
  1047  
  1048  const message = `
  1049  --MyBoundary
  1050  Content-Disposition: form-data; name="filea"; filename="filea.txt"
  1051  Content-Type: text/plain
  1052  
  1053  ` + fileaContents + `
  1054  --MyBoundary
  1055  Content-Disposition: form-data; name="fileb"; filename="fileb.txt"
  1056  Content-Type: text/plain
  1057  
  1058  ` + filebContents + `
  1059  --MyBoundary
  1060  Content-Disposition: form-data; name="texta"
  1061  
  1062  ` + textaValue + `
  1063  --MyBoundary
  1064  Content-Disposition: form-data; name="textb"
  1065  
  1066  ` + textbValue + `
  1067  --MyBoundary--
  1068  `
  1069  
  1070  func benchmarkReadRequest(b *testing.B, request string) {
  1071  	request = request + "\n"                            // final \n
  1072  	request = strings.ReplaceAll(request, "\n", "\r\n") // expand \n to \r\n
  1073  	b.SetBytes(int64(len(request)))
  1074  	r := bufio.NewReader(&infiniteReader{buf: []byte(request)})
  1075  	b.ReportAllocs()
  1076  	b.ResetTimer()
  1077  	for i := 0; i < b.N; i++ {
  1078  		_, err := ReadRequest(r)
  1079  		if err != nil {
  1080  			b.Fatalf("failed to read request: %v", err)
  1081  		}
  1082  	}
  1083  }
  1084  
  1085  // infiniteReader satisfies Read requests as if the contents of buf
  1086  // loop indefinitely.
  1087  type infiniteReader struct {
  1088  	buf    []byte
  1089  	offset int
  1090  }
  1091  
  1092  func (r *infiniteReader) Read(b []byte) (int, error) {
  1093  	n := copy(b, r.buf[r.offset:])
  1094  	r.offset = (r.offset + n) % len(r.buf)
  1095  	return n, nil
  1096  }
  1097  
  1098  func BenchmarkReadRequestChrome(b *testing.B) {
  1099  	// https://github.com/felixge/node-http-perf/blob/master/fixtures/get.http
  1100  	benchmarkReadRequest(b, `GET / HTTP/1.1
  1101  Host: localhost:8080
  1102  Connection: keep-alive
  1103  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  1104  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
  1105  Accept-Encoding: gzip,deflate,sdch
  1106  Accept-Language: en-US,en;q=0.8
  1107  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  1108  Cookie: __utma=1.1978842379.1323102373.1323102373.1323102373.1; EPi:NumberOfVisits=1,2012-02-28T13:42:18; CrmSession=5b707226b9563e1bc69084d07a107c98; plushContainerWidth=100%25; plushNoTopMenu=0; hudson_auto_refresh=false
  1109  `)
  1110  }
  1111  
  1112  func BenchmarkReadRequestCurl(b *testing.B) {
  1113  	// curl http://localhost:8080/
  1114  	benchmarkReadRequest(b, `GET / HTTP/1.1
  1115  User-Agent: curl/7.27.0
  1116  Host: localhost:8080
  1117  Accept: */*
  1118  `)
  1119  }
  1120  
  1121  func BenchmarkReadRequestApachebench(b *testing.B) {
  1122  	// ab -n 1 -c 1 http://localhost:8080/
  1123  	benchmarkReadRequest(b, `GET / HTTP/1.0
  1124  Host: localhost:8080
  1125  User-Agent: ApacheBench/2.3
  1126  Accept: */*
  1127  `)
  1128  }
  1129  
  1130  func BenchmarkReadRequestSiege(b *testing.B) {
  1131  	// siege -r 1 -c 1 http://localhost:8080/
  1132  	benchmarkReadRequest(b, `GET / HTTP/1.1
  1133  Host: localhost:8080
  1134  Accept: */*
  1135  Accept-Encoding: gzip
  1136  User-Agent: JoeDog/1.00 [en] (X11; I; Siege 2.70)
  1137  Connection: keep-alive
  1138  `)
  1139  }
  1140  
  1141  func BenchmarkReadRequestWrk(b *testing.B) {
  1142  	// wrk -t 1 -r 1 -c 1 http://localhost:8080/
  1143  	benchmarkReadRequest(b, `GET / HTTP/1.1
  1144  Host: localhost:8080
  1145  `)
  1146  }
  1147  
  1148  const (
  1149  	withTLS = true
  1150  	noTLS   = false
  1151  )
  1152  
  1153  func BenchmarkFileAndServer_1KB(b *testing.B) {
  1154  	benchmarkFileAndServer(b, 1<<10)
  1155  }
  1156  
  1157  func BenchmarkFileAndServer_16MB(b *testing.B) {
  1158  	benchmarkFileAndServer(b, 1<<24)
  1159  }
  1160  
  1161  func BenchmarkFileAndServer_64MB(b *testing.B) {
  1162  	benchmarkFileAndServer(b, 1<<26)
  1163  }
  1164  
  1165  func benchmarkFileAndServer(b *testing.B, n int64) {
  1166  	f, err := os.CreateTemp(os.TempDir(), "go-bench-http-file-and-server")
  1167  	if err != nil {
  1168  		b.Fatalf("Failed to create temp file: %v", err)
  1169  	}
  1170  
  1171  	defer func() {
  1172  		f.Close()
  1173  		os.RemoveAll(f.Name())
  1174  	}()
  1175  
  1176  	if _, err := io.CopyN(f, rand.Reader, n); err != nil {
  1177  		b.Fatalf("Failed to copy %d bytes: %v", n, err)
  1178  	}
  1179  
  1180  	b.Run("NoTLS", func(b *testing.B) {
  1181  		runFileAndServerBenchmarks(b, noTLS, f, n)
  1182  	})
  1183  
  1184  	b.Run("TLS", func(b *testing.B) {
  1185  		runFileAndServerBenchmarks(b, withTLS, f, n)
  1186  	})
  1187  }
  1188  
  1189  func runFileAndServerBenchmarks(b *testing.B, tlsOption bool, f *os.File, n int64) {
  1190  	handler := HandlerFunc(func(rw ResponseWriter, req *Request) {
  1191  		defer req.Body.Close()
  1192  		nc, err := io.Copy(io.Discard, req.Body)
  1193  		if err != nil {
  1194  			panic(err)
  1195  		}
  1196  
  1197  		if nc != n {
  1198  			panic(fmt.Errorf("Copied %d Wanted %d bytes", nc, n))
  1199  		}
  1200  	})
  1201  
  1202  	var cst *httptest.Server
  1203  	if tlsOption == withTLS {
  1204  		cst = httptest.NewTLSServer(handler)
  1205  	} else {
  1206  		cst = httptest.NewServer(handler)
  1207  	}
  1208  
  1209  	defer cst.Close()
  1210  	b.ResetTimer()
  1211  	for i := 0; i < b.N; i++ {
  1212  		// Perform some setup.
  1213  		b.StopTimer()
  1214  		if _, err := f.Seek(0, 0); err != nil {
  1215  			b.Fatalf("Failed to seek back to file: %v", err)
  1216  		}
  1217  
  1218  		b.StartTimer()
  1219  		req, err := NewRequest("PUT", cst.URL, io.NopCloser(f))
  1220  		if err != nil {
  1221  			b.Fatal(err)
  1222  		}
  1223  
  1224  		req.ContentLength = n
  1225  		// Prevent mime sniffing by setting the Content-Type.
  1226  		req.Header.Set("Content-Type", "application/octet-stream")
  1227  		res, err := cst.Client().Do(req)
  1228  		if err != nil {
  1229  			b.Fatalf("Failed to make request to backend: %v", err)
  1230  		}
  1231  
  1232  		res.Body.Close()
  1233  		b.SetBytes(n)
  1234  	}
  1235  }