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.
26 func TestQuery(t *testing.T) {
27 req := &Request{Method: "GET"}
28 req.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar")
29 if q := req.FormValue("q"); q != "foo" {
30 t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
34 // Issue #25192: Test that ParseForm fails but still parses the form when a URL
35 // containing a semicolon is provided.
36 func TestParseFormSemicolonSeparator(t *testing.T) {
37 for _, method := range []string{"POST", "PATCH", "PUT", "GET"} {
38 req, _ := NewRequest(method, "http://www.google.com/search?q=foo;q=bar&a=1",
39 strings.NewReader("q"))
40 err := req.ParseForm()
42 t.Fatalf(`for method %s, ParseForm expected an error, got success`, method)
44 wantForm := url.Values{"a": []string{"1"}}
45 if !reflect.DeepEqual(req.Form, wantForm) {
46 t.Fatalf("for method %s, ParseForm expected req.Form = %v, want %v", method, req.Form, wantForm)
51 func TestParseFormQuery(t *testing.T) {
52 req, _ := NewRequest("POST", "http://www.google.com/search?q=foo&q=bar&both=x&prio=1&orphan=nope&empty=not",
53 strings.NewReader("z=post&both=y&prio=2&=nokey&orphan&empty=&"))
54 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
56 if q := req.FormValue("q"); q != "foo" {
57 t.Errorf(`req.FormValue("q") = %q, want "foo"`, q)
59 if z := req.FormValue("z"); z != "post" {
60 t.Errorf(`req.FormValue("z") = %q, want "post"`, z)
62 if bq, found := req.PostForm["q"]; found {
63 t.Errorf(`req.PostForm["q"] = %q, want no entry in map`, bq)
65 if bz := req.PostFormValue("z"); bz != "post" {
66 t.Errorf(`req.PostFormValue("z") = %q, want "post"`, bz)
68 if qs := req.Form["q"]; !reflect.DeepEqual(qs, []string{"foo", "bar"}) {
69 t.Errorf(`req.Form["q"] = %q, want ["foo", "bar"]`, qs)
71 if both := req.Form["both"]; !reflect.DeepEqual(both, []string{"y", "x"}) {
72 t.Errorf(`req.Form["both"] = %q, want ["y", "x"]`, both)
74 if prio := req.FormValue("prio"); prio != "2" {
75 t.Errorf(`req.FormValue("prio") = %q, want "2" (from body)`, prio)
77 if orphan := req.Form["orphan"]; !reflect.DeepEqual(orphan, []string{"", "nope"}) {
78 t.Errorf(`req.FormValue("orphan") = %q, want "" (from body)`, orphan)
80 if empty := req.Form["empty"]; !reflect.DeepEqual(empty, []string{"", "not"}) {
81 t.Errorf(`req.FormValue("empty") = %q, want "" (from body)`, empty)
83 if nokey := req.Form[""]; !reflect.DeepEqual(nokey, []string{"nokey"}) {
84 t.Errorf(`req.FormValue("nokey") = %q, want "nokey" (from body)`, nokey)
88 // Tests that we only parse the form automatically for certain methods.
89 func TestParseFormQueryMethods(t *testing.T) {
90 for _, method := range []string{"POST", "PATCH", "PUT", "FOO"} {
91 req, _ := NewRequest(method, "http://www.google.com/search",
92 strings.NewReader("foo=bar"))
93 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
98 if got := req.FormValue("foo"); got != want {
99 t.Errorf(`for method %s, FormValue("foo") = %q; want %q`, method, got, want)
104 func TestParseFormUnknownContentType(t *testing.T) {
105 for _, test := range []struct {
110 {"text", "", Header{"Content-Type": {"text/plain"}}},
111 // Empty content type is legal - may be treated as
112 // application/octet-stream (RFC 7231, section 3.1.1.5)
113 {"empty", "", Header{}},
114 {"boundary", "mime: invalid media parameter", Header{"Content-Type": {"text/plain; boundary="}}},
115 {"unknown", "", Header{"Content-Type": {"application/unknown"}}},
121 Header: test.contentType,
122 Body: io.NopCloser(strings.NewReader("body")),
124 err := req.ParseForm()
126 case err == nil && test.wantErr != "":
127 t.Errorf("unexpected success; want error %q", test.wantErr)
128 case err != nil && test.wantErr == "":
129 t.Errorf("want success, got error: %v", err)
130 case test.wantErr != "" && test.wantErr != fmt.Sprint(err):
131 t.Errorf("got error %q; want %q", err, test.wantErr)
138 func TestParseFormInitializeOnError(t *testing.T) {
139 nilBody, _ := NewRequest("POST", "http://www.google.com/search?q=foo", nil)
142 {Method: "GET", URL: nil},
144 for i, req := range tests {
145 err := req.ParseForm()
147 t.Errorf("%d. Form not initialized, error %v", i, err)
149 if req.PostForm == nil {
150 t.Errorf("%d. PostForm not initialized, error %v", i, err)
155 func TestMultipartReader(t *testing.T) {
160 {false, `multipart/form-data; boundary="foo123"`},
161 {false, `multipart/mixed; boundary="foo123"`},
162 {true, `text/plain`},
165 for i, test := range tests {
168 Header: Header{"Content-Type": {test.contentType}},
169 Body: io.NopCloser(new(bytes.Buffer)),
171 multipart, err := req.MultipartReader()
172 if test.shouldError {
173 if err == nil || multipart != nil {
174 t.Errorf("test %d: unexpectedly got nil-error (%v) or non-nil-multipart (%v)", i, err, multipart)
178 if err != nil || multipart == nil {
179 t.Errorf("test %d: unexpectedly got error (%v) or nil-multipart (%v)", i, err, multipart)
184 // Issue 9305: ParseMultipartForm should populate PostForm too
185 func TestParseMultipartFormPopulatesPostForm(t *testing.T) {
188 Content-Disposition: form-data; name="field1"
192 Content-Disposition: form-data; name="field2"
196 Content-Disposition: form-data; name="file"; filename="file"
197 Content-Type: application/octet-stream
198 Content-Transfer-Encoding: binary
205 Header: Header{"Content-Type": {`multipart/form-data; boundary=xxx`}},
206 Body: io.NopCloser(strings.NewReader(postData)),
209 initialFormItems := map[string]string{
213 "field2": "initial-value2",
216 req.Form = make(url.Values)
217 for k, v := range initialFormItems {
221 err := req.ParseMultipartForm(10000)
223 t.Fatalf("unexpected multipart error %v", err)
226 wantForm := url.Values{
227 "language": []string{"Go"},
228 "name": []string{"gopher"},
229 "skill": []string{"go-ing"},
230 "field1": []string{"value1"},
231 "field2": []string{"initial-value2", "value2"},
233 if !reflect.DeepEqual(req.Form, wantForm) {
234 t.Fatalf("req.Form = %v, want %v", req.Form, wantForm)
237 wantPostForm := url.Values{
238 "field1": []string{"value1"},
239 "field2": []string{"value2"},
241 if !reflect.DeepEqual(req.PostForm, wantPostForm) {
242 t.Fatalf("req.PostForm = %v, want %v", req.PostForm, wantPostForm)
246 func TestParseMultipartForm(t *testing.T) {
249 Header: Header{"Content-Type": {`multipart/form-data; boundary="foo123"`}},
250 Body: io.NopCloser(new(bytes.Buffer)),
252 err := req.ParseMultipartForm(25)
254 t.Error("expected multipart EOF, got nil")
257 req.Header = Header{"Content-Type": {"text/plain"}}
258 err = req.ParseMultipartForm(25)
259 if err != ErrNotMultipart {
260 t.Error("expected ErrNotMultipart for text/plain")
264 // Issue 45789: multipart form should not include directory path in filename
265 func TestParseMultipartFormFilename(t *testing.T) {
268 Content-Disposition: form-data; name="file"; filename="../usr/foobar.txt/"
269 Content-Type: text/plain
275 Header: Header{"Content-Type": {`multipart/form-data; boundary=xxx`}},
276 Body: io.NopCloser(strings.NewReader(postData)),
278 _, hdr, err := req.FormFile("file")
282 if hdr.Filename != "foobar.txt" {
283 t.Errorf("expected only the last element of the path, got %q", hdr.Filename)
287 // Issue #40430: Test that if maxMemory for ParseMultipartForm when combined with
288 // the payload size and the internal leeway buffer size of 10MiB overflows, that we
289 // correctly return an error.
290 func TestMaxInt64ForMultipartFormMaxMemoryOverflow(t *testing.T) {
291 run(t, testMaxInt64ForMultipartFormMaxMemoryOverflow)
293 func testMaxInt64ForMultipartFormMaxMemoryOverflow(t *testing.T, mode testMode) {
294 payloadSize := 1 << 10
295 cst := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
296 // The combination of:
297 // MaxInt64 + payloadSize + (internal spare of 10MiB)
298 // triggers the overflow. See issue https://golang.org/issue/40430/
299 if err := req.ParseMultipartForm(math.MaxInt64); err != nil {
300 Error(rw, err.Error(), StatusBadRequest)
304 fBuf := new(bytes.Buffer)
305 mw := multipart.NewWriter(fBuf)
306 mf, err := mw.CreateFormFile("file", "myfile.txt")
310 if _, err := mf.Write(bytes.Repeat([]byte("abc"), payloadSize)); err != nil {
313 if err := mw.Close(); err != nil {
316 req, err := NewRequest("POST", cst.URL, fBuf)
320 req.Header.Set("Content-Type", mw.FormDataContentType())
321 res, err := cst.Client().Do(req)
326 if g, w := res.StatusCode, StatusOK; g != w {
327 t.Fatalf("Status code mismatch: got %d, want %d", g, w)
331 func TestRequestRedirect(t *testing.T) { run(t, testRequestRedirect) }
332 func testRequestRedirect(t *testing.T, mode testMode) {
333 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
336 w.Header().Set("Location", "/foo/")
337 w.WriteHeader(StatusSeeOther)
339 fmt.Fprintf(w, "foo")
341 w.WriteHeader(StatusBadRequest)
345 var end = regexp.MustCompile("/foo/$")
346 r, err := cst.c.Get(cst.ts.URL)
351 url := r.Request.URL.String()
352 if r.StatusCode != 200 || !end.MatchString(url) {
353 t.Fatalf("Get got status %d at %q, want 200 matching /foo/$", r.StatusCode, url)
357 func TestSetBasicAuth(t *testing.T) {
358 r, _ := NewRequest("GET", "http://example.com/", nil)
359 r.SetBasicAuth("Aladdin", "open sesame")
360 if g, e := r.Header.Get("Authorization"), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; g != e {
361 t.Errorf("got header %q, want %q", g, e)
365 func TestMultipartRequest(t *testing.T) {
366 // Test that we can read the values and files of a
367 // multipart request with FormValue and FormFile,
368 // and that ParseMultipartForm can be called multiple times.
369 req := newTestMultipartRequest(t)
370 if err := req.ParseMultipartForm(25); err != nil {
371 t.Fatal("ParseMultipartForm first call:", err)
373 defer req.MultipartForm.RemoveAll()
374 validateTestMultipartContents(t, req, false)
375 if err := req.ParseMultipartForm(25); err != nil {
376 t.Fatal("ParseMultipartForm second call:", err)
378 validateTestMultipartContents(t, req, false)
381 // Issue #25192: Test that ParseMultipartForm fails but still parses the
382 // multi-part form when a URL containing a semicolon is provided.
383 func TestParseMultipartFormSemicolonSeparator(t *testing.T) {
384 req := newTestMultipartRequest(t)
385 req.URL = &url.URL{RawQuery: "q=foo;q=bar"}
386 if err := req.ParseMultipartForm(25); err == nil {
387 t.Fatal("ParseMultipartForm expected error due to invalid semicolon, got nil")
389 defer req.MultipartForm.RemoveAll()
390 validateTestMultipartContents(t, req, false)
393 func TestMultipartRequestAuto(t *testing.T) {
394 // Test that FormValue and FormFile automatically invoke
395 // ParseMultipartForm and return the right values.
396 req := newTestMultipartRequest(t)
398 if req.MultipartForm != nil {
399 req.MultipartForm.RemoveAll()
402 validateTestMultipartContents(t, req, true)
405 func TestMissingFileMultipartRequest(t *testing.T) {
406 // Test that FormFile returns an error if
407 // the named file is missing.
408 req := newTestMultipartRequest(t)
409 testMissingFile(t, req)
412 // Test that FormValue invokes ParseMultipartForm.
413 func TestFormValueCallsParseMultipartForm(t *testing.T) {
414 req, _ := NewRequest("POST", "http://www.google.com/", strings.NewReader("z=post"))
415 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
417 t.Fatal("Unexpected request Form, want nil")
421 t.Fatal("ParseMultipartForm not called by FormValue")
425 // Test that FormFile invokes ParseMultipartForm.
426 func TestFormFileCallsParseMultipartForm(t *testing.T) {
427 req := newTestMultipartRequest(t)
429 t.Fatal("Unexpected request Form, want nil")
433 t.Fatal("ParseMultipartForm not called by FormFile")
437 // Test that ParseMultipartForm errors if called
438 // after MultipartReader on the same request.
439 func TestParseMultipartFormOrder(t *testing.T) {
440 req := newTestMultipartRequest(t)
441 if _, err := req.MultipartReader(); err != nil {
442 t.Fatalf("MultipartReader: %v", err)
444 if err := req.ParseMultipartForm(1024); err == nil {
445 t.Fatal("expected an error from ParseMultipartForm after call to MultipartReader")
449 // Test that MultipartReader errors if called
450 // after ParseMultipartForm on the same request.
451 func TestMultipartReaderOrder(t *testing.T) {
452 req := newTestMultipartRequest(t)
453 if err := req.ParseMultipartForm(25); err != nil {
454 t.Fatalf("ParseMultipartForm: %v", err)
456 defer req.MultipartForm.RemoveAll()
457 if _, err := req.MultipartReader(); err == nil {
458 t.Fatal("expected an error from MultipartReader after call to ParseMultipartForm")
462 // Test that FormFile errors if called after
463 // MultipartReader on the same request.
464 func TestFormFileOrder(t *testing.T) {
465 req := newTestMultipartRequest(t)
466 if _, err := req.MultipartReader(); err != nil {
467 t.Fatalf("MultipartReader: %v", err)
469 if _, _, err := req.FormFile(""); err == nil {
470 t.Fatal("expected an error from FormFile after call to MultipartReader")
474 var readRequestErrorTests = []struct {
480 0: {"GET / HTTP/1.1\r\nheader:foo\r\n\r\n", "", Header{"Header": {"foo"}}},
481 1: {"GET / HTTP/1.1\r\nheader:foo\r\n", io.ErrUnexpectedEOF.Error(), nil},
482 2: {"", io.EOF.Error(), nil},
484 in: "HEAD / HTTP/1.1\r\n\r\n",
488 // Multiple Content-Length values should either be
489 // deduplicated if same or reject otherwise
492 in: "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 0\r\n\r\nGopher hey\r\n",
493 err: "cannot contain multiple Content-Length headers",
496 in: "POST / HTTP/1.1\r\nContent-Length: 10\r\nContent-Length: 6\r\n\r\nGopher\r\n",
497 err: "cannot contain multiple Content-Length headers",
500 in: "PUT / HTTP/1.1\r\nContent-Length: 6 \r\nContent-Length: 6\r\nContent-Length:6\r\n\r\nGopher\r\n",
502 header: Header{"Content-Length": {"6"}},
505 in: "PUT / HTTP/1.1\r\nContent-Length: 1\r\nContent-Length: 6 \r\n\r\n",
506 err: "cannot contain multiple Content-Length headers",
509 in: "POST / HTTP/1.1\r\nContent-Length:\r\nContent-Length: 3\r\n\r\n",
510 err: "cannot contain multiple Content-Length headers",
513 in: "HEAD / HTTP/1.1\r\nContent-Length:0\r\nContent-Length: 0\r\n\r\n",
514 header: Header{"Content-Length": {"0"}},
517 in: "HEAD / HTTP/1.1\r\nHost: foo\r\nHost: bar\r\n\r\n\r\n\r\n",
518 err: "too many Host headers",
522 func TestReadRequestErrors(t *testing.T) {
523 for i, tt := range readRequestErrorTests {
524 req, err := ReadRequest(bufio.NewReader(strings.NewReader(tt.in)))
527 t.Errorf("#%d: got nil err; want %q", i, tt.err)
530 if !reflect.DeepEqual(tt.header, req.Header) {
531 t.Errorf("#%d: gotHeader: %q wantHeader: %q", i, req.Header, tt.header)
536 if tt.err == "" || !strings.Contains(err.Error(), tt.err) {
537 t.Errorf("%d: got error = %v; want %v", i, err, tt.err)
542 var newRequestHostTests = []struct {
545 {"http://www.example.com/", "www.example.com"},
546 {"http://www.example.com:8080/", "www.example.com:8080"},
548 {"http://192.168.0.1/", "192.168.0.1"},
549 {"http://192.168.0.1:8080/", "192.168.0.1:8080"},
550 {"http://192.168.0.1:/", "192.168.0.1"},
552 {"http://[fe80::1]/", "[fe80::1]"},
553 {"http://[fe80::1]:8080/", "[fe80::1]:8080"},
554 {"http://[fe80::1%25en0]/", "[fe80::1%en0]"},
555 {"http://[fe80::1%25en0]:8080/", "[fe80::1%en0]:8080"},
556 {"http://[fe80::1%25en0]:/", "[fe80::1%en0]"},
559 func TestNewRequestHost(t *testing.T) {
560 for i, tt := range newRequestHostTests {
561 req, err := NewRequest("GET", tt.in, nil)
563 t.Errorf("#%v: %v", i, err)
566 if req.Host != tt.out {
567 t.Errorf("got %q; want %q", req.Host, tt.out)
572 func TestRequestInvalidMethod(t *testing.T) {
573 _, err := NewRequest("bad method", "http://foo.com/", nil)
575 t.Error("expected error from NewRequest with invalid method")
577 req, err := NewRequest("GET", "http://foo.example/", nil)
581 req.Method = "bad method"
582 _, err = DefaultClient.Do(req)
583 if err == nil || !strings.Contains(err.Error(), "invalid method") {
584 t.Errorf("Transport error = %v; want invalid method", err)
587 req, err = NewRequest("", "http://foo.com/", nil)
589 t.Errorf("NewRequest(empty method) = %v; want nil", err)
590 } else if req.Method != "GET" {
591 t.Errorf("NewRequest(empty method) has method %q; want GET", req.Method)
595 func TestNewRequestContentLength(t *testing.T) {
596 readByte := func(r io.Reader) io.Reader {
605 {bytes.NewReader([]byte("123")), 3},
606 {bytes.NewBuffer([]byte("1234")), 4},
607 {strings.NewReader("12345"), 5},
608 {strings.NewReader(""), 0},
611 // Not detected. During Go 1.8 we tried to make these set to -1, but
612 // due to Issue 18117, we keep these returning 0, even though they're
614 {struct{ io.Reader }{strings.NewReader("xyz")}, 0},
615 {io.NewSectionReader(strings.NewReader("x"), 0, 6), 0},
616 {readByte(io.NewSectionReader(strings.NewReader("xy"), 0, 6)), 0},
618 for i, tt := range tests {
619 req, err := NewRequest("POST", "http://localhost/", tt.r)
623 if req.ContentLength != tt.want {
624 t.Errorf("test[%d]: ContentLength(%T) = %d; want %d", i, tt.r, req.ContentLength, tt.want)
629 var parseHTTPVersionTests = []struct {
634 {"HTTP/0.0", 0, 0, true},
635 {"HTTP/0.9", 0, 9, true},
636 {"HTTP/1.0", 1, 0, true},
637 {"HTTP/1.1", 1, 1, true},
639 {"HTTP", 0, 0, false},
640 {"HTTP/one.one", 0, 0, false},
641 {"HTTP/1.1/", 0, 0, false},
642 {"HTTP/-1,0", 0, 0, false},
643 {"HTTP/0,-1", 0, 0, false},
644 {"HTTP/", 0, 0, false},
645 {"HTTP/1,1", 0, 0, false},
646 {"HTTP/+1.1", 0, 0, false},
647 {"HTTP/1.+1", 0, 0, false},
648 {"HTTP/0000000001.1", 0, 0, false},
649 {"HTTP/1.0000000001", 0, 0, false},
650 {"HTTP/3.14", 0, 0, false},
651 {"HTTP/12.3", 0, 0, false},
654 func TestParseHTTPVersion(t *testing.T) {
655 for _, tt := range parseHTTPVersionTests {
656 major, minor, ok := ParseHTTPVersion(tt.vers)
657 if ok != tt.ok || major != tt.major || minor != tt.minor {
658 type version struct {
662 t.Errorf("failed to parse %q, expected: %#v, got %#v", tt.vers, version{tt.major, tt.minor, tt.ok}, version{major, minor, ok})
667 type getBasicAuthTest struct {
668 username, password string
672 type basicAuthCredentialsTest struct {
673 username, password string
676 var getBasicAuthTests = []struct {
677 username, password string
680 {"Aladdin", "open sesame", true},
681 {"Aladdin", "open:sesame", true},
685 func TestGetBasicAuth(t *testing.T) {
686 for _, tt := range getBasicAuthTests {
687 r, _ := NewRequest("GET", "http://example.com/", nil)
688 r.SetBasicAuth(tt.username, tt.password)
689 username, password, ok := r.BasicAuth()
690 if ok != tt.ok || username != tt.username || password != tt.password {
691 t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok},
692 getBasicAuthTest{tt.username, tt.password, tt.ok})
695 // Unauthenticated request.
696 r, _ := NewRequest("GET", "http://example.com/", nil)
697 username, password, ok := r.BasicAuth()
699 t.Errorf("expected false from BasicAuth when the request is unauthenticated")
701 want := basicAuthCredentialsTest{"", ""}
702 if username != want.username || password != want.password {
703 t.Errorf("expected credentials: %#v when the request is unauthenticated, got %#v",
704 want, basicAuthCredentialsTest{username, password})
708 var parseBasicAuthTests = []struct {
709 header, username, password string
712 {"Basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "Aladdin", "open sesame", true},
714 // Case doesn't matter:
715 {"BASIC " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "Aladdin", "open sesame", true},
716 {"basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "Aladdin", "open sesame", true},
718 {"Basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open:sesame")), "Aladdin", "open:sesame", true},
719 {"Basic " + base64.StdEncoding.EncodeToString([]byte(":")), "", "", true},
720 {"Basic" + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "", "", false},
721 {base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "", "", false},
722 {"Basic ", "", "", false},
723 {"Basic Aladdin:open sesame", "", "", false},
724 {`Digest username="Aladdin"`, "", "", false},
727 func TestParseBasicAuth(t *testing.T) {
728 for _, tt := range parseBasicAuthTests {
729 r, _ := NewRequest("GET", "http://example.com/", nil)
730 r.Header.Set("Authorization", tt.header)
731 username, password, ok := r.BasicAuth()
732 if ok != tt.ok || username != tt.username || password != tt.password {
733 t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok},
734 getBasicAuthTest{tt.username, tt.password, tt.ok})
739 type logWrites struct {
744 func (l logWrites) WriteByte(c byte) error {
745 l.t.Fatalf("unexpected WriteByte call")
749 func (l logWrites) Write(p []byte) (n int, err error) {
750 *l.dst = append(*l.dst, string(p))
754 func TestRequestWriteBufferedWriter(t *testing.T) {
756 req, _ := NewRequest("GET", "http://foo.com/", nil)
757 req.Write(logWrites{t, &got})
759 "GET / HTTP/1.1\r\n",
761 "User-Agent: " + DefaultUserAgent + "\r\n",
764 if !reflect.DeepEqual(got, want) {
765 t.Errorf("Writes = %q\n Want = %q", got, want)
769 func TestRequestBadHost(t *testing.T) {
771 req, err := NewRequest("GET", "http://foo/after", nil)
775 req.Host = "foo.com with spaces"
776 req.URL.Host = "foo.com with spaces"
777 req.Write(logWrites{t, &got})
779 "GET /after HTTP/1.1\r\n",
781 "User-Agent: " + DefaultUserAgent + "\r\n",
784 if !reflect.DeepEqual(got, want) {
785 t.Errorf("Writes = %q\n Want = %q", got, want)
789 func TestStarRequest(t *testing.T) {
790 req, err := ReadRequest(bufio.NewReader(strings.NewReader("M-SEARCH * HTTP/1.1\r\n\r\n")))
794 if req.ContentLength != 0 {
795 t.Errorf("ContentLength = %d; want 0", req.ContentLength)
798 t.Errorf("Body = nil; want non-nil")
801 // Request.Write has Client semantics for Body/ContentLength,
802 // where ContentLength 0 means unknown if Body is non-nil, and
803 // thus chunking will happen unless we change semantics and
804 // signal that we want to serialize it as exactly zero. The
805 // only way to do that for outbound requests is with a nil
810 var out strings.Builder
811 if err := clientReq.Write(&out); err != nil {
815 if strings.Contains(out.String(), "chunked") {
816 t.Error("wrote chunked request; want no body")
818 back, err := ReadRequest(bufio.NewReader(strings.NewReader(out.String())))
822 // Ignore the Headers (the User-Agent breaks the deep equal,
823 // but we don't care about it)
826 if !reflect.DeepEqual(req, back) {
827 t.Errorf("Original request doesn't match Request read back.")
828 t.Logf("Original: %#v", req)
829 t.Logf("Original.URL: %#v", req.URL)
830 t.Logf("Wrote: %s", out.String())
831 t.Logf("Read back (doesn't match Original): %#v", back)
835 type responseWriterJustWriter struct {
839 func (responseWriterJustWriter) Header() Header { panic("should not be called") }
840 func (responseWriterJustWriter) WriteHeader(int) { panic("should not be called") }
842 // delayedEOFReader never returns (n > 0, io.EOF), instead putting
843 // off the io.EOF until a subsequent Read call.
844 type delayedEOFReader struct {
848 func (dr delayedEOFReader) Read(p []byte) (n int, err error) {
849 n, err = dr.r.Read(p)
850 if n > 0 && err == io.EOF {
856 func TestIssue10884_MaxBytesEOF(t *testing.T) {
858 _, err := io.Copy(dst, MaxBytesReader(
859 responseWriterJustWriter{dst},
860 io.NopCloser(delayedEOFReader{strings.NewReader("12345")}),
867 // Issue 14981: MaxBytesReader's return error wasn't sticky. It
868 // doesn't technically need to be, but people expected it to be.
869 func TestMaxBytesReaderStickyError(t *testing.T) {
870 isSticky := func(r io.Reader) error {
872 buf := make([]byte, 1000)
875 n, err := r.Read(buf)
876 fmt.Fprintf(&log, "Read(%d) = %d, %v\n", len(buf), n, err)
884 if !reflect.DeepEqual(err, firstErr) {
885 return fmt.Errorf("non-sticky error. got log:\n%s", log.Bytes())
887 t.Logf("Got log: %s", log.Bytes())
891 tests := [...]struct {
899 for i, tt := range tests {
900 rc := MaxBytesReader(nil, io.NopCloser(bytes.NewReader(make([]byte, tt.readable))), tt.limit)
901 if err := isSticky(rc); err != nil {
902 t.Errorf("%d. error: %v", i, err)
907 // Issue 45101: maxBytesReader's Read panicked when n < -1. This test
908 // also ensures that Read treats negative limits as equivalent to 0.
909 func TestMaxBytesReaderDifferentLimits(t *testing.T) {
910 const testStr = "1234"
911 tests := [...]struct {
921 wantErr: false, // Ensure we won't return an error when the limit is negative, but we don't need to read.
966 limit: int64(len(testStr)),
977 10: { /* Issue 54408 */
978 limit: int64(1<<63 - 1),
984 for i, tt := range tests {
985 rc := MaxBytesReader(nil, io.NopCloser(strings.NewReader(testStr)), tt.limit)
987 n, err := rc.Read(make([]byte, tt.lenP))
990 t.Errorf("%d. n: %d, want n: %d", i, n, tt.wantN)
993 if (err != nil) != tt.wantErr {
994 t.Errorf("%d. error: %v", i, err)
999 func TestWithContextNilURL(t *testing.T) {
1000 req, err := NewRequest("POST", "https://golang.org/", nil)
1007 reqCopy := req.WithContext(context.Background())
1008 if reqCopy.URL != nil {
1009 t.Error("expected nil URL in cloned request")
1013 // Ensure that Request.Clone creates a deep copy of TransferEncoding.
1015 func TestRequestCloneTransferEncoding(t *testing.T) {
1016 body := strings.NewReader("body")
1017 req, _ := NewRequest("POST", "https://example.org/", body)
1018 req.TransferEncoding = []string{
1022 clonedReq := req.Clone(context.Background())
1023 // modify original after deep copy
1024 req.TransferEncoding[0] = "encoding2"
1026 if req.TransferEncoding[0] != "encoding2" {
1027 t.Error("expected req.TransferEncoding to be changed")
1029 if clonedReq.TransferEncoding[0] != "encoding1" {
1030 t.Error("expected clonedReq.TransferEncoding to be unchanged")
1034 // Issue 34878: verify we don't panic when including basic auth (Go 1.13 regression)
1035 func TestNoPanicOnRoundTripWithBasicAuth(t *testing.T) { run(t, testNoPanicWithBasicAuth) }
1036 func testNoPanicWithBasicAuth(t *testing.T, mode testMode) {
1037 cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {}))
1039 u, err := url.Parse(cst.ts.URL)
1043 u.User = url.UserPassword("foo", "bar")
1048 if _, err := cst.c.Do(req); err != nil {
1049 t.Fatalf("Unexpected error: %v", err)
1053 // verify that NewRequest sets Request.GetBody and that it works
1054 func TestNewRequestGetBody(t *testing.T) {
1058 {r: strings.NewReader("hello")},
1059 {r: bytes.NewReader([]byte("hello"))},
1060 {r: bytes.NewBuffer([]byte("hello"))},
1062 for i, tt := range tests {
1063 req, err := NewRequest("POST", "http://foo.tld/", tt.r)
1065 t.Errorf("test[%d]: %v", i, err)
1068 if req.Body == nil {
1069 t.Errorf("test[%d]: Body = nil", i)
1072 if req.GetBody == nil {
1073 t.Errorf("test[%d]: GetBody = nil", i)
1076 slurp1, err := io.ReadAll(req.Body)
1078 t.Errorf("test[%d]: ReadAll(Body) = %v", i, err)
1080 newBody, err := req.GetBody()
1082 t.Errorf("test[%d]: GetBody = %v", i, err)
1084 slurp2, err := io.ReadAll(newBody)
1086 t.Errorf("test[%d]: ReadAll(GetBody()) = %v", i, err)
1088 if string(slurp1) != string(slurp2) {
1089 t.Errorf("test[%d]: Body %q != GetBody %q", i, slurp1, slurp2)
1094 func testMissingFile(t *testing.T, req *Request) {
1095 f, fh, err := req.FormFile("missing")
1097 t.Errorf("FormFile file = %v, want nil", f)
1100 t.Errorf("FormFile file header = %v, want nil", fh)
1102 if err != ErrMissingFile {
1103 t.Errorf("FormFile err = %q, want ErrMissingFile", err)
1107 func newTestMultipartRequest(t *testing.T) *Request {
1108 b := strings.NewReader(strings.ReplaceAll(message, "\n", "\r\n"))
1109 req, err := NewRequest("POST", "/", b)
1111 t.Fatal("NewRequest:", err)
1113 ctype := fmt.Sprintf(`multipart/form-data; boundary="%s"`, boundary)
1114 req.Header.Set("Content-type", ctype)
1118 func validateTestMultipartContents(t *testing.T, req *Request, allMem bool) {
1119 if g, e := req.FormValue("texta"), textaValue; g != e {
1120 t.Errorf("texta value = %q, want %q", g, e)
1122 if g, e := req.FormValue("textb"), textbValue; g != e {
1123 t.Errorf("textb value = %q, want %q", g, e)
1125 if g := req.FormValue("missing"); g != "" {
1126 t.Errorf("missing value = %q, want empty string", g)
1129 assertMem := func(n string, fd multipart.File) {
1130 if _, ok := fd.(*os.File); ok {
1131 t.Error(n, " is *os.File, should not be")
1134 fda := testMultipartFile(t, req, "filea", "filea.txt", fileaContents)
1136 assertMem("filea", fda)
1137 fdb := testMultipartFile(t, req, "fileb", "fileb.txt", filebContents)
1140 assertMem("fileb", fdb)
1142 if _, ok := fdb.(*os.File); !ok {
1143 t.Errorf("fileb has unexpected underlying type %T", fdb)
1147 testMissingFile(t, req)
1150 func testMultipartFile(t *testing.T, req *Request, key, expectFilename, expectContent string) multipart.File {
1151 f, fh, err := req.FormFile(key)
1153 t.Fatalf("FormFile(%q): %q", key, err)
1155 if fh.Filename != expectFilename {
1156 t.Errorf("filename = %q, want %q", fh.Filename, expectFilename)
1158 var b strings.Builder
1159 _, err = io.Copy(&b, f)
1161 t.Fatal("copying contents:", err)
1163 if g := b.String(); g != expectContent {
1164 t.Errorf("contents = %q, want %q", g, expectContent)
1169 // Issue 53181: verify Request.Cookie return the correct Cookie.
1170 // Return ErrNoCookie instead of the first cookie when name is "".
1171 func TestRequestCookie(t *testing.T) {
1172 for _, tt := range []struct {
1184 expectedErr: ErrNoCookie,
1187 req, err := NewRequest("GET", "http://example.com/", nil)
1191 req.AddCookie(&Cookie{Name: tt.name, Value: tt.value})
1192 c, err := req.Cookie(tt.name)
1193 if err != tt.expectedErr {
1194 t.Errorf("got %v, want %v", err, tt.expectedErr)
1197 // skip if error occurred.
1201 if c.Value != tt.value {
1202 t.Errorf("got %v, want %v", c.Value, tt.value)
1204 if c.Name != tt.name {
1205 t.Errorf("got %s, want %v", tt.name, c.Name)
1211 fileaContents = "This is a test file."
1212 filebContents = "Another test file."
1215 boundary = `MyBoundary`
1220 Content-Disposition: form-data; name="filea"; filename="filea.txt"
1221 Content-Type: text/plain
1223 ` + fileaContents + `
1225 Content-Disposition: form-data; name="fileb"; filename="fileb.txt"
1226 Content-Type: text/plain
1228 ` + filebContents + `
1230 Content-Disposition: form-data; name="texta"
1234 Content-Disposition: form-data; name="textb"
1240 func benchmarkReadRequest(b *testing.B, request string) {
1241 request = request + "\n" // final \n
1242 request = strings.ReplaceAll(request, "\n", "\r\n") // expand \n to \r\n
1243 b.SetBytes(int64(len(request)))
1244 r := bufio.NewReader(&infiniteReader{buf: []byte(request)})
1247 for i := 0; i < b.N; i++ {
1248 _, err := ReadRequest(r)
1250 b.Fatalf("failed to read request: %v", err)
1255 // infiniteReader satisfies Read requests as if the contents of buf
1256 // loop indefinitely.
1257 type infiniteReader struct {
1262 func (r *infiniteReader) Read(b []byte) (int, error) {
1263 n := copy(b, r.buf[r.offset:])
1264 r.offset = (r.offset + n) % len(r.buf)
1268 func BenchmarkReadRequestChrome(b *testing.B) {
1269 // https://github.com/felixge/node-http-perf/blob/master/fixtures/get.http
1270 benchmarkReadRequest(b, `GET / HTTP/1.1
1271 Host: localhost:8080
1272 Connection: keep-alive
1273 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
1274 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
1275 Accept-Encoding: gzip,deflate,sdch
1276 Accept-Language: en-US,en;q=0.8
1277 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
1278 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
1282 func BenchmarkReadRequestCurl(b *testing.B) {
1283 // curl http://localhost:8080/
1284 benchmarkReadRequest(b, `GET / HTTP/1.1
1285 User-Agent: curl/7.27.0
1286 Host: localhost:8080
1291 func BenchmarkReadRequestApachebench(b *testing.B) {
1292 // ab -n 1 -c 1 http://localhost:8080/
1293 benchmarkReadRequest(b, `GET / HTTP/1.0
1294 Host: localhost:8080
1295 User-Agent: ApacheBench/2.3
1300 func BenchmarkReadRequestSiege(b *testing.B) {
1301 // siege -r 1 -c 1 http://localhost:8080/
1302 benchmarkReadRequest(b, `GET / HTTP/1.1
1303 Host: localhost:8080
1305 Accept-Encoding: gzip
1306 User-Agent: JoeDog/1.00 [en] (X11; I; Siege 2.70)
1307 Connection: keep-alive
1311 func BenchmarkReadRequestWrk(b *testing.B) {
1312 // wrk -t 1 -r 1 -c 1 http://localhost:8080/
1313 benchmarkReadRequest(b, `GET / HTTP/1.1
1314 Host: localhost:8080
1318 func BenchmarkFileAndServer_1KB(b *testing.B) {
1319 benchmarkFileAndServer(b, 1<<10)
1322 func BenchmarkFileAndServer_16MB(b *testing.B) {
1323 benchmarkFileAndServer(b, 1<<24)
1326 func BenchmarkFileAndServer_64MB(b *testing.B) {
1327 benchmarkFileAndServer(b, 1<<26)
1330 func benchmarkFileAndServer(b *testing.B, n int64) {
1331 f, err := os.CreateTemp(os.TempDir(), "go-bench-http-file-and-server")
1333 b.Fatalf("Failed to create temp file: %v", err)
1338 os.RemoveAll(f.Name())
1341 if _, err := io.CopyN(f, rand.Reader, n); err != nil {
1342 b.Fatalf("Failed to copy %d bytes: %v", n, err)
1345 run(b, func(b *testing.B, mode testMode) {
1346 runFileAndServerBenchmarks(b, mode, f, n)
1347 }, []testMode{http1Mode, https1Mode, http2Mode})
1350 func runFileAndServerBenchmarks(b *testing.B, mode testMode, f *os.File, n int64) {
1351 handler := HandlerFunc(func(rw ResponseWriter, req *Request) {
1352 defer req.Body.Close()
1353 nc, err := io.Copy(io.Discard, req.Body)
1359 panic(fmt.Errorf("Copied %d Wanted %d bytes", nc, n))
1363 cst := newClientServerTest(b, mode, handler).ts
1366 for i := 0; i < b.N; i++ {
1367 // Perform some setup.
1369 if _, err := f.Seek(0, 0); err != nil {
1370 b.Fatalf("Failed to seek back to file: %v", err)
1374 req, err := NewRequest("PUT", cst.URL, io.NopCloser(f))
1379 req.ContentLength = n
1380 // Prevent mime sniffing by setting the Content-Type.
1381 req.Header.Set("Content-Type", "application/octet-stream")
1382 res, err := cst.Client().Do(req)
1384 b.Fatalf("Failed to make request to backend: %v", err)