github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/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 "encoding/base64" 11 "fmt" 12 "io" 13 "io/ioutil" 14 "mime/multipart" 15 . "net/http" 16 "net/url" 17 "os" 18 "reflect" 19 "regexp" 20 "strings" 21 "testing" 22 ) 23 24 func TestQuery(t *testing.T) { 25 req := &Request{Method: "GET"} 26 req.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar") 27 if q := req.FormValue("q"); q != "foo" { 28 t.Errorf(`req.FormValue("q") = %q, want "foo"`, q) 29 } 30 } 31 32 func TestPostQuery(t *testing.T) { 33 req, _ := NewRequest("POST", "http://www.google.com/search?q=foo&q=bar&both=x&prio=1&empty=not", 34 strings.NewReader("z=post&both=y&prio=2&empty=")) 35 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value") 36 37 if q := req.FormValue("q"); q != "foo" { 38 t.Errorf(`req.FormValue("q") = %q, want "foo"`, q) 39 } 40 if z := req.FormValue("z"); z != "post" { 41 t.Errorf(`req.FormValue("z") = %q, want "post"`, z) 42 } 43 if bq, found := req.PostForm["q"]; found { 44 t.Errorf(`req.PostForm["q"] = %q, want no entry in map`, bq) 45 } 46 if bz := req.PostFormValue("z"); bz != "post" { 47 t.Errorf(`req.PostFormValue("z") = %q, want "post"`, bz) 48 } 49 if qs := req.Form["q"]; !reflect.DeepEqual(qs, []string{"foo", "bar"}) { 50 t.Errorf(`req.Form["q"] = %q, want ["foo", "bar"]`, qs) 51 } 52 if both := req.Form["both"]; !reflect.DeepEqual(both, []string{"y", "x"}) { 53 t.Errorf(`req.Form["both"] = %q, want ["y", "x"]`, both) 54 } 55 if prio := req.FormValue("prio"); prio != "2" { 56 t.Errorf(`req.FormValue("prio") = %q, want "2" (from body)`, prio) 57 } 58 if empty := req.FormValue("empty"); empty != "" { 59 t.Errorf(`req.FormValue("empty") = %q, want "" (from body)`, empty) 60 } 61 } 62 63 func TestPatchQuery(t *testing.T) { 64 req, _ := NewRequest("PATCH", "http://www.google.com/search?q=foo&q=bar&both=x&prio=1&empty=not", 65 strings.NewReader("z=post&both=y&prio=2&empty=")) 66 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value") 67 68 if q := req.FormValue("q"); q != "foo" { 69 t.Errorf(`req.FormValue("q") = %q, want "foo"`, q) 70 } 71 if z := req.FormValue("z"); z != "post" { 72 t.Errorf(`req.FormValue("z") = %q, want "post"`, z) 73 } 74 if bq, found := req.PostForm["q"]; found { 75 t.Errorf(`req.PostForm["q"] = %q, want no entry in map`, bq) 76 } 77 if bz := req.PostFormValue("z"); bz != "post" { 78 t.Errorf(`req.PostFormValue("z") = %q, want "post"`, bz) 79 } 80 if qs := req.Form["q"]; !reflect.DeepEqual(qs, []string{"foo", "bar"}) { 81 t.Errorf(`req.Form["q"] = %q, want ["foo", "bar"]`, qs) 82 } 83 if both := req.Form["both"]; !reflect.DeepEqual(both, []string{"y", "x"}) { 84 t.Errorf(`req.Form["both"] = %q, want ["y", "x"]`, both) 85 } 86 if prio := req.FormValue("prio"); prio != "2" { 87 t.Errorf(`req.FormValue("prio") = %q, want "2" (from body)`, prio) 88 } 89 if empty := req.FormValue("empty"); empty != "" { 90 t.Errorf(`req.FormValue("empty") = %q, want "" (from body)`, empty) 91 } 92 } 93 94 type stringMap map[string][]string 95 type parseContentTypeTest struct { 96 shouldError bool 97 contentType stringMap 98 } 99 100 var parseContentTypeTests = []parseContentTypeTest{ 101 {false, stringMap{"Content-Type": {"text/plain"}}}, 102 // Empty content type is legal - shoult be treated as 103 // application/octet-stream (RFC 2616, section 7.2.1) 104 {false, stringMap{}}, 105 {true, stringMap{"Content-Type": {"text/plain; boundary="}}}, 106 {false, stringMap{"Content-Type": {"application/unknown"}}}, 107 } 108 109 func TestParseFormUnknownContentType(t *testing.T) { 110 for i, test := range parseContentTypeTests { 111 req := &Request{ 112 Method: "POST", 113 Header: Header(test.contentType), 114 Body: ioutil.NopCloser(strings.NewReader("body")), 115 } 116 err := req.ParseForm() 117 switch { 118 case err == nil && test.shouldError: 119 t.Errorf("test %d should have returned error", i) 120 case err != nil && !test.shouldError: 121 t.Errorf("test %d should not have returned error, got %v", i, err) 122 } 123 } 124 } 125 126 func TestParseFormInitializeOnError(t *testing.T) { 127 nilBody, _ := NewRequest("POST", "http://www.google.com/search?q=foo", nil) 128 tests := []*Request{ 129 nilBody, 130 {Method: "GET", URL: nil}, 131 } 132 for i, req := range tests { 133 err := req.ParseForm() 134 if req.Form == nil { 135 t.Errorf("%d. Form not initialized, error %v", i, err) 136 } 137 if req.PostForm == nil { 138 t.Errorf("%d. PostForm not initialized, error %v", i, err) 139 } 140 } 141 } 142 143 func TestMultipartReader(t *testing.T) { 144 req := &Request{ 145 Method: "POST", 146 Header: Header{"Content-Type": {`multipart/form-data; boundary="foo123"`}}, 147 Body: ioutil.NopCloser(new(bytes.Buffer)), 148 } 149 multipart, err := req.MultipartReader() 150 if multipart == nil { 151 t.Errorf("expected multipart; error: %v", err) 152 } 153 154 req.Header = Header{"Content-Type": {"text/plain"}} 155 multipart, err = req.MultipartReader() 156 if multipart != nil { 157 t.Error("unexpected multipart for text/plain") 158 } 159 } 160 161 func TestParseMultipartForm(t *testing.T) { 162 req := &Request{ 163 Method: "POST", 164 Header: Header{"Content-Type": {`multipart/form-data; boundary="foo123"`}}, 165 Body: ioutil.NopCloser(new(bytes.Buffer)), 166 } 167 err := req.ParseMultipartForm(25) 168 if err == nil { 169 t.Error("expected multipart EOF, got nil") 170 } 171 172 req.Header = Header{"Content-Type": {"text/plain"}} 173 err = req.ParseMultipartForm(25) 174 if err != ErrNotMultipart { 175 t.Error("expected ErrNotMultipart for text/plain") 176 } 177 } 178 179 func TestRedirect_h1(t *testing.T) { testRedirect(t, false) } 180 func TestRedirect_h2(t *testing.T) { testRedirect(t, true) } 181 182 func testRedirect(t *testing.T, h2 bool) { 183 defer afterTest(t) 184 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 185 switch r.URL.Path { 186 case "/": 187 w.Header().Set("Location", "/foo/") 188 w.WriteHeader(StatusSeeOther) 189 case "/foo/": 190 fmt.Fprintf(w, "foo") 191 default: 192 w.WriteHeader(StatusBadRequest) 193 } 194 })) 195 defer cst.close() 196 197 var end = regexp.MustCompile("/foo/$") 198 r, err := cst.c.Get(cst.ts.URL) 199 if err != nil { 200 t.Fatal(err) 201 } 202 r.Body.Close() 203 url := r.Request.URL.String() 204 if r.StatusCode != 200 || !end.MatchString(url) { 205 t.Fatalf("Get got status %d at %q, want 200 matching /foo/$", r.StatusCode, url) 206 } 207 } 208 209 func TestSetBasicAuth(t *testing.T) { 210 r, _ := NewRequest("GET", "http://example.com/", nil) 211 r.SetBasicAuth("Aladdin", "open sesame") 212 if g, e := r.Header.Get("Authorization"), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="; g != e { 213 t.Errorf("got header %q, want %q", g, e) 214 } 215 } 216 217 func TestMultipartRequest(t *testing.T) { 218 // Test that we can read the values and files of a 219 // multipart request with FormValue and FormFile, 220 // and that ParseMultipartForm can be called multiple times. 221 req := newTestMultipartRequest(t) 222 if err := req.ParseMultipartForm(25); err != nil { 223 t.Fatal("ParseMultipartForm first call:", err) 224 } 225 defer req.MultipartForm.RemoveAll() 226 validateTestMultipartContents(t, req, false) 227 if err := req.ParseMultipartForm(25); err != nil { 228 t.Fatal("ParseMultipartForm second call:", err) 229 } 230 validateTestMultipartContents(t, req, false) 231 } 232 233 func TestMultipartRequestAuto(t *testing.T) { 234 // Test that FormValue and FormFile automatically invoke 235 // ParseMultipartForm and return the right values. 236 req := newTestMultipartRequest(t) 237 defer func() { 238 if req.MultipartForm != nil { 239 req.MultipartForm.RemoveAll() 240 } 241 }() 242 validateTestMultipartContents(t, req, true) 243 } 244 245 func TestMissingFileMultipartRequest(t *testing.T) { 246 // Test that FormFile returns an error if 247 // the named file is missing. 248 req := newTestMultipartRequest(t) 249 testMissingFile(t, req) 250 } 251 252 // Test that FormValue invokes ParseMultipartForm. 253 func TestFormValueCallsParseMultipartForm(t *testing.T) { 254 req, _ := NewRequest("POST", "http://www.google.com/", strings.NewReader("z=post")) 255 req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value") 256 if req.Form != nil { 257 t.Fatal("Unexpected request Form, want nil") 258 } 259 req.FormValue("z") 260 if req.Form == nil { 261 t.Fatal("ParseMultipartForm not called by FormValue") 262 } 263 } 264 265 // Test that FormFile invokes ParseMultipartForm. 266 func TestFormFileCallsParseMultipartForm(t *testing.T) { 267 req := newTestMultipartRequest(t) 268 if req.Form != nil { 269 t.Fatal("Unexpected request Form, want nil") 270 } 271 req.FormFile("") 272 if req.Form == nil { 273 t.Fatal("ParseMultipartForm not called by FormFile") 274 } 275 } 276 277 // Test that ParseMultipartForm errors if called 278 // after MultipartReader on the same request. 279 func TestParseMultipartFormOrder(t *testing.T) { 280 req := newTestMultipartRequest(t) 281 if _, err := req.MultipartReader(); err != nil { 282 t.Fatalf("MultipartReader: %v", err) 283 } 284 if err := req.ParseMultipartForm(1024); err == nil { 285 t.Fatal("expected an error from ParseMultipartForm after call to MultipartReader") 286 } 287 } 288 289 // Test that MultipartReader errors if called 290 // after ParseMultipartForm on the same request. 291 func TestMultipartReaderOrder(t *testing.T) { 292 req := newTestMultipartRequest(t) 293 if err := req.ParseMultipartForm(25); err != nil { 294 t.Fatalf("ParseMultipartForm: %v", err) 295 } 296 defer req.MultipartForm.RemoveAll() 297 if _, err := req.MultipartReader(); err == nil { 298 t.Fatal("expected an error from MultipartReader after call to ParseMultipartForm") 299 } 300 } 301 302 // Test that FormFile errors if called after 303 // MultipartReader on the same request. 304 func TestFormFileOrder(t *testing.T) { 305 req := newTestMultipartRequest(t) 306 if _, err := req.MultipartReader(); err != nil { 307 t.Fatalf("MultipartReader: %v", err) 308 } 309 if _, _, err := req.FormFile(""); err == nil { 310 t.Fatal("expected an error from FormFile after call to MultipartReader") 311 } 312 } 313 314 var readRequestErrorTests = []struct { 315 in string 316 err error 317 }{ 318 {"GET / HTTP/1.1\r\nheader:foo\r\n\r\n", nil}, 319 {"GET / HTTP/1.1\r\nheader:foo\r\n", io.ErrUnexpectedEOF}, 320 {"", io.EOF}, 321 } 322 323 func TestReadRequestErrors(t *testing.T) { 324 for i, tt := range readRequestErrorTests { 325 _, err := ReadRequest(bufio.NewReader(strings.NewReader(tt.in))) 326 if err != tt.err { 327 t.Errorf("%d. got error = %v; want %v", i, err, tt.err) 328 } 329 } 330 } 331 332 var newRequestHostTests = []struct { 333 in, out string 334 }{ 335 {"http://www.example.com/", "www.example.com"}, 336 {"http://www.example.com:8080/", "www.example.com:8080"}, 337 338 {"http://192.168.0.1/", "192.168.0.1"}, 339 {"http://192.168.0.1:8080/", "192.168.0.1:8080"}, 340 341 {"http://[fe80::1]/", "[fe80::1]"}, 342 {"http://[fe80::1]:8080/", "[fe80::1]:8080"}, 343 {"http://[fe80::1%25en0]/", "[fe80::1%en0]"}, 344 {"http://[fe80::1%25en0]:8080/", "[fe80::1%en0]:8080"}, 345 } 346 347 func TestNewRequestHost(t *testing.T) { 348 for i, tt := range newRequestHostTests { 349 req, err := NewRequest("GET", tt.in, nil) 350 if err != nil { 351 t.Errorf("#%v: %v", i, err) 352 continue 353 } 354 if req.Host != tt.out { 355 t.Errorf("got %q; want %q", req.Host, tt.out) 356 } 357 } 358 } 359 360 func TestRequestInvalidMethod(t *testing.T) { 361 _, err := NewRequest("bad method", "http://foo.com/", nil) 362 if err == nil { 363 t.Error("expected error from NewRequest with invalid method") 364 } 365 req, err := NewRequest("GET", "http://foo.example/", nil) 366 if err != nil { 367 t.Fatal(err) 368 } 369 req.Method = "bad method" 370 _, err = DefaultClient.Do(req) 371 if err == nil || !strings.Contains(err.Error(), "invalid method") { 372 t.Errorf("Transport error = %v; want invalid method", err) 373 } 374 } 375 376 func TestNewRequestContentLength(t *testing.T) { 377 readByte := func(r io.Reader) io.Reader { 378 var b [1]byte 379 r.Read(b[:]) 380 return r 381 } 382 tests := []struct { 383 r io.Reader 384 want int64 385 }{ 386 {bytes.NewReader([]byte("123")), 3}, 387 {bytes.NewBuffer([]byte("1234")), 4}, 388 {strings.NewReader("12345"), 5}, 389 // Not detected: 390 {struct{ io.Reader }{strings.NewReader("xyz")}, 0}, 391 {io.NewSectionReader(strings.NewReader("x"), 0, 6), 0}, 392 {readByte(io.NewSectionReader(strings.NewReader("xy"), 0, 6)), 0}, 393 } 394 for _, tt := range tests { 395 req, err := NewRequest("POST", "http://localhost/", tt.r) 396 if err != nil { 397 t.Fatal(err) 398 } 399 if req.ContentLength != tt.want { 400 t.Errorf("ContentLength(%T) = %d; want %d", tt.r, req.ContentLength, tt.want) 401 } 402 } 403 } 404 405 var parseHTTPVersionTests = []struct { 406 vers string 407 major, minor int 408 ok bool 409 }{ 410 {"HTTP/0.9", 0, 9, true}, 411 {"HTTP/1.0", 1, 0, true}, 412 {"HTTP/1.1", 1, 1, true}, 413 {"HTTP/3.14", 3, 14, true}, 414 415 {"HTTP", 0, 0, false}, 416 {"HTTP/one.one", 0, 0, false}, 417 {"HTTP/1.1/", 0, 0, false}, 418 {"HTTP/-1,0", 0, 0, false}, 419 {"HTTP/0,-1", 0, 0, false}, 420 {"HTTP/", 0, 0, false}, 421 {"HTTP/1,1", 0, 0, false}, 422 } 423 424 func TestParseHTTPVersion(t *testing.T) { 425 for _, tt := range parseHTTPVersionTests { 426 major, minor, ok := ParseHTTPVersion(tt.vers) 427 if ok != tt.ok || major != tt.major || minor != tt.minor { 428 type version struct { 429 major, minor int 430 ok bool 431 } 432 t.Errorf("failed to parse %q, expected: %#v, got %#v", tt.vers, version{tt.major, tt.minor, tt.ok}, version{major, minor, ok}) 433 } 434 } 435 } 436 437 type getBasicAuthTest struct { 438 username, password string 439 ok bool 440 } 441 442 type basicAuthCredentialsTest struct { 443 username, password string 444 } 445 446 var getBasicAuthTests = []struct { 447 username, password string 448 ok bool 449 }{ 450 {"Aladdin", "open sesame", true}, 451 {"Aladdin", "open:sesame", true}, 452 {"", "", true}, 453 } 454 455 func TestGetBasicAuth(t *testing.T) { 456 for _, tt := range getBasicAuthTests { 457 r, _ := NewRequest("GET", "http://example.com/", nil) 458 r.SetBasicAuth(tt.username, tt.password) 459 username, password, ok := r.BasicAuth() 460 if ok != tt.ok || username != tt.username || password != tt.password { 461 t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok}, 462 getBasicAuthTest{tt.username, tt.password, tt.ok}) 463 } 464 } 465 // Unauthenticated request. 466 r, _ := NewRequest("GET", "http://example.com/", nil) 467 username, password, ok := r.BasicAuth() 468 if ok { 469 t.Errorf("expected false from BasicAuth when the request is unauthenticated") 470 } 471 want := basicAuthCredentialsTest{"", ""} 472 if username != want.username || password != want.password { 473 t.Errorf("expected credentials: %#v when the request is unauthenticated, got %#v", 474 want, basicAuthCredentialsTest{username, password}) 475 } 476 } 477 478 var parseBasicAuthTests = []struct { 479 header, username, password string 480 ok bool 481 }{ 482 {"Basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "Aladdin", "open sesame", true}, 483 {"Basic " + base64.StdEncoding.EncodeToString([]byte("Aladdin:open:sesame")), "Aladdin", "open:sesame", true}, 484 {"Basic " + base64.StdEncoding.EncodeToString([]byte(":")), "", "", true}, 485 {"Basic" + base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "", "", false}, 486 {base64.StdEncoding.EncodeToString([]byte("Aladdin:open sesame")), "", "", false}, 487 {"Basic ", "", "", false}, 488 {"Basic Aladdin:open sesame", "", "", false}, 489 {`Digest username="Aladdin"`, "", "", false}, 490 } 491 492 func TestParseBasicAuth(t *testing.T) { 493 for _, tt := range parseBasicAuthTests { 494 r, _ := NewRequest("GET", "http://example.com/", nil) 495 r.Header.Set("Authorization", tt.header) 496 username, password, ok := r.BasicAuth() 497 if ok != tt.ok || username != tt.username || password != tt.password { 498 t.Errorf("BasicAuth() = %#v, want %#v", getBasicAuthTest{username, password, ok}, 499 getBasicAuthTest{tt.username, tt.password, tt.ok}) 500 } 501 } 502 } 503 504 type logWrites struct { 505 t *testing.T 506 dst *[]string 507 } 508 509 func (l logWrites) WriteByte(c byte) error { 510 l.t.Fatalf("unexpected WriteByte call") 511 return nil 512 } 513 514 func (l logWrites) Write(p []byte) (n int, err error) { 515 *l.dst = append(*l.dst, string(p)) 516 return len(p), nil 517 } 518 519 func TestRequestWriteBufferedWriter(t *testing.T) { 520 got := []string{} 521 req, _ := NewRequest("GET", "http://foo.com/", nil) 522 req.Write(logWrites{t, &got}) 523 want := []string{ 524 "GET / HTTP/1.1\r\n", 525 "Host: foo.com\r\n", 526 "User-Agent: " + DefaultUserAgent + "\r\n", 527 "\r\n", 528 } 529 if !reflect.DeepEqual(got, want) { 530 t.Errorf("Writes = %q\n Want = %q", got, want) 531 } 532 } 533 534 func TestRequestBadHost(t *testing.T) { 535 got := []string{} 536 req, err := NewRequest("GET", "http://foo.com with spaces/after", nil) 537 if err != nil { 538 t.Fatal(err) 539 } 540 req.Write(logWrites{t, &got}) 541 want := []string{ 542 "GET /after HTTP/1.1\r\n", 543 "Host: foo.com\r\n", 544 "User-Agent: " + DefaultUserAgent + "\r\n", 545 "\r\n", 546 } 547 if !reflect.DeepEqual(got, want) { 548 t.Errorf("Writes = %q\n Want = %q", got, want) 549 } 550 } 551 552 func TestStarRequest(t *testing.T) { 553 req, err := ReadRequest(bufio.NewReader(strings.NewReader("M-SEARCH * HTTP/1.1\r\n\r\n"))) 554 if err != nil { 555 return 556 } 557 var out bytes.Buffer 558 if err := req.Write(&out); err != nil { 559 t.Fatal(err) 560 } 561 back, err := ReadRequest(bufio.NewReader(&out)) 562 if err != nil { 563 t.Fatal(err) 564 } 565 // Ignore the Headers (the User-Agent breaks the deep equal, 566 // but we don't care about it) 567 req.Header = nil 568 back.Header = nil 569 if !reflect.DeepEqual(req, back) { 570 t.Errorf("Original request doesn't match Request read back.") 571 t.Logf("Original: %#v", req) 572 t.Logf("Original.URL: %#v", req.URL) 573 t.Logf("Wrote: %s", out.Bytes()) 574 t.Logf("Read back (doesn't match Original): %#v", back) 575 } 576 } 577 578 type responseWriterJustWriter struct { 579 io.Writer 580 } 581 582 func (responseWriterJustWriter) Header() Header { panic("should not be called") } 583 func (responseWriterJustWriter) WriteHeader(int) { panic("should not be called") } 584 585 // delayedEOFReader never returns (n > 0, io.EOF), instead putting 586 // off the io.EOF until a subsequent Read call. 587 type delayedEOFReader struct { 588 r io.Reader 589 } 590 591 func (dr delayedEOFReader) Read(p []byte) (n int, err error) { 592 n, err = dr.r.Read(p) 593 if n > 0 && err == io.EOF { 594 err = nil 595 } 596 return 597 } 598 599 func TestIssue10884_MaxBytesEOF(t *testing.T) { 600 dst := ioutil.Discard 601 _, err := io.Copy(dst, MaxBytesReader( 602 responseWriterJustWriter{dst}, 603 ioutil.NopCloser(delayedEOFReader{strings.NewReader("12345")}), 604 5)) 605 if err != nil { 606 t.Fatal(err) 607 } 608 } 609 610 func testMissingFile(t *testing.T, req *Request) { 611 f, fh, err := req.FormFile("missing") 612 if f != nil { 613 t.Errorf("FormFile file = %v, want nil", f) 614 } 615 if fh != nil { 616 t.Errorf("FormFile file header = %q, want nil", fh) 617 } 618 if err != ErrMissingFile { 619 t.Errorf("FormFile err = %q, want ErrMissingFile", err) 620 } 621 } 622 623 func newTestMultipartRequest(t *testing.T) *Request { 624 b := strings.NewReader(strings.Replace(message, "\n", "\r\n", -1)) 625 req, err := NewRequest("POST", "/", b) 626 if err != nil { 627 t.Fatal("NewRequest:", err) 628 } 629 ctype := fmt.Sprintf(`multipart/form-data; boundary="%s"`, boundary) 630 req.Header.Set("Content-type", ctype) 631 return req 632 } 633 634 func validateTestMultipartContents(t *testing.T, req *Request, allMem bool) { 635 if g, e := req.FormValue("texta"), textaValue; g != e { 636 t.Errorf("texta value = %q, want %q", g, e) 637 } 638 if g, e := req.FormValue("textb"), textbValue; g != e { 639 t.Errorf("textb value = %q, want %q", g, e) 640 } 641 if g := req.FormValue("missing"); g != "" { 642 t.Errorf("missing value = %q, want empty string", g) 643 } 644 645 assertMem := func(n string, fd multipart.File) { 646 if _, ok := fd.(*os.File); ok { 647 t.Error(n, " is *os.File, should not be") 648 } 649 } 650 fda := testMultipartFile(t, req, "filea", "filea.txt", fileaContents) 651 defer fda.Close() 652 assertMem("filea", fda) 653 fdb := testMultipartFile(t, req, "fileb", "fileb.txt", filebContents) 654 defer fdb.Close() 655 if allMem { 656 assertMem("fileb", fdb) 657 } else { 658 if _, ok := fdb.(*os.File); !ok { 659 t.Errorf("fileb has unexpected underlying type %T", fdb) 660 } 661 } 662 663 testMissingFile(t, req) 664 } 665 666 func testMultipartFile(t *testing.T, req *Request, key, expectFilename, expectContent string) multipart.File { 667 f, fh, err := req.FormFile(key) 668 if err != nil { 669 t.Fatalf("FormFile(%q): %q", key, err) 670 } 671 if fh.Filename != expectFilename { 672 t.Errorf("filename = %q, want %q", fh.Filename, expectFilename) 673 } 674 var b bytes.Buffer 675 _, err = io.Copy(&b, f) 676 if err != nil { 677 t.Fatal("copying contents:", err) 678 } 679 if g := b.String(); g != expectContent { 680 t.Errorf("contents = %q, want %q", g, expectContent) 681 } 682 return f 683 } 684 685 const ( 686 fileaContents = "This is a test file." 687 filebContents = "Another test file." 688 textaValue = "foo" 689 textbValue = "bar" 690 boundary = `MyBoundary` 691 ) 692 693 const message = ` 694 --MyBoundary 695 Content-Disposition: form-data; name="filea"; filename="filea.txt" 696 Content-Type: text/plain 697 698 ` + fileaContents + ` 699 --MyBoundary 700 Content-Disposition: form-data; name="fileb"; filename="fileb.txt" 701 Content-Type: text/plain 702 703 ` + filebContents + ` 704 --MyBoundary 705 Content-Disposition: form-data; name="texta" 706 707 ` + textaValue + ` 708 --MyBoundary 709 Content-Disposition: form-data; name="textb" 710 711 ` + textbValue + ` 712 --MyBoundary-- 713 ` 714 715 func benchmarkReadRequest(b *testing.B, request string) { 716 request = request + "\n" // final \n 717 request = strings.Replace(request, "\n", "\r\n", -1) // expand \n to \r\n 718 b.SetBytes(int64(len(request))) 719 r := bufio.NewReader(&infiniteReader{buf: []byte(request)}) 720 b.ReportAllocs() 721 b.ResetTimer() 722 for i := 0; i < b.N; i++ { 723 _, err := ReadRequest(r) 724 if err != nil { 725 b.Fatalf("failed to read request: %v", err) 726 } 727 } 728 } 729 730 // infiniteReader satisfies Read requests as if the contents of buf 731 // loop indefinitely. 732 type infiniteReader struct { 733 buf []byte 734 offset int 735 } 736 737 func (r *infiniteReader) Read(b []byte) (int, error) { 738 n := copy(b, r.buf[r.offset:]) 739 r.offset = (r.offset + n) % len(r.buf) 740 return n, nil 741 } 742 743 func BenchmarkReadRequestChrome(b *testing.B) { 744 // https://github.com/felixge/node-http-perf/blob/master/fixtures/get.http 745 benchmarkReadRequest(b, `GET / HTTP/1.1 746 Host: localhost:8080 747 Connection: keep-alive 748 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 749 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 750 Accept-Encoding: gzip,deflate,sdch 751 Accept-Language: en-US,en;q=0.8 752 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 753 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 754 `) 755 } 756 757 func BenchmarkReadRequestCurl(b *testing.B) { 758 // curl http://localhost:8080/ 759 benchmarkReadRequest(b, `GET / HTTP/1.1 760 User-Agent: curl/7.27.0 761 Host: localhost:8080 762 Accept: */* 763 `) 764 } 765 766 func BenchmarkReadRequestApachebench(b *testing.B) { 767 // ab -n 1 -c 1 http://localhost:8080/ 768 benchmarkReadRequest(b, `GET / HTTP/1.0 769 Host: localhost:8080 770 User-Agent: ApacheBench/2.3 771 Accept: */* 772 `) 773 } 774 775 func BenchmarkReadRequestSiege(b *testing.B) { 776 // siege -r 1 -c 1 http://localhost:8080/ 777 benchmarkReadRequest(b, `GET / HTTP/1.1 778 Host: localhost:8080 779 Accept: */* 780 Accept-Encoding: gzip 781 User-Agent: JoeDog/1.00 [en] (X11; I; Siege 2.70) 782 Connection: keep-alive 783 `) 784 } 785 786 func BenchmarkReadRequestWrk(b *testing.B) { 787 // wrk -t 1 -r 1 -c 1 http://localhost:8080/ 788 benchmarkReadRequest(b, `GET / HTTP/1.1 789 Host: localhost:8080 790 `) 791 }