github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/src/pkg/net/http/serve_test.go (about) 1 // Copyright 2010 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 // End-to-end serving tests 6 7 package http_test 8 9 import ( 10 "bufio" 11 "bytes" 12 "crypto/tls" 13 "errors" 14 "fmt" 15 "io" 16 "io/ioutil" 17 "log" 18 "net" 19 . "net/http" 20 "net/http/httptest" 21 "net/http/httputil" 22 "net/url" 23 "os" 24 "os/exec" 25 "reflect" 26 "runtime" 27 "strconv" 28 "strings" 29 "sync" 30 "sync/atomic" 31 "syscall" 32 "testing" 33 "time" 34 ) 35 36 type dummyAddr string 37 type oneConnListener struct { 38 conn net.Conn 39 } 40 41 func (l *oneConnListener) Accept() (c net.Conn, err error) { 42 c = l.conn 43 if c == nil { 44 err = io.EOF 45 return 46 } 47 err = nil 48 l.conn = nil 49 return 50 } 51 52 func (l *oneConnListener) Close() error { 53 return nil 54 } 55 56 func (l *oneConnListener) Addr() net.Addr { 57 return dummyAddr("test-address") 58 } 59 60 func (a dummyAddr) Network() string { 61 return string(a) 62 } 63 64 func (a dummyAddr) String() string { 65 return string(a) 66 } 67 68 type noopConn struct{} 69 70 func (noopConn) LocalAddr() net.Addr { return dummyAddr("local-addr") } 71 func (noopConn) RemoteAddr() net.Addr { return dummyAddr("remote-addr") } 72 func (noopConn) SetDeadline(t time.Time) error { return nil } 73 func (noopConn) SetReadDeadline(t time.Time) error { return nil } 74 func (noopConn) SetWriteDeadline(t time.Time) error { return nil } 75 76 type rwTestConn struct { 77 io.Reader 78 io.Writer 79 noopConn 80 81 closeFunc func() error // called if non-nil 82 closec chan bool // else, if non-nil, send value to it on close 83 } 84 85 func (c *rwTestConn) Close() error { 86 if c.closeFunc != nil { 87 return c.closeFunc() 88 } 89 select { 90 case c.closec <- true: 91 default: 92 } 93 return nil 94 } 95 96 type testConn struct { 97 readBuf bytes.Buffer 98 writeBuf bytes.Buffer 99 closec chan bool // if non-nil, send value to it on close 100 noopConn 101 } 102 103 func (c *testConn) Read(b []byte) (int, error) { 104 return c.readBuf.Read(b) 105 } 106 107 func (c *testConn) Write(b []byte) (int, error) { 108 return c.writeBuf.Write(b) 109 } 110 111 func (c *testConn) Close() error { 112 select { 113 case c.closec <- true: 114 default: 115 } 116 return nil 117 } 118 119 // reqBytes treats req as a request (with \n delimiters) and returns it with \r\n delimiters, 120 // ending in \r\n\r\n 121 func reqBytes(req string) []byte { 122 return []byte(strings.Replace(strings.TrimSpace(req), "\n", "\r\n", -1) + "\r\n\r\n") 123 } 124 125 type handlerTest struct { 126 handler Handler 127 } 128 129 func newHandlerTest(h Handler) handlerTest { 130 return handlerTest{h} 131 } 132 133 func (ht handlerTest) rawResponse(req string) string { 134 reqb := reqBytes(req) 135 var output bytes.Buffer 136 conn := &rwTestConn{ 137 Reader: bytes.NewReader(reqb), 138 Writer: &output, 139 closec: make(chan bool, 1), 140 } 141 ln := &oneConnListener{conn: conn} 142 go Serve(ln, ht.handler) 143 <-conn.closec 144 return output.String() 145 } 146 147 func TestConsumingBodyOnNextConn(t *testing.T) { 148 conn := new(testConn) 149 for i := 0; i < 2; i++ { 150 conn.readBuf.Write([]byte( 151 "POST / HTTP/1.1\r\n" + 152 "Host: test\r\n" + 153 "Content-Length: 11\r\n" + 154 "\r\n" + 155 "foo=1&bar=1")) 156 } 157 158 reqNum := 0 159 ch := make(chan *Request) 160 servech := make(chan error) 161 listener := &oneConnListener{conn} 162 handler := func(res ResponseWriter, req *Request) { 163 reqNum++ 164 ch <- req 165 } 166 167 go func() { 168 servech <- Serve(listener, HandlerFunc(handler)) 169 }() 170 171 var req *Request 172 req = <-ch 173 if req == nil { 174 t.Fatal("Got nil first request.") 175 } 176 if req.Method != "POST" { 177 t.Errorf("For request #1's method, got %q; expected %q", 178 req.Method, "POST") 179 } 180 181 req = <-ch 182 if req == nil { 183 t.Fatal("Got nil first request.") 184 } 185 if req.Method != "POST" { 186 t.Errorf("For request #2's method, got %q; expected %q", 187 req.Method, "POST") 188 } 189 190 if serveerr := <-servech; serveerr != io.EOF { 191 t.Errorf("Serve returned %q; expected EOF", serveerr) 192 } 193 } 194 195 type stringHandler string 196 197 func (s stringHandler) ServeHTTP(w ResponseWriter, r *Request) { 198 w.Header().Set("Result", string(s)) 199 } 200 201 var handlers = []struct { 202 pattern string 203 msg string 204 }{ 205 {"/", "Default"}, 206 {"/someDir/", "someDir"}, 207 {"someHost.com/someDir/", "someHost.com/someDir"}, 208 } 209 210 var vtests = []struct { 211 url string 212 expected string 213 }{ 214 {"http://localhost/someDir/apage", "someDir"}, 215 {"http://localhost/otherDir/apage", "Default"}, 216 {"http://someHost.com/someDir/apage", "someHost.com/someDir"}, 217 {"http://otherHost.com/someDir/apage", "someDir"}, 218 {"http://otherHost.com/aDir/apage", "Default"}, 219 // redirections for trees 220 {"http://localhost/someDir", "/someDir/"}, 221 {"http://someHost.com/someDir", "/someDir/"}, 222 } 223 224 func TestHostHandlers(t *testing.T) { 225 defer afterTest(t) 226 mux := NewServeMux() 227 for _, h := range handlers { 228 mux.Handle(h.pattern, stringHandler(h.msg)) 229 } 230 ts := httptest.NewServer(mux) 231 defer ts.Close() 232 233 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 234 if err != nil { 235 t.Fatal(err) 236 } 237 defer conn.Close() 238 cc := httputil.NewClientConn(conn, nil) 239 for _, vt := range vtests { 240 var r *Response 241 var req Request 242 if req.URL, err = url.Parse(vt.url); err != nil { 243 t.Errorf("cannot parse url: %v", err) 244 continue 245 } 246 if err := cc.Write(&req); err != nil { 247 t.Errorf("writing request: %v", err) 248 continue 249 } 250 r, err := cc.Read(&req) 251 if err != nil { 252 t.Errorf("reading response: %v", err) 253 continue 254 } 255 switch r.StatusCode { 256 case StatusOK: 257 s := r.Header.Get("Result") 258 if s != vt.expected { 259 t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) 260 } 261 case StatusMovedPermanently: 262 s := r.Header.Get("Location") 263 if s != vt.expected { 264 t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) 265 } 266 default: 267 t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode) 268 } 269 } 270 } 271 272 var serveMuxRegister = []struct { 273 pattern string 274 h Handler 275 }{ 276 {"/dir/", serve(200)}, 277 {"/search", serve(201)}, 278 {"codesearch.google.com/search", serve(202)}, 279 {"codesearch.google.com/", serve(203)}, 280 {"example.com/", HandlerFunc(checkQueryStringHandler)}, 281 } 282 283 // serve returns a handler that sends a response with the given code. 284 func serve(code int) HandlerFunc { 285 return func(w ResponseWriter, r *Request) { 286 w.WriteHeader(code) 287 } 288 } 289 290 // checkQueryStringHandler checks if r.URL.RawQuery has the same value 291 // as the URL excluding the scheme and the query string and sends 200 292 // response code if it is, 500 otherwise. 293 func checkQueryStringHandler(w ResponseWriter, r *Request) { 294 u := *r.URL 295 u.Scheme = "http" 296 u.Host = r.Host 297 u.RawQuery = "" 298 if "http://"+r.URL.RawQuery == u.String() { 299 w.WriteHeader(200) 300 } else { 301 w.WriteHeader(500) 302 } 303 } 304 305 var serveMuxTests = []struct { 306 method string 307 host string 308 path string 309 code int 310 pattern string 311 }{ 312 {"GET", "google.com", "/", 404, ""}, 313 {"GET", "google.com", "/dir", 301, "/dir/"}, 314 {"GET", "google.com", "/dir/", 200, "/dir/"}, 315 {"GET", "google.com", "/dir/file", 200, "/dir/"}, 316 {"GET", "google.com", "/search", 201, "/search"}, 317 {"GET", "google.com", "/search/", 404, ""}, 318 {"GET", "google.com", "/search/foo", 404, ""}, 319 {"GET", "codesearch.google.com", "/search", 202, "codesearch.google.com/search"}, 320 {"GET", "codesearch.google.com", "/search/", 203, "codesearch.google.com/"}, 321 {"GET", "codesearch.google.com", "/search/foo", 203, "codesearch.google.com/"}, 322 {"GET", "codesearch.google.com", "/", 203, "codesearch.google.com/"}, 323 {"GET", "images.google.com", "/search", 201, "/search"}, 324 {"GET", "images.google.com", "/search/", 404, ""}, 325 {"GET", "images.google.com", "/search/foo", 404, ""}, 326 {"GET", "google.com", "/../search", 301, "/search"}, 327 {"GET", "google.com", "/dir/..", 301, ""}, 328 {"GET", "google.com", "/dir/..", 301, ""}, 329 {"GET", "google.com", "/dir/./file", 301, "/dir/"}, 330 331 // The /foo -> /foo/ redirect applies to CONNECT requests 332 // but the path canonicalization does not. 333 {"CONNECT", "google.com", "/dir", 301, "/dir/"}, 334 {"CONNECT", "google.com", "/../search", 404, ""}, 335 {"CONNECT", "google.com", "/dir/..", 200, "/dir/"}, 336 {"CONNECT", "google.com", "/dir/..", 200, "/dir/"}, 337 {"CONNECT", "google.com", "/dir/./file", 200, "/dir/"}, 338 } 339 340 func TestServeMuxHandler(t *testing.T) { 341 mux := NewServeMux() 342 for _, e := range serveMuxRegister { 343 mux.Handle(e.pattern, e.h) 344 } 345 346 for _, tt := range serveMuxTests { 347 r := &Request{ 348 Method: tt.method, 349 Host: tt.host, 350 URL: &url.URL{ 351 Path: tt.path, 352 }, 353 } 354 h, pattern := mux.Handler(r) 355 rr := httptest.NewRecorder() 356 h.ServeHTTP(rr, r) 357 if pattern != tt.pattern || rr.Code != tt.code { 358 t.Errorf("%s %s %s = %d, %q, want %d, %q", tt.method, tt.host, tt.path, rr.Code, pattern, tt.code, tt.pattern) 359 } 360 } 361 } 362 363 var serveMuxTests2 = []struct { 364 method string 365 host string 366 url string 367 code int 368 redirOk bool 369 }{ 370 {"GET", "google.com", "/", 404, false}, 371 {"GET", "example.com", "/test/?example.com/test/", 200, false}, 372 {"GET", "example.com", "test/?example.com/test/", 200, true}, 373 } 374 375 // TestServeMuxHandlerRedirects tests that automatic redirects generated by 376 // mux.Handler() shouldn't clear the request's query string. 377 func TestServeMuxHandlerRedirects(t *testing.T) { 378 mux := NewServeMux() 379 for _, e := range serveMuxRegister { 380 mux.Handle(e.pattern, e.h) 381 } 382 383 for _, tt := range serveMuxTests2 { 384 tries := 1 385 turl := tt.url 386 for tries > 0 { 387 u, e := url.Parse(turl) 388 if e != nil { 389 t.Fatal(e) 390 } 391 r := &Request{ 392 Method: tt.method, 393 Host: tt.host, 394 URL: u, 395 } 396 h, _ := mux.Handler(r) 397 rr := httptest.NewRecorder() 398 h.ServeHTTP(rr, r) 399 if rr.Code != 301 { 400 if rr.Code != tt.code { 401 t.Errorf("%s %s %s = %d, want %d", tt.method, tt.host, tt.url, rr.Code, tt.code) 402 } 403 break 404 } 405 if !tt.redirOk { 406 t.Errorf("%s %s %s, unexpected redirect", tt.method, tt.host, tt.url) 407 break 408 } 409 turl = rr.HeaderMap.Get("Location") 410 tries-- 411 } 412 if tries < 0 { 413 t.Errorf("%s %s %s, too many redirects", tt.method, tt.host, tt.url) 414 } 415 } 416 } 417 418 // Tests for http://code.google.com/p/go/issues/detail?id=900 419 func TestMuxRedirectLeadingSlashes(t *testing.T) { 420 paths := []string{"//foo.txt", "///foo.txt", "/../../foo.txt"} 421 for _, path := range paths { 422 req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n"))) 423 if err != nil { 424 t.Errorf("%s", err) 425 } 426 mux := NewServeMux() 427 resp := httptest.NewRecorder() 428 429 mux.ServeHTTP(resp, req) 430 431 if loc, expected := resp.Header().Get("Location"), "/foo.txt"; loc != expected { 432 t.Errorf("Expected Location header set to %q; got %q", expected, loc) 433 return 434 } 435 436 if code, expected := resp.Code, StatusMovedPermanently; code != expected { 437 t.Errorf("Expected response code of StatusMovedPermanently; got %d", code) 438 return 439 } 440 } 441 } 442 443 func TestServerTimeouts(t *testing.T) { 444 if runtime.GOOS == "plan9" { 445 t.Skip("skipping test; see http://golang.org/issue/7237") 446 } 447 defer afterTest(t) 448 reqNum := 0 449 ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) { 450 reqNum++ 451 fmt.Fprintf(res, "req=%d", reqNum) 452 })) 453 ts.Config.ReadTimeout = 250 * time.Millisecond 454 ts.Config.WriteTimeout = 250 * time.Millisecond 455 ts.Start() 456 defer ts.Close() 457 458 // Hit the HTTP server successfully. 459 tr := &Transport{DisableKeepAlives: true} // they interfere with this test 460 defer tr.CloseIdleConnections() 461 c := &Client{Transport: tr} 462 r, err := c.Get(ts.URL) 463 if err != nil { 464 t.Fatalf("http Get #1: %v", err) 465 } 466 got, _ := ioutil.ReadAll(r.Body) 467 expected := "req=1" 468 if string(got) != expected { 469 t.Errorf("Unexpected response for request #1; got %q; expected %q", 470 string(got), expected) 471 } 472 473 // Slow client that should timeout. 474 t1 := time.Now() 475 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 476 if err != nil { 477 t.Fatalf("Dial: %v", err) 478 } 479 buf := make([]byte, 1) 480 n, err := conn.Read(buf) 481 latency := time.Since(t1) 482 if n != 0 || err != io.EOF { 483 t.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF) 484 } 485 if latency < 200*time.Millisecond /* fudge from 250 ms above */ { 486 t.Errorf("got EOF after %s, want >= %s", latency, 200*time.Millisecond) 487 } 488 489 // Hit the HTTP server successfully again, verifying that the 490 // previous slow connection didn't run our handler. (that we 491 // get "req=2", not "req=3") 492 r, err = Get(ts.URL) 493 if err != nil { 494 t.Fatalf("http Get #2: %v", err) 495 } 496 got, _ = ioutil.ReadAll(r.Body) 497 expected = "req=2" 498 if string(got) != expected { 499 t.Errorf("Get #2 got %q, want %q", string(got), expected) 500 } 501 502 if !testing.Short() { 503 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 504 if err != nil { 505 t.Fatalf("Dial: %v", err) 506 } 507 defer conn.Close() 508 go io.Copy(ioutil.Discard, conn) 509 for i := 0; i < 5; i++ { 510 _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n")) 511 if err != nil { 512 t.Fatalf("on write %d: %v", i, err) 513 } 514 time.Sleep(ts.Config.ReadTimeout / 2) 515 } 516 } 517 } 518 519 // golang.org/issue/4741 -- setting only a write timeout that triggers 520 // shouldn't cause a handler to block forever on reads (next HTTP 521 // request) that will never happen. 522 func TestOnlyWriteTimeout(t *testing.T) { 523 if runtime.GOOS == "plan9" { 524 t.Skip("skipping test; see http://golang.org/issue/7237") 525 } 526 defer afterTest(t) 527 var conn net.Conn 528 var afterTimeoutErrc = make(chan error, 1) 529 ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, req *Request) { 530 buf := make([]byte, 512<<10) 531 _, err := w.Write(buf) 532 if err != nil { 533 t.Errorf("handler Write error: %v", err) 534 return 535 } 536 conn.SetWriteDeadline(time.Now().Add(-30 * time.Second)) 537 _, err = w.Write(buf) 538 afterTimeoutErrc <- err 539 })) 540 ts.Listener = trackLastConnListener{ts.Listener, &conn} 541 ts.Start() 542 defer ts.Close() 543 544 tr := &Transport{DisableKeepAlives: false} 545 defer tr.CloseIdleConnections() 546 c := &Client{Transport: tr} 547 548 errc := make(chan error) 549 go func() { 550 res, err := c.Get(ts.URL) 551 if err != nil { 552 errc <- err 553 return 554 } 555 _, err = io.Copy(ioutil.Discard, res.Body) 556 errc <- err 557 }() 558 select { 559 case err := <-errc: 560 if err == nil { 561 t.Errorf("expected an error from Get request") 562 } 563 case <-time.After(5 * time.Second): 564 t.Fatal("timeout waiting for Get error") 565 } 566 if err := <-afterTimeoutErrc; err == nil { 567 t.Error("expected write error after timeout") 568 } 569 } 570 571 // trackLastConnListener tracks the last net.Conn that was accepted. 572 type trackLastConnListener struct { 573 net.Listener 574 last *net.Conn // destination 575 } 576 577 func (l trackLastConnListener) Accept() (c net.Conn, err error) { 578 c, err = l.Listener.Accept() 579 *l.last = c 580 return 581 } 582 583 // TestIdentityResponse verifies that a handler can unset 584 func TestIdentityResponse(t *testing.T) { 585 defer afterTest(t) 586 handler := HandlerFunc(func(rw ResponseWriter, req *Request) { 587 rw.Header().Set("Content-Length", "3") 588 rw.Header().Set("Transfer-Encoding", req.FormValue("te")) 589 switch { 590 case req.FormValue("overwrite") == "1": 591 _, err := rw.Write([]byte("foo TOO LONG")) 592 if err != ErrContentLength { 593 t.Errorf("expected ErrContentLength; got %v", err) 594 } 595 case req.FormValue("underwrite") == "1": 596 rw.Header().Set("Content-Length", "500") 597 rw.Write([]byte("too short")) 598 default: 599 rw.Write([]byte("foo")) 600 } 601 }) 602 603 ts := httptest.NewServer(handler) 604 defer ts.Close() 605 606 // Note: this relies on the assumption (which is true) that 607 // Get sends HTTP/1.1 or greater requests. Otherwise the 608 // server wouldn't have the choice to send back chunked 609 // responses. 610 for _, te := range []string{"", "identity"} { 611 url := ts.URL + "/?te=" + te 612 res, err := Get(url) 613 if err != nil { 614 t.Fatalf("error with Get of %s: %v", url, err) 615 } 616 if cl, expected := res.ContentLength, int64(3); cl != expected { 617 t.Errorf("for %s expected res.ContentLength of %d; got %d", url, expected, cl) 618 } 619 if cl, expected := res.Header.Get("Content-Length"), "3"; cl != expected { 620 t.Errorf("for %s expected Content-Length header of %q; got %q", url, expected, cl) 621 } 622 if tl, expected := len(res.TransferEncoding), 0; tl != expected { 623 t.Errorf("for %s expected len(res.TransferEncoding) of %d; got %d (%v)", 624 url, expected, tl, res.TransferEncoding) 625 } 626 res.Body.Close() 627 } 628 629 // Verify that ErrContentLength is returned 630 url := ts.URL + "/?overwrite=1" 631 res, err := Get(url) 632 if err != nil { 633 t.Fatalf("error with Get of %s: %v", url, err) 634 } 635 res.Body.Close() 636 637 // Verify that the connection is closed when the declared Content-Length 638 // is larger than what the handler wrote. 639 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 640 if err != nil { 641 t.Fatalf("error dialing: %v", err) 642 } 643 _, err = conn.Write([]byte("GET /?underwrite=1 HTTP/1.1\r\nHost: foo\r\n\r\n")) 644 if err != nil { 645 t.Fatalf("error writing: %v", err) 646 } 647 648 // The ReadAll will hang for a failing test, so use a Timer to 649 // fail explicitly. 650 goTimeout(t, 2*time.Second, func() { 651 got, _ := ioutil.ReadAll(conn) 652 expectedSuffix := "\r\n\r\ntoo short" 653 if !strings.HasSuffix(string(got), expectedSuffix) { 654 t.Errorf("Expected output to end with %q; got response body %q", 655 expectedSuffix, string(got)) 656 } 657 }) 658 } 659 660 func testTCPConnectionCloses(t *testing.T, req string, h Handler) { 661 defer afterTest(t) 662 s := httptest.NewServer(h) 663 defer s.Close() 664 665 conn, err := net.Dial("tcp", s.Listener.Addr().String()) 666 if err != nil { 667 t.Fatal("dial error:", err) 668 } 669 defer conn.Close() 670 671 _, err = fmt.Fprint(conn, req) 672 if err != nil { 673 t.Fatal("print error:", err) 674 } 675 676 r := bufio.NewReader(conn) 677 res, err := ReadResponse(r, &Request{Method: "GET"}) 678 if err != nil { 679 t.Fatal("ReadResponse error:", err) 680 } 681 682 didReadAll := make(chan bool, 1) 683 go func() { 684 select { 685 case <-time.After(5 * time.Second): 686 t.Error("body not closed after 5s") 687 return 688 case <-didReadAll: 689 } 690 }() 691 692 _, err = ioutil.ReadAll(r) 693 if err != nil { 694 t.Fatal("read error:", err) 695 } 696 didReadAll <- true 697 698 if !res.Close { 699 t.Errorf("Response.Close = false; want true") 700 } 701 } 702 703 // TestServeHTTP10Close verifies that HTTP/1.0 requests won't be kept alive. 704 func TestServeHTTP10Close(t *testing.T) { 705 testTCPConnectionCloses(t, "GET / HTTP/1.0\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 706 ServeFile(w, r, "testdata/file") 707 })) 708 } 709 710 // TestClientCanClose verifies that clients can also force a connection to close. 711 func TestClientCanClose(t *testing.T) { 712 testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nConnection: close\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 713 // Nothing. 714 })) 715 } 716 717 // TestHandlersCanSetConnectionClose verifies that handlers can force a connection to close, 718 // even for HTTP/1.1 requests. 719 func TestHandlersCanSetConnectionClose11(t *testing.T) { 720 testTCPConnectionCloses(t, "GET / HTTP/1.1\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 721 w.Header().Set("Connection", "close") 722 })) 723 } 724 725 func TestHandlersCanSetConnectionClose10(t *testing.T) { 726 testTCPConnectionCloses(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 727 w.Header().Set("Connection", "close") 728 })) 729 } 730 731 func TestSetsRemoteAddr(t *testing.T) { 732 defer afterTest(t) 733 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 734 fmt.Fprintf(w, "%s", r.RemoteAddr) 735 })) 736 defer ts.Close() 737 738 res, err := Get(ts.URL) 739 if err != nil { 740 t.Fatalf("Get error: %v", err) 741 } 742 body, err := ioutil.ReadAll(res.Body) 743 if err != nil { 744 t.Fatalf("ReadAll error: %v", err) 745 } 746 ip := string(body) 747 if !strings.HasPrefix(ip, "127.0.0.1:") && !strings.HasPrefix(ip, "[::1]:") { 748 t.Fatalf("Expected local addr; got %q", ip) 749 } 750 } 751 752 func TestChunkedResponseHeaders(t *testing.T) { 753 defer afterTest(t) 754 log.SetOutput(ioutil.Discard) // is noisy otherwise 755 defer log.SetOutput(os.Stderr) 756 757 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 758 w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted 759 w.(Flusher).Flush() 760 fmt.Fprintf(w, "I am a chunked response.") 761 })) 762 defer ts.Close() 763 764 res, err := Get(ts.URL) 765 if err != nil { 766 t.Fatalf("Get error: %v", err) 767 } 768 defer res.Body.Close() 769 if g, e := res.ContentLength, int64(-1); g != e { 770 t.Errorf("expected ContentLength of %d; got %d", e, g) 771 } 772 if g, e := res.TransferEncoding, []string{"chunked"}; !reflect.DeepEqual(g, e) { 773 t.Errorf("expected TransferEncoding of %v; got %v", e, g) 774 } 775 if _, haveCL := res.Header["Content-Length"]; haveCL { 776 t.Errorf("Unexpected Content-Length") 777 } 778 } 779 780 // Test304Responses verifies that 304s don't declare that they're 781 // chunking in their response headers and aren't allowed to produce 782 // output. 783 func Test304Responses(t *testing.T) { 784 defer afterTest(t) 785 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 786 w.WriteHeader(StatusNotModified) 787 _, err := w.Write([]byte("illegal body")) 788 if err != ErrBodyNotAllowed { 789 t.Errorf("on Write, expected ErrBodyNotAllowed, got %v", err) 790 } 791 })) 792 defer ts.Close() 793 res, err := Get(ts.URL) 794 if err != nil { 795 t.Error(err) 796 } 797 if len(res.TransferEncoding) > 0 { 798 t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding) 799 } 800 body, err := ioutil.ReadAll(res.Body) 801 if err != nil { 802 t.Error(err) 803 } 804 if len(body) > 0 { 805 t.Errorf("got unexpected body %q", string(body)) 806 } 807 } 808 809 // TestHeadResponses verifies that all MIME type sniffing and Content-Length 810 // counting of GET requests also happens on HEAD requests. 811 func TestHeadResponses(t *testing.T) { 812 defer afterTest(t) 813 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 814 _, err := w.Write([]byte("<html>")) 815 if err != nil { 816 t.Errorf("ResponseWriter.Write: %v", err) 817 } 818 819 // Also exercise the ReaderFrom path 820 _, err = io.Copy(w, strings.NewReader("789a")) 821 if err != nil { 822 t.Errorf("Copy(ResponseWriter, ...): %v", err) 823 } 824 })) 825 defer ts.Close() 826 res, err := Head(ts.URL) 827 if err != nil { 828 t.Error(err) 829 } 830 if len(res.TransferEncoding) > 0 { 831 t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding) 832 } 833 if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" { 834 t.Errorf("Content-Type: %q; want text/html; charset=utf-8", ct) 835 } 836 if v := res.ContentLength; v != 10 { 837 t.Errorf("Content-Length: %d; want 10", v) 838 } 839 body, err := ioutil.ReadAll(res.Body) 840 if err != nil { 841 t.Error(err) 842 } 843 if len(body) > 0 { 844 t.Errorf("got unexpected body %q", string(body)) 845 } 846 } 847 848 func TestTLSHandshakeTimeout(t *testing.T) { 849 if runtime.GOOS == "plan9" { 850 t.Skip("skipping test; see http://golang.org/issue/7237") 851 } 852 defer afterTest(t) 853 ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 854 errc := make(chanWriter, 10) // but only expecting 1 855 ts.Config.ReadTimeout = 250 * time.Millisecond 856 ts.Config.ErrorLog = log.New(errc, "", 0) 857 ts.StartTLS() 858 defer ts.Close() 859 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 860 if err != nil { 861 t.Fatalf("Dial: %v", err) 862 } 863 defer conn.Close() 864 goTimeout(t, 10*time.Second, func() { 865 var buf [1]byte 866 n, err := conn.Read(buf[:]) 867 if err == nil || n != 0 { 868 t.Errorf("Read = %d, %v; want an error and no bytes", n, err) 869 } 870 }) 871 select { 872 case v := <-errc: 873 if !strings.Contains(v, "timeout") && !strings.Contains(v, "TLS handshake") { 874 t.Errorf("expected a TLS handshake timeout error; got %q", v) 875 } 876 case <-time.After(5 * time.Second): 877 t.Errorf("timeout waiting for logged error") 878 } 879 } 880 881 func TestTLSServer(t *testing.T) { 882 defer afterTest(t) 883 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 884 if r.TLS != nil { 885 w.Header().Set("X-TLS-Set", "true") 886 if r.TLS.HandshakeComplete { 887 w.Header().Set("X-TLS-HandshakeComplete", "true") 888 } 889 } 890 })) 891 ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0) 892 defer ts.Close() 893 894 // Connect an idle TCP connection to this server before we run 895 // our real tests. This idle connection used to block forever 896 // in the TLS handshake, preventing future connections from 897 // being accepted. It may prevent future accidental blocking 898 // in newConn. 899 idleConn, err := net.Dial("tcp", ts.Listener.Addr().String()) 900 if err != nil { 901 t.Fatalf("Dial: %v", err) 902 } 903 defer idleConn.Close() 904 goTimeout(t, 10*time.Second, func() { 905 if !strings.HasPrefix(ts.URL, "https://") { 906 t.Errorf("expected test TLS server to start with https://, got %q", ts.URL) 907 return 908 } 909 noVerifyTransport := &Transport{ 910 TLSClientConfig: &tls.Config{ 911 InsecureSkipVerify: true, 912 }, 913 } 914 client := &Client{Transport: noVerifyTransport} 915 res, err := client.Get(ts.URL) 916 if err != nil { 917 t.Error(err) 918 return 919 } 920 if res == nil { 921 t.Errorf("got nil Response") 922 return 923 } 924 defer res.Body.Close() 925 if res.Header.Get("X-TLS-Set") != "true" { 926 t.Errorf("expected X-TLS-Set response header") 927 return 928 } 929 if res.Header.Get("X-TLS-HandshakeComplete") != "true" { 930 t.Errorf("expected X-TLS-HandshakeComplete header") 931 } 932 }) 933 } 934 935 type serverExpectTest struct { 936 contentLength int // of request body 937 chunked bool 938 expectation string // e.g. "100-continue" 939 readBody bool // whether handler should read the body (if false, sends StatusUnauthorized) 940 expectedResponse string // expected substring in first line of http response 941 } 942 943 func expectTest(contentLength int, expectation string, readBody bool, expectedResponse string) serverExpectTest { 944 return serverExpectTest{ 945 contentLength: contentLength, 946 expectation: expectation, 947 readBody: readBody, 948 expectedResponse: expectedResponse, 949 } 950 } 951 952 var serverExpectTests = []serverExpectTest{ 953 // Normal 100-continues, case-insensitive. 954 expectTest(100, "100-continue", true, "100 Continue"), 955 expectTest(100, "100-cOntInUE", true, "100 Continue"), 956 957 // No 100-continue. 958 expectTest(100, "", true, "200 OK"), 959 960 // 100-continue but requesting client to deny us, 961 // so it never reads the body. 962 expectTest(100, "100-continue", false, "401 Unauthorized"), 963 // Likewise without 100-continue: 964 expectTest(100, "", false, "401 Unauthorized"), 965 966 // Non-standard expectations are failures 967 expectTest(0, "a-pony", false, "417 Expectation Failed"), 968 969 // Expect-100 requested but no body (is apparently okay: Issue 7625) 970 expectTest(0, "100-continue", true, "200 OK"), 971 // Expect-100 requested but handler doesn't read the body 972 expectTest(0, "100-continue", false, "401 Unauthorized"), 973 // Expect-100 continue with no body, but a chunked body. 974 { 975 expectation: "100-continue", 976 readBody: true, 977 chunked: true, 978 expectedResponse: "100 Continue", 979 }, 980 } 981 982 // Tests that the server responds to the "Expect" request header 983 // correctly. 984 func TestServerExpect(t *testing.T) { 985 defer afterTest(t) 986 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 987 // Note using r.FormValue("readbody") because for POST 988 // requests that would read from r.Body, which we only 989 // conditionally want to do. 990 if strings.Contains(r.URL.RawQuery, "readbody=true") { 991 ioutil.ReadAll(r.Body) 992 w.Write([]byte("Hi")) 993 } else { 994 w.WriteHeader(StatusUnauthorized) 995 } 996 })) 997 defer ts.Close() 998 999 runTest := func(test serverExpectTest) { 1000 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1001 if err != nil { 1002 t.Fatalf("Dial: %v", err) 1003 } 1004 defer conn.Close() 1005 1006 // Only send the body immediately if we're acting like an HTTP client 1007 // that doesn't send 100-continue expectations. 1008 writeBody := test.contentLength != 0 && strings.ToLower(test.expectation) != "100-continue" 1009 1010 go func() { 1011 contentLen := fmt.Sprintf("Content-Length: %d", test.contentLength) 1012 if test.chunked { 1013 contentLen = "Transfer-Encoding: chunked" 1014 } 1015 _, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+ 1016 "Connection: close\r\n"+ 1017 "%s\r\n"+ 1018 "Expect: %s\r\nHost: foo\r\n\r\n", 1019 test.readBody, contentLen, test.expectation) 1020 if err != nil { 1021 t.Errorf("On test %#v, error writing request headers: %v", test, err) 1022 return 1023 } 1024 if writeBody { 1025 var targ io.WriteCloser = struct { 1026 io.Writer 1027 io.Closer 1028 }{ 1029 conn, 1030 ioutil.NopCloser(nil), 1031 } 1032 if test.chunked { 1033 targ = httputil.NewChunkedWriter(conn) 1034 } 1035 body := strings.Repeat("A", test.contentLength) 1036 _, err = fmt.Fprint(targ, body) 1037 if err == nil { 1038 err = targ.Close() 1039 } 1040 if err != nil { 1041 if !test.readBody { 1042 // Server likely already hung up on us. 1043 // See larger comment below. 1044 t.Logf("On test %#v, acceptable error writing request body: %v", test, err) 1045 return 1046 } 1047 t.Errorf("On test %#v, error writing request body: %v", test, err) 1048 } 1049 } 1050 }() 1051 bufr := bufio.NewReader(conn) 1052 line, err := bufr.ReadString('\n') 1053 if err != nil { 1054 if writeBody && !test.readBody { 1055 // This is an acceptable failure due to a possible TCP race: 1056 // We were still writing data and the server hung up on us. A TCP 1057 // implementation may send a RST if our request body data was known 1058 // to be lost, which may trigger our reads to fail. 1059 // See RFC 1122 page 88. 1060 t.Logf("On test %#v, acceptable error from ReadString: %v", test, err) 1061 return 1062 } 1063 t.Fatalf("On test %#v, ReadString: %v", test, err) 1064 } 1065 if !strings.Contains(line, test.expectedResponse) { 1066 t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse) 1067 } 1068 } 1069 1070 for _, test := range serverExpectTests { 1071 runTest(test) 1072 } 1073 } 1074 1075 // Under a ~256KB (maxPostHandlerReadBytes) threshold, the server 1076 // should consume client request bodies that a handler didn't read. 1077 func TestServerUnreadRequestBodyLittle(t *testing.T) { 1078 conn := new(testConn) 1079 body := strings.Repeat("x", 100<<10) 1080 conn.readBuf.Write([]byte(fmt.Sprintf( 1081 "POST / HTTP/1.1\r\n"+ 1082 "Host: test\r\n"+ 1083 "Content-Length: %d\r\n"+ 1084 "\r\n", len(body)))) 1085 conn.readBuf.Write([]byte(body)) 1086 1087 done := make(chan bool) 1088 1089 ls := &oneConnListener{conn} 1090 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 1091 defer close(done) 1092 if conn.readBuf.Len() < len(body)/2 { 1093 t.Errorf("on request, read buffer length is %d; expected about 100 KB", conn.readBuf.Len()) 1094 } 1095 rw.WriteHeader(200) 1096 rw.(Flusher).Flush() 1097 if g, e := conn.readBuf.Len(), 0; g != e { 1098 t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e) 1099 } 1100 if c := rw.Header().Get("Connection"); c != "" { 1101 t.Errorf(`Connection header = %q; want ""`, c) 1102 } 1103 })) 1104 <-done 1105 } 1106 1107 // Over a ~256KB (maxPostHandlerReadBytes) threshold, the server 1108 // should ignore client request bodies that a handler didn't read 1109 // and close the connection. 1110 func TestServerUnreadRequestBodyLarge(t *testing.T) { 1111 conn := new(testConn) 1112 body := strings.Repeat("x", 1<<20) 1113 conn.readBuf.Write([]byte(fmt.Sprintf( 1114 "POST / HTTP/1.1\r\n"+ 1115 "Host: test\r\n"+ 1116 "Content-Length: %d\r\n"+ 1117 "\r\n", len(body)))) 1118 conn.readBuf.Write([]byte(body)) 1119 conn.closec = make(chan bool, 1) 1120 1121 ls := &oneConnListener{conn} 1122 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 1123 if conn.readBuf.Len() < len(body)/2 { 1124 t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len()) 1125 } 1126 rw.WriteHeader(200) 1127 rw.(Flusher).Flush() 1128 if conn.readBuf.Len() < len(body)/2 { 1129 t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len()) 1130 } 1131 })) 1132 <-conn.closec 1133 1134 if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") { 1135 t.Errorf("Expected a Connection: close header; got response: %s", res) 1136 } 1137 } 1138 1139 func TestTimeoutHandler(t *testing.T) { 1140 defer afterTest(t) 1141 sendHi := make(chan bool, 1) 1142 writeErrors := make(chan error, 1) 1143 sayHi := HandlerFunc(func(w ResponseWriter, r *Request) { 1144 <-sendHi 1145 _, werr := w.Write([]byte("hi")) 1146 writeErrors <- werr 1147 }) 1148 timeout := make(chan time.Time, 1) // write to this to force timeouts 1149 ts := httptest.NewServer(NewTestTimeoutHandler(sayHi, timeout)) 1150 defer ts.Close() 1151 1152 // Succeed without timing out: 1153 sendHi <- true 1154 res, err := Get(ts.URL) 1155 if err != nil { 1156 t.Error(err) 1157 } 1158 if g, e := res.StatusCode, StatusOK; g != e { 1159 t.Errorf("got res.StatusCode %d; expected %d", g, e) 1160 } 1161 body, _ := ioutil.ReadAll(res.Body) 1162 if g, e := string(body), "hi"; g != e { 1163 t.Errorf("got body %q; expected %q", g, e) 1164 } 1165 if g := <-writeErrors; g != nil { 1166 t.Errorf("got unexpected Write error on first request: %v", g) 1167 } 1168 1169 // Times out: 1170 timeout <- time.Time{} 1171 res, err = Get(ts.URL) 1172 if err != nil { 1173 t.Error(err) 1174 } 1175 if g, e := res.StatusCode, StatusServiceUnavailable; g != e { 1176 t.Errorf("got res.StatusCode %d; expected %d", g, e) 1177 } 1178 body, _ = ioutil.ReadAll(res.Body) 1179 if !strings.Contains(string(body), "<title>Timeout</title>") { 1180 t.Errorf("expected timeout body; got %q", string(body)) 1181 } 1182 1183 // Now make the previously-timed out handler speak again, 1184 // which verifies the panic is handled: 1185 sendHi <- true 1186 if g, e := <-writeErrors, ErrHandlerTimeout; g != e { 1187 t.Errorf("expected Write error of %v; got %v", e, g) 1188 } 1189 } 1190 1191 // Verifies we don't path.Clean() on the wrong parts in redirects. 1192 func TestRedirectMunging(t *testing.T) { 1193 req, _ := NewRequest("GET", "http://example.com/", nil) 1194 1195 resp := httptest.NewRecorder() 1196 Redirect(resp, req, "/foo?next=http://bar.com/", 302) 1197 if g, e := resp.Header().Get("Location"), "/foo?next=http://bar.com/"; g != e { 1198 t.Errorf("Location header was %q; want %q", g, e) 1199 } 1200 1201 resp = httptest.NewRecorder() 1202 Redirect(resp, req, "http://localhost:8080/_ah/login?continue=http://localhost:8080/", 302) 1203 if g, e := resp.Header().Get("Location"), "http://localhost:8080/_ah/login?continue=http://localhost:8080/"; g != e { 1204 t.Errorf("Location header was %q; want %q", g, e) 1205 } 1206 } 1207 1208 func TestRedirectBadPath(t *testing.T) { 1209 // This used to crash. It's not valid input (bad path), but it 1210 // shouldn't crash. 1211 rr := httptest.NewRecorder() 1212 req := &Request{ 1213 Method: "GET", 1214 URL: &url.URL{ 1215 Scheme: "http", 1216 Path: "not-empty-but-no-leading-slash", // bogus 1217 }, 1218 } 1219 Redirect(rr, req, "", 304) 1220 if rr.Code != 304 { 1221 t.Errorf("Code = %d; want 304", rr.Code) 1222 } 1223 } 1224 1225 // TestZeroLengthPostAndResponse exercises an optimization done by the Transport: 1226 // when there is no body (either because the method doesn't permit a body, or an 1227 // explicit Content-Length of zero is present), then the transport can re-use the 1228 // connection immediately. But when it re-uses the connection, it typically closes 1229 // the previous request's body, which is not optimal for zero-lengthed bodies, 1230 // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF. 1231 func TestZeroLengthPostAndResponse(t *testing.T) { 1232 defer afterTest(t) 1233 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 1234 all, err := ioutil.ReadAll(r.Body) 1235 if err != nil { 1236 t.Fatalf("handler ReadAll: %v", err) 1237 } 1238 if len(all) != 0 { 1239 t.Errorf("handler got %d bytes; expected 0", len(all)) 1240 } 1241 rw.Header().Set("Content-Length", "0") 1242 })) 1243 defer ts.Close() 1244 1245 req, err := NewRequest("POST", ts.URL, strings.NewReader("")) 1246 if err != nil { 1247 t.Fatal(err) 1248 } 1249 req.ContentLength = 0 1250 1251 var resp [5]*Response 1252 for i := range resp { 1253 resp[i], err = DefaultClient.Do(req) 1254 if err != nil { 1255 t.Fatalf("client post #%d: %v", i, err) 1256 } 1257 } 1258 1259 for i := range resp { 1260 all, err := ioutil.ReadAll(resp[i].Body) 1261 if err != nil { 1262 t.Fatalf("req #%d: client ReadAll: %v", i, err) 1263 } 1264 if len(all) != 0 { 1265 t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all)) 1266 } 1267 } 1268 } 1269 1270 func TestHandlerPanicNil(t *testing.T) { 1271 testHandlerPanic(t, false, nil) 1272 } 1273 1274 func TestHandlerPanic(t *testing.T) { 1275 testHandlerPanic(t, false, "intentional death for testing") 1276 } 1277 1278 func TestHandlerPanicWithHijack(t *testing.T) { 1279 testHandlerPanic(t, true, "intentional death for testing") 1280 } 1281 1282 func testHandlerPanic(t *testing.T, withHijack bool, panicValue interface{}) { 1283 defer afterTest(t) 1284 // Unlike the other tests that set the log output to ioutil.Discard 1285 // to quiet the output, this test uses a pipe. The pipe serves three 1286 // purposes: 1287 // 1288 // 1) The log.Print from the http server (generated by the caught 1289 // panic) will go to the pipe instead of stderr, making the 1290 // output quiet. 1291 // 1292 // 2) We read from the pipe to verify that the handler 1293 // actually caught the panic and logged something. 1294 // 1295 // 3) The blocking Read call prevents this TestHandlerPanic 1296 // function from exiting before the HTTP server handler 1297 // finishes crashing. If this text function exited too 1298 // early (and its defer log.SetOutput(os.Stderr) ran), 1299 // then the crash output could spill into the next test. 1300 pr, pw := io.Pipe() 1301 log.SetOutput(pw) 1302 defer log.SetOutput(os.Stderr) 1303 defer pw.Close() 1304 1305 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1306 if withHijack { 1307 rwc, _, err := w.(Hijacker).Hijack() 1308 if err != nil { 1309 t.Logf("unexpected error: %v", err) 1310 } 1311 defer rwc.Close() 1312 } 1313 panic(panicValue) 1314 })) 1315 defer ts.Close() 1316 1317 // Do a blocking read on the log output pipe so its logging 1318 // doesn't bleed into the next test. But wait only 5 seconds 1319 // for it. 1320 done := make(chan bool, 1) 1321 go func() { 1322 buf := make([]byte, 4<<10) 1323 _, err := pr.Read(buf) 1324 pr.Close() 1325 if err != nil && err != io.EOF { 1326 t.Error(err) 1327 } 1328 done <- true 1329 }() 1330 1331 _, err := Get(ts.URL) 1332 if err == nil { 1333 t.Logf("expected an error") 1334 } 1335 1336 if panicValue == nil { 1337 return 1338 } 1339 1340 select { 1341 case <-done: 1342 return 1343 case <-time.After(5 * time.Second): 1344 t.Fatal("expected server handler to log an error") 1345 } 1346 } 1347 1348 func TestNoDate(t *testing.T) { 1349 defer afterTest(t) 1350 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1351 w.Header()["Date"] = nil 1352 })) 1353 defer ts.Close() 1354 res, err := Get(ts.URL) 1355 if err != nil { 1356 t.Fatal(err) 1357 } 1358 _, present := res.Header["Date"] 1359 if present { 1360 t.Fatalf("Expected no Date header; got %v", res.Header["Date"]) 1361 } 1362 } 1363 1364 func TestStripPrefix(t *testing.T) { 1365 defer afterTest(t) 1366 h := HandlerFunc(func(w ResponseWriter, r *Request) { 1367 w.Header().Set("X-Path", r.URL.Path) 1368 }) 1369 ts := httptest.NewServer(StripPrefix("/foo", h)) 1370 defer ts.Close() 1371 1372 res, err := Get(ts.URL + "/foo/bar") 1373 if err != nil { 1374 t.Fatal(err) 1375 } 1376 if g, e := res.Header.Get("X-Path"), "/bar"; g != e { 1377 t.Errorf("test 1: got %s, want %s", g, e) 1378 } 1379 res.Body.Close() 1380 1381 res, err = Get(ts.URL + "/bar") 1382 if err != nil { 1383 t.Fatal(err) 1384 } 1385 if g, e := res.StatusCode, 404; g != e { 1386 t.Errorf("test 2: got status %v, want %v", g, e) 1387 } 1388 res.Body.Close() 1389 } 1390 1391 func TestRequestLimit(t *testing.T) { 1392 defer afterTest(t) 1393 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1394 t.Fatalf("didn't expect to get request in Handler") 1395 })) 1396 defer ts.Close() 1397 req, _ := NewRequest("GET", ts.URL, nil) 1398 var bytesPerHeader = len("header12345: val12345\r\n") 1399 for i := 0; i < ((DefaultMaxHeaderBytes+4096)/bytesPerHeader)+1; i++ { 1400 req.Header.Set(fmt.Sprintf("header%05d", i), fmt.Sprintf("val%05d", i)) 1401 } 1402 res, err := DefaultClient.Do(req) 1403 if err != nil { 1404 // Some HTTP clients may fail on this undefined behavior (server replying and 1405 // closing the connection while the request is still being written), but 1406 // we do support it (at least currently), so we expect a response below. 1407 t.Fatalf("Do: %v", err) 1408 } 1409 defer res.Body.Close() 1410 if res.StatusCode != 413 { 1411 t.Fatalf("expected 413 response status; got: %d %s", res.StatusCode, res.Status) 1412 } 1413 } 1414 1415 type neverEnding byte 1416 1417 func (b neverEnding) Read(p []byte) (n int, err error) { 1418 for i := range p { 1419 p[i] = byte(b) 1420 } 1421 return len(p), nil 1422 } 1423 1424 type countReader struct { 1425 r io.Reader 1426 n *int64 1427 } 1428 1429 func (cr countReader) Read(p []byte) (n int, err error) { 1430 n, err = cr.r.Read(p) 1431 atomic.AddInt64(cr.n, int64(n)) 1432 return 1433 } 1434 1435 func TestRequestBodyLimit(t *testing.T) { 1436 defer afterTest(t) 1437 const limit = 1 << 20 1438 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1439 r.Body = MaxBytesReader(w, r.Body, limit) 1440 n, err := io.Copy(ioutil.Discard, r.Body) 1441 if err == nil { 1442 t.Errorf("expected error from io.Copy") 1443 } 1444 if n != limit { 1445 t.Errorf("io.Copy = %d, want %d", n, limit) 1446 } 1447 })) 1448 defer ts.Close() 1449 1450 nWritten := new(int64) 1451 req, _ := NewRequest("POST", ts.URL, io.LimitReader(countReader{neverEnding('a'), nWritten}, limit*200)) 1452 1453 // Send the POST, but don't care it succeeds or not. The 1454 // remote side is going to reply and then close the TCP 1455 // connection, and HTTP doesn't really define if that's 1456 // allowed or not. Some HTTP clients will get the response 1457 // and some (like ours, currently) will complain that the 1458 // request write failed, without reading the response. 1459 // 1460 // But that's okay, since what we're really testing is that 1461 // the remote side hung up on us before we wrote too much. 1462 _, _ = DefaultClient.Do(req) 1463 1464 if atomic.LoadInt64(nWritten) > limit*100 { 1465 t.Errorf("handler restricted the request body to %d bytes, but client managed to write %d", 1466 limit, nWritten) 1467 } 1468 } 1469 1470 // TestClientWriteShutdown tests that if the client shuts down the write 1471 // side of their TCP connection, the server doesn't send a 400 Bad Request. 1472 func TestClientWriteShutdown(t *testing.T) { 1473 if runtime.GOOS == "plan9" { 1474 t.Skip("skipping test; see http://golang.org/issue/7237") 1475 } 1476 defer afterTest(t) 1477 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 1478 defer ts.Close() 1479 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1480 if err != nil { 1481 t.Fatalf("Dial: %v", err) 1482 } 1483 err = conn.(*net.TCPConn).CloseWrite() 1484 if err != nil { 1485 t.Fatalf("Dial: %v", err) 1486 } 1487 donec := make(chan bool) 1488 go func() { 1489 defer close(donec) 1490 bs, err := ioutil.ReadAll(conn) 1491 if err != nil { 1492 t.Fatalf("ReadAll: %v", err) 1493 } 1494 got := string(bs) 1495 if got != "" { 1496 t.Errorf("read %q from server; want nothing", got) 1497 } 1498 }() 1499 select { 1500 case <-donec: 1501 case <-time.After(10 * time.Second): 1502 t.Fatalf("timeout") 1503 } 1504 } 1505 1506 // Tests that chunked server responses that write 1 byte at a time are 1507 // buffered before chunk headers are added, not after chunk headers. 1508 func TestServerBufferedChunking(t *testing.T) { 1509 conn := new(testConn) 1510 conn.readBuf.Write([]byte("GET / HTTP/1.1\r\n\r\n")) 1511 conn.closec = make(chan bool, 1) 1512 ls := &oneConnListener{conn} 1513 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 1514 rw.(Flusher).Flush() // force the Header to be sent, in chunking mode, not counting the length 1515 rw.Write([]byte{'x'}) 1516 rw.Write([]byte{'y'}) 1517 rw.Write([]byte{'z'}) 1518 })) 1519 <-conn.closec 1520 if !bytes.HasSuffix(conn.writeBuf.Bytes(), []byte("\r\n\r\n3\r\nxyz\r\n0\r\n\r\n")) { 1521 t.Errorf("response didn't end with a single 3 byte 'xyz' chunk; got:\n%q", 1522 conn.writeBuf.Bytes()) 1523 } 1524 } 1525 1526 // Tests that the server flushes its response headers out when it's 1527 // ignoring the response body and waits a bit before forcefully 1528 // closing the TCP connection, causing the client to get a RST. 1529 // See http://golang.org/issue/3595 1530 func TestServerGracefulClose(t *testing.T) { 1531 defer afterTest(t) 1532 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1533 Error(w, "bye", StatusUnauthorized) 1534 })) 1535 defer ts.Close() 1536 1537 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1538 if err != nil { 1539 t.Fatal(err) 1540 } 1541 defer conn.Close() 1542 const bodySize = 5 << 20 1543 req := []byte(fmt.Sprintf("POST / HTTP/1.1\r\nHost: foo.com\r\nContent-Length: %d\r\n\r\n", bodySize)) 1544 for i := 0; i < bodySize; i++ { 1545 req = append(req, 'x') 1546 } 1547 writeErr := make(chan error) 1548 go func() { 1549 _, err := conn.Write(req) 1550 writeErr <- err 1551 }() 1552 br := bufio.NewReader(conn) 1553 lineNum := 0 1554 for { 1555 line, err := br.ReadString('\n') 1556 if err == io.EOF { 1557 break 1558 } 1559 if err != nil { 1560 t.Fatalf("ReadLine: %v", err) 1561 } 1562 lineNum++ 1563 if lineNum == 1 && !strings.Contains(line, "401 Unauthorized") { 1564 t.Errorf("Response line = %q; want a 401", line) 1565 } 1566 } 1567 // Wait for write to finish. This is a broken pipe on both 1568 // Darwin and Linux, but checking this isn't the point of 1569 // the test. 1570 <-writeErr 1571 } 1572 1573 func TestCaseSensitiveMethod(t *testing.T) { 1574 defer afterTest(t) 1575 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1576 if r.Method != "get" { 1577 t.Errorf(`Got method %q; want "get"`, r.Method) 1578 } 1579 })) 1580 defer ts.Close() 1581 req, _ := NewRequest("get", ts.URL, nil) 1582 res, err := DefaultClient.Do(req) 1583 if err != nil { 1584 t.Error(err) 1585 return 1586 } 1587 res.Body.Close() 1588 } 1589 1590 // TestContentLengthZero tests that for both an HTTP/1.0 and HTTP/1.1 1591 // request (both keep-alive), when a Handler never writes any 1592 // response, the net/http package adds a "Content-Length: 0" response 1593 // header. 1594 func TestContentLengthZero(t *testing.T) { 1595 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {})) 1596 defer ts.Close() 1597 1598 for _, version := range []string{"HTTP/1.0", "HTTP/1.1"} { 1599 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1600 if err != nil { 1601 t.Fatalf("error dialing: %v", err) 1602 } 1603 _, err = fmt.Fprintf(conn, "GET / %v\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n", version) 1604 if err != nil { 1605 t.Fatalf("error writing: %v", err) 1606 } 1607 req, _ := NewRequest("GET", "/", nil) 1608 res, err := ReadResponse(bufio.NewReader(conn), req) 1609 if err != nil { 1610 t.Fatalf("error reading response: %v", err) 1611 } 1612 if te := res.TransferEncoding; len(te) > 0 { 1613 t.Errorf("For version %q, Transfer-Encoding = %q; want none", version, te) 1614 } 1615 if cl := res.ContentLength; cl != 0 { 1616 t.Errorf("For version %q, Content-Length = %v; want 0", version, cl) 1617 } 1618 conn.Close() 1619 } 1620 } 1621 1622 func TestCloseNotifier(t *testing.T) { 1623 defer afterTest(t) 1624 gotReq := make(chan bool, 1) 1625 sawClose := make(chan bool, 1) 1626 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 1627 gotReq <- true 1628 cc := rw.(CloseNotifier).CloseNotify() 1629 <-cc 1630 sawClose <- true 1631 })) 1632 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1633 if err != nil { 1634 t.Fatalf("error dialing: %v", err) 1635 } 1636 diec := make(chan bool) 1637 go func() { 1638 _, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n") 1639 if err != nil { 1640 t.Fatal(err) 1641 } 1642 <-diec 1643 conn.Close() 1644 }() 1645 For: 1646 for { 1647 select { 1648 case <-gotReq: 1649 diec <- true 1650 case <-sawClose: 1651 break For 1652 case <-time.After(5 * time.Second): 1653 t.Fatal("timeout") 1654 } 1655 } 1656 ts.Close() 1657 } 1658 1659 func TestCloseNotifierChanLeak(t *testing.T) { 1660 defer afterTest(t) 1661 req := reqBytes("GET / HTTP/1.0\nHost: golang.org") 1662 for i := 0; i < 20; i++ { 1663 var output bytes.Buffer 1664 conn := &rwTestConn{ 1665 Reader: bytes.NewReader(req), 1666 Writer: &output, 1667 closec: make(chan bool, 1), 1668 } 1669 ln := &oneConnListener{conn: conn} 1670 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 1671 // Ignore the return value and never read from 1672 // it, testing that we don't leak goroutines 1673 // on the sending side: 1674 _ = rw.(CloseNotifier).CloseNotify() 1675 }) 1676 go Serve(ln, handler) 1677 <-conn.closec 1678 } 1679 } 1680 1681 func TestOptions(t *testing.T) { 1682 uric := make(chan string, 2) // only expect 1, but leave space for 2 1683 mux := NewServeMux() 1684 mux.HandleFunc("/", func(w ResponseWriter, r *Request) { 1685 uric <- r.RequestURI 1686 }) 1687 ts := httptest.NewServer(mux) 1688 defer ts.Close() 1689 1690 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1691 if err != nil { 1692 t.Fatal(err) 1693 } 1694 defer conn.Close() 1695 1696 // An OPTIONS * request should succeed. 1697 _, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n")) 1698 if err != nil { 1699 t.Fatal(err) 1700 } 1701 br := bufio.NewReader(conn) 1702 res, err := ReadResponse(br, &Request{Method: "OPTIONS"}) 1703 if err != nil { 1704 t.Fatal(err) 1705 } 1706 if res.StatusCode != 200 { 1707 t.Errorf("Got non-200 response to OPTIONS *: %#v", res) 1708 } 1709 1710 // A GET * request on a ServeMux should fail. 1711 _, err = conn.Write([]byte("GET * HTTP/1.1\r\nHost: foo.com\r\n\r\n")) 1712 if err != nil { 1713 t.Fatal(err) 1714 } 1715 res, err = ReadResponse(br, &Request{Method: "GET"}) 1716 if err != nil { 1717 t.Fatal(err) 1718 } 1719 if res.StatusCode != 400 { 1720 t.Errorf("Got non-400 response to GET *: %#v", res) 1721 } 1722 1723 res, err = Get(ts.URL + "/second") 1724 if err != nil { 1725 t.Fatal(err) 1726 } 1727 res.Body.Close() 1728 if got := <-uric; got != "/second" { 1729 t.Errorf("Handler saw request for %q; want /second", got) 1730 } 1731 } 1732 1733 // Tests regarding the ordering of Write, WriteHeader, Header, and 1734 // Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the 1735 // (*response).header to the wire. In Go 1.1, the actual wire flush is 1736 // delayed, so we could maybe tack on a Content-Length and better 1737 // Content-Type after we see more (or all) of the output. To preserve 1738 // compatibility with Go 1, we need to be careful to track which 1739 // headers were live at the time of WriteHeader, so we write the same 1740 // ones, even if the handler modifies them (~erroneously) after the 1741 // first Write. 1742 func TestHeaderToWire(t *testing.T) { 1743 tests := []struct { 1744 name string 1745 handler func(ResponseWriter, *Request) 1746 check func(output string) error 1747 }{ 1748 { 1749 name: "write without Header", 1750 handler: func(rw ResponseWriter, r *Request) { 1751 rw.Write([]byte("hello world")) 1752 }, 1753 check: func(got string) error { 1754 if !strings.Contains(got, "Content-Length:") { 1755 return errors.New("no content-length") 1756 } 1757 if !strings.Contains(got, "Content-Type: text/plain") { 1758 return errors.New("no content-length") 1759 } 1760 return nil 1761 }, 1762 }, 1763 { 1764 name: "Header mutation before write", 1765 handler: func(rw ResponseWriter, r *Request) { 1766 h := rw.Header() 1767 h.Set("Content-Type", "some/type") 1768 rw.Write([]byte("hello world")) 1769 h.Set("Too-Late", "bogus") 1770 }, 1771 check: func(got string) error { 1772 if !strings.Contains(got, "Content-Length:") { 1773 return errors.New("no content-length") 1774 } 1775 if !strings.Contains(got, "Content-Type: some/type") { 1776 return errors.New("wrong content-type") 1777 } 1778 if strings.Contains(got, "Too-Late") { 1779 return errors.New("don't want too-late header") 1780 } 1781 return nil 1782 }, 1783 }, 1784 { 1785 name: "write then useless Header mutation", 1786 handler: func(rw ResponseWriter, r *Request) { 1787 rw.Write([]byte("hello world")) 1788 rw.Header().Set("Too-Late", "Write already wrote headers") 1789 }, 1790 check: func(got string) error { 1791 if strings.Contains(got, "Too-Late") { 1792 return errors.New("header appeared from after WriteHeader") 1793 } 1794 return nil 1795 }, 1796 }, 1797 { 1798 name: "flush then write", 1799 handler: func(rw ResponseWriter, r *Request) { 1800 rw.(Flusher).Flush() 1801 rw.Write([]byte("post-flush")) 1802 rw.Header().Set("Too-Late", "Write already wrote headers") 1803 }, 1804 check: func(got string) error { 1805 if !strings.Contains(got, "Transfer-Encoding: chunked") { 1806 return errors.New("not chunked") 1807 } 1808 if strings.Contains(got, "Too-Late") { 1809 return errors.New("header appeared from after WriteHeader") 1810 } 1811 return nil 1812 }, 1813 }, 1814 { 1815 name: "header then flush", 1816 handler: func(rw ResponseWriter, r *Request) { 1817 rw.Header().Set("Content-Type", "some/type") 1818 rw.(Flusher).Flush() 1819 rw.Write([]byte("post-flush")) 1820 rw.Header().Set("Too-Late", "Write already wrote headers") 1821 }, 1822 check: func(got string) error { 1823 if !strings.Contains(got, "Transfer-Encoding: chunked") { 1824 return errors.New("not chunked") 1825 } 1826 if strings.Contains(got, "Too-Late") { 1827 return errors.New("header appeared from after WriteHeader") 1828 } 1829 if !strings.Contains(got, "Content-Type: some/type") { 1830 return errors.New("wrong content-length") 1831 } 1832 return nil 1833 }, 1834 }, 1835 { 1836 name: "sniff-on-first-write content-type", 1837 handler: func(rw ResponseWriter, r *Request) { 1838 rw.Write([]byte("<html><head></head><body>some html</body></html>")) 1839 rw.Header().Set("Content-Type", "x/wrong") 1840 }, 1841 check: func(got string) error { 1842 if !strings.Contains(got, "Content-Type: text/html") { 1843 return errors.New("wrong content-length; want html") 1844 } 1845 return nil 1846 }, 1847 }, 1848 { 1849 name: "explicit content-type wins", 1850 handler: func(rw ResponseWriter, r *Request) { 1851 rw.Header().Set("Content-Type", "some/type") 1852 rw.Write([]byte("<html><head></head><body>some html</body></html>")) 1853 }, 1854 check: func(got string) error { 1855 if !strings.Contains(got, "Content-Type: some/type") { 1856 return errors.New("wrong content-length; want html") 1857 } 1858 return nil 1859 }, 1860 }, 1861 { 1862 name: "empty handler", 1863 handler: func(rw ResponseWriter, r *Request) { 1864 }, 1865 check: func(got string) error { 1866 if !strings.Contains(got, "Content-Type: text/plain") { 1867 return errors.New("wrong content-length; want text/plain") 1868 } 1869 if !strings.Contains(got, "Content-Length: 0") { 1870 return errors.New("want 0 content-length") 1871 } 1872 return nil 1873 }, 1874 }, 1875 { 1876 name: "only Header, no write", 1877 handler: func(rw ResponseWriter, r *Request) { 1878 rw.Header().Set("Some-Header", "some-value") 1879 }, 1880 check: func(got string) error { 1881 if !strings.Contains(got, "Some-Header") { 1882 return errors.New("didn't get header") 1883 } 1884 return nil 1885 }, 1886 }, 1887 { 1888 name: "WriteHeader call", 1889 handler: func(rw ResponseWriter, r *Request) { 1890 rw.WriteHeader(404) 1891 rw.Header().Set("Too-Late", "some-value") 1892 }, 1893 check: func(got string) error { 1894 if !strings.Contains(got, "404") { 1895 return errors.New("wrong status") 1896 } 1897 if strings.Contains(got, "Some-Header") { 1898 return errors.New("shouldn't have seen Too-Late") 1899 } 1900 return nil 1901 }, 1902 }, 1903 } 1904 for _, tc := range tests { 1905 ht := newHandlerTest(HandlerFunc(tc.handler)) 1906 got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org") 1907 if err := tc.check(got); err != nil { 1908 t.Errorf("%s: %v\nGot response:\n%s", tc.name, err, got) 1909 } 1910 } 1911 } 1912 1913 // goTimeout runs f, failing t if f takes more than ns to complete. 1914 func goTimeout(t *testing.T, d time.Duration, f func()) { 1915 ch := make(chan bool, 2) 1916 timer := time.AfterFunc(d, func() { 1917 t.Errorf("Timeout expired after %v", d) 1918 ch <- true 1919 }) 1920 defer timer.Stop() 1921 go func() { 1922 defer func() { ch <- true }() 1923 f() 1924 }() 1925 <-ch 1926 } 1927 1928 type errorListener struct { 1929 errs []error 1930 } 1931 1932 func (l *errorListener) Accept() (c net.Conn, err error) { 1933 if len(l.errs) == 0 { 1934 return nil, io.EOF 1935 } 1936 err = l.errs[0] 1937 l.errs = l.errs[1:] 1938 return 1939 } 1940 1941 func (l *errorListener) Close() error { 1942 return nil 1943 } 1944 1945 func (l *errorListener) Addr() net.Addr { 1946 return dummyAddr("test-address") 1947 } 1948 1949 func TestAcceptMaxFds(t *testing.T) { 1950 log.SetOutput(ioutil.Discard) // is noisy otherwise 1951 defer log.SetOutput(os.Stderr) 1952 1953 ln := &errorListener{[]error{ 1954 &net.OpError{ 1955 Op: "accept", 1956 Err: syscall.EMFILE, 1957 }}} 1958 err := Serve(ln, HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {}))) 1959 if err != io.EOF { 1960 t.Errorf("got error %v, want EOF", err) 1961 } 1962 } 1963 1964 func TestWriteAfterHijack(t *testing.T) { 1965 req := reqBytes("GET / HTTP/1.1\nHost: golang.org") 1966 var buf bytes.Buffer 1967 wrotec := make(chan bool, 1) 1968 conn := &rwTestConn{ 1969 Reader: bytes.NewReader(req), 1970 Writer: &buf, 1971 closec: make(chan bool, 1), 1972 } 1973 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 1974 conn, bufrw, err := rw.(Hijacker).Hijack() 1975 if err != nil { 1976 t.Error(err) 1977 return 1978 } 1979 go func() { 1980 bufrw.Write([]byte("[hijack-to-bufw]")) 1981 bufrw.Flush() 1982 conn.Write([]byte("[hijack-to-conn]")) 1983 conn.Close() 1984 wrotec <- true 1985 }() 1986 }) 1987 ln := &oneConnListener{conn: conn} 1988 go Serve(ln, handler) 1989 <-conn.closec 1990 <-wrotec 1991 if g, w := buf.String(), "[hijack-to-bufw][hijack-to-conn]"; g != w { 1992 t.Errorf("wrote %q; want %q", g, w) 1993 } 1994 } 1995 1996 func TestDoubleHijack(t *testing.T) { 1997 req := reqBytes("GET / HTTP/1.1\nHost: golang.org") 1998 var buf bytes.Buffer 1999 conn := &rwTestConn{ 2000 Reader: bytes.NewReader(req), 2001 Writer: &buf, 2002 closec: make(chan bool, 1), 2003 } 2004 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 2005 conn, _, err := rw.(Hijacker).Hijack() 2006 if err != nil { 2007 t.Error(err) 2008 return 2009 } 2010 _, _, err = rw.(Hijacker).Hijack() 2011 if err == nil { 2012 t.Errorf("got err = nil; want err != nil") 2013 } 2014 conn.Close() 2015 }) 2016 ln := &oneConnListener{conn: conn} 2017 go Serve(ln, handler) 2018 <-conn.closec 2019 } 2020 2021 // http://code.google.com/p/go/issues/detail?id=5955 2022 // Note that this does not test the "request too large" 2023 // exit path from the http server. This is intentional; 2024 // not sending Connection: close is just a minor wire 2025 // optimization and is pointless if dealing with a 2026 // badly behaved client. 2027 func TestHTTP10ConnectionHeader(t *testing.T) { 2028 defer afterTest(t) 2029 2030 mux := NewServeMux() 2031 mux.Handle("/", HandlerFunc(func(resp ResponseWriter, req *Request) {})) 2032 ts := httptest.NewServer(mux) 2033 defer ts.Close() 2034 2035 // net/http uses HTTP/1.1 for requests, so write requests manually 2036 tests := []struct { 2037 req string // raw http request 2038 expect []string // expected Connection header(s) 2039 }{ 2040 { 2041 req: "GET / HTTP/1.0\r\n\r\n", 2042 expect: nil, 2043 }, 2044 { 2045 req: "OPTIONS * HTTP/1.0\r\n\r\n", 2046 expect: nil, 2047 }, 2048 { 2049 req: "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", 2050 expect: []string{"keep-alive"}, 2051 }, 2052 } 2053 2054 for _, tt := range tests { 2055 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 2056 if err != nil { 2057 t.Fatal("dial err:", err) 2058 } 2059 2060 _, err = fmt.Fprint(conn, tt.req) 2061 if err != nil { 2062 t.Fatal("conn write err:", err) 2063 } 2064 2065 resp, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "GET"}) 2066 if err != nil { 2067 t.Fatal("ReadResponse err:", err) 2068 } 2069 conn.Close() 2070 resp.Body.Close() 2071 2072 got := resp.Header["Connection"] 2073 if !reflect.DeepEqual(got, tt.expect) { 2074 t.Errorf("wrong Connection headers for request %q. Got %q expect %q", tt.req, got, tt.expect) 2075 } 2076 } 2077 } 2078 2079 // See golang.org/issue/5660 2080 func TestServerReaderFromOrder(t *testing.T) { 2081 defer afterTest(t) 2082 pr, pw := io.Pipe() 2083 const size = 3 << 20 2084 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 2085 rw.Header().Set("Content-Type", "text/plain") // prevent sniffing path 2086 done := make(chan bool) 2087 go func() { 2088 io.Copy(rw, pr) 2089 close(done) 2090 }() 2091 time.Sleep(25 * time.Millisecond) // give Copy a chance to break things 2092 n, err := io.Copy(ioutil.Discard, req.Body) 2093 if err != nil { 2094 t.Errorf("handler Copy: %v", err) 2095 return 2096 } 2097 if n != size { 2098 t.Errorf("handler Copy = %d; want %d", n, size) 2099 } 2100 pw.Write([]byte("hi")) 2101 pw.Close() 2102 <-done 2103 })) 2104 defer ts.Close() 2105 2106 req, err := NewRequest("POST", ts.URL, io.LimitReader(neverEnding('a'), size)) 2107 if err != nil { 2108 t.Fatal(err) 2109 } 2110 res, err := DefaultClient.Do(req) 2111 if err != nil { 2112 t.Fatal(err) 2113 } 2114 all, err := ioutil.ReadAll(res.Body) 2115 if err != nil { 2116 t.Fatal(err) 2117 } 2118 res.Body.Close() 2119 if string(all) != "hi" { 2120 t.Errorf("Body = %q; want hi", all) 2121 } 2122 } 2123 2124 // Issue 6157, Issue 6685 2125 func TestCodesPreventingContentTypeAndBody(t *testing.T) { 2126 for _, code := range []int{StatusNotModified, StatusNoContent, StatusContinue} { 2127 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 2128 if r.URL.Path == "/header" { 2129 w.Header().Set("Content-Length", "123") 2130 } 2131 w.WriteHeader(code) 2132 if r.URL.Path == "/more" { 2133 w.Write([]byte("stuff")) 2134 } 2135 })) 2136 for _, req := range []string{ 2137 "GET / HTTP/1.0", 2138 "GET /header HTTP/1.0", 2139 "GET /more HTTP/1.0", 2140 "GET / HTTP/1.1", 2141 "GET /header HTTP/1.1", 2142 "GET /more HTTP/1.1", 2143 } { 2144 got := ht.rawResponse(req) 2145 wantStatus := fmt.Sprintf("%d %s", code, StatusText(code)) 2146 if !strings.Contains(got, wantStatus) { 2147 t.Errorf("Code %d: Wanted %q Modified for %q: %s", code, wantStatus, req, got) 2148 } else if strings.Contains(got, "Content-Length") { 2149 t.Errorf("Code %d: Got a Content-Length from %q: %s", code, req, got) 2150 } else if strings.Contains(got, "stuff") { 2151 t.Errorf("Code %d: Response contains a body from %q: %s", code, req, got) 2152 } 2153 } 2154 } 2155 } 2156 2157 func TestContentTypeOkayOn204(t *testing.T) { 2158 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 2159 w.Header().Set("Content-Length", "123") // suppressed 2160 w.Header().Set("Content-Type", "foo/bar") 2161 w.WriteHeader(204) 2162 })) 2163 got := ht.rawResponse("GET / HTTP/1.1") 2164 if !strings.Contains(got, "Content-Type: foo/bar") { 2165 t.Errorf("Response = %q; want Content-Type: foo/bar", got) 2166 } 2167 if strings.Contains(got, "Content-Length: 123") { 2168 t.Errorf("Response = %q; don't want a Content-Length", got) 2169 } 2170 } 2171 2172 // Issue 6995 2173 // A server Handler can receive a Request, and then turn around and 2174 // give a copy of that Request.Body out to the Transport (e.g. any 2175 // proxy). So then two people own that Request.Body (both the server 2176 // and the http client), and both think they can close it on failure. 2177 // Therefore, all incoming server requests Bodies need to be thread-safe. 2178 func TestTransportAndServerSharedBodyRace(t *testing.T) { 2179 defer afterTest(t) 2180 2181 const bodySize = 1 << 20 2182 2183 unblockBackend := make(chan bool) 2184 backend := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 2185 io.CopyN(rw, req.Body, bodySize/2) 2186 <-unblockBackend 2187 })) 2188 defer backend.Close() 2189 2190 backendRespc := make(chan *Response, 1) 2191 proxy := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 2192 if req.RequestURI == "/foo" { 2193 rw.Write([]byte("bar")) 2194 return 2195 } 2196 req2, _ := NewRequest("POST", backend.URL, req.Body) 2197 req2.ContentLength = bodySize 2198 2199 bresp, err := DefaultClient.Do(req2) 2200 if err != nil { 2201 t.Errorf("Proxy outbound request: %v", err) 2202 return 2203 } 2204 _, err = io.CopyN(ioutil.Discard, bresp.Body, bodySize/4) 2205 if err != nil { 2206 t.Errorf("Proxy copy error: %v", err) 2207 return 2208 } 2209 backendRespc <- bresp // to close later 2210 2211 // Try to cause a race: Both the DefaultTransport and the proxy handler's Server 2212 // will try to read/close req.Body (aka req2.Body) 2213 DefaultTransport.(*Transport).CancelRequest(req2) 2214 rw.Write([]byte("OK")) 2215 })) 2216 defer proxy.Close() 2217 2218 req, _ := NewRequest("POST", proxy.URL, io.LimitReader(neverEnding('a'), bodySize)) 2219 res, err := DefaultClient.Do(req) 2220 if err != nil { 2221 t.Fatalf("Original request: %v", err) 2222 } 2223 2224 // Cleanup, so we don't leak goroutines. 2225 res.Body.Close() 2226 close(unblockBackend) 2227 (<-backendRespc).Body.Close() 2228 } 2229 2230 // Test that a hanging Request.Body.Read from another goroutine can't 2231 // cause the Handler goroutine's Request.Body.Close to block. 2232 func TestRequestBodyCloseDoesntBlock(t *testing.T) { 2233 t.Skipf("Skipping known issue; see golang.org/issue/7121") 2234 if testing.Short() { 2235 t.Skip("skipping in -short mode") 2236 } 2237 defer afterTest(t) 2238 2239 readErrCh := make(chan error, 1) 2240 errCh := make(chan error, 2) 2241 2242 server := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 2243 go func(body io.Reader) { 2244 _, err := body.Read(make([]byte, 100)) 2245 readErrCh <- err 2246 }(req.Body) 2247 time.Sleep(500 * time.Millisecond) 2248 })) 2249 defer server.Close() 2250 2251 closeConn := make(chan bool) 2252 defer close(closeConn) 2253 go func() { 2254 conn, err := net.Dial("tcp", server.Listener.Addr().String()) 2255 if err != nil { 2256 errCh <- err 2257 return 2258 } 2259 defer conn.Close() 2260 _, err = conn.Write([]byte("POST / HTTP/1.1\r\nConnection: close\r\nHost: foo\r\nContent-Length: 100000\r\n\r\n")) 2261 if err != nil { 2262 errCh <- err 2263 return 2264 } 2265 // And now just block, making the server block on our 2266 // 100000 bytes of body that will never arrive. 2267 <-closeConn 2268 }() 2269 select { 2270 case err := <-readErrCh: 2271 if err == nil { 2272 t.Error("Read was nil. Expected error.") 2273 } 2274 case err := <-errCh: 2275 t.Error(err) 2276 case <-time.After(5 * time.Second): 2277 t.Error("timeout") 2278 } 2279 } 2280 2281 func TestResponseWriterWriteStringAllocs(t *testing.T) { 2282 ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) { 2283 if r.URL.Path == "/s" { 2284 io.WriteString(w, "Hello world") 2285 } else { 2286 w.Write([]byte("Hello world")) 2287 } 2288 })) 2289 before := testing.AllocsPerRun(50, func() { ht.rawResponse("GET / HTTP/1.0") }) 2290 after := testing.AllocsPerRun(50, func() { ht.rawResponse("GET /s HTTP/1.0") }) 2291 if int(after) >= int(before) { 2292 t.Errorf("WriteString allocs of %v >= Write allocs of %v", after, before) 2293 } 2294 } 2295 2296 func TestAppendTime(t *testing.T) { 2297 var b [len(TimeFormat)]byte 2298 t1 := time.Date(2013, 9, 21, 15, 41, 0, 0, time.FixedZone("CEST", 2*60*60)) 2299 res := ExportAppendTime(b[:0], t1) 2300 t2, err := ParseTime(string(res)) 2301 if err != nil { 2302 t.Fatalf("Error parsing time: %s", err) 2303 } 2304 if !t1.Equal(t2) { 2305 t.Fatalf("Times differ; expected: %v, got %v (%s)", t1, t2, string(res)) 2306 } 2307 } 2308 2309 func TestServerConnState(t *testing.T) { 2310 defer afterTest(t) 2311 handler := map[string]func(w ResponseWriter, r *Request){ 2312 "/": func(w ResponseWriter, r *Request) { 2313 fmt.Fprintf(w, "Hello.") 2314 }, 2315 "/close": func(w ResponseWriter, r *Request) { 2316 w.Header().Set("Connection", "close") 2317 fmt.Fprintf(w, "Hello.") 2318 }, 2319 "/hijack": func(w ResponseWriter, r *Request) { 2320 c, _, _ := w.(Hijacker).Hijack() 2321 c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello.")) 2322 c.Close() 2323 }, 2324 "/hijack-panic": func(w ResponseWriter, r *Request) { 2325 c, _, _ := w.(Hijacker).Hijack() 2326 c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello.")) 2327 c.Close() 2328 panic("intentional panic") 2329 }, 2330 } 2331 ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) { 2332 handler[r.URL.Path](w, r) 2333 })) 2334 defer ts.Close() 2335 2336 var mu sync.Mutex // guard stateLog and connID 2337 var stateLog = map[int][]ConnState{} 2338 var connID = map[net.Conn]int{} 2339 2340 ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0) 2341 ts.Config.ConnState = func(c net.Conn, state ConnState) { 2342 if c == nil { 2343 t.Errorf("nil conn seen in state %s", state) 2344 return 2345 } 2346 mu.Lock() 2347 defer mu.Unlock() 2348 id, ok := connID[c] 2349 if !ok { 2350 id = len(connID) + 1 2351 connID[c] = id 2352 } 2353 stateLog[id] = append(stateLog[id], state) 2354 } 2355 ts.Start() 2356 2357 mustGet(t, ts.URL+"/") 2358 mustGet(t, ts.URL+"/close") 2359 2360 mustGet(t, ts.URL+"/") 2361 mustGet(t, ts.URL+"/", "Connection", "close") 2362 2363 mustGet(t, ts.URL+"/hijack") 2364 mustGet(t, ts.URL+"/hijack-panic") 2365 2366 // New->Closed 2367 { 2368 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 2369 if err != nil { 2370 t.Fatal(err) 2371 } 2372 c.Close() 2373 } 2374 2375 // New->Active->Closed 2376 { 2377 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 2378 if err != nil { 2379 t.Fatal(err) 2380 } 2381 if _, err := io.WriteString(c, "BOGUS REQUEST\r\n\r\n"); err != nil { 2382 t.Fatal(err) 2383 } 2384 c.Close() 2385 } 2386 2387 // New->Idle->Closed 2388 { 2389 c, err := net.Dial("tcp", ts.Listener.Addr().String()) 2390 if err != nil { 2391 t.Fatal(err) 2392 } 2393 if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil { 2394 t.Fatal(err) 2395 } 2396 res, err := ReadResponse(bufio.NewReader(c), nil) 2397 if err != nil { 2398 t.Fatal(err) 2399 } 2400 if _, err := io.Copy(ioutil.Discard, res.Body); err != nil { 2401 t.Fatal(err) 2402 } 2403 c.Close() 2404 } 2405 2406 want := map[int][]ConnState{ 2407 1: []ConnState{StateNew, StateActive, StateIdle, StateActive, StateClosed}, 2408 2: []ConnState{StateNew, StateActive, StateIdle, StateActive, StateClosed}, 2409 3: []ConnState{StateNew, StateActive, StateHijacked}, 2410 4: []ConnState{StateNew, StateActive, StateHijacked}, 2411 5: []ConnState{StateNew, StateClosed}, 2412 6: []ConnState{StateNew, StateActive, StateClosed}, 2413 7: []ConnState{StateNew, StateActive, StateIdle, StateClosed}, 2414 } 2415 logString := func(m map[int][]ConnState) string { 2416 var b bytes.Buffer 2417 for id, l := range m { 2418 fmt.Fprintf(&b, "Conn %d: ", id) 2419 for _, s := range l { 2420 fmt.Fprintf(&b, "%s ", s) 2421 } 2422 b.WriteString("\n") 2423 } 2424 return b.String() 2425 } 2426 2427 for i := 0; i < 5; i++ { 2428 time.Sleep(time.Duration(i) * 50 * time.Millisecond) 2429 mu.Lock() 2430 match := reflect.DeepEqual(stateLog, want) 2431 mu.Unlock() 2432 if match { 2433 return 2434 } 2435 } 2436 2437 mu.Lock() 2438 t.Errorf("Unexpected events.\nGot log: %s\n Want: %s\n", logString(stateLog), logString(want)) 2439 mu.Unlock() 2440 } 2441 2442 func mustGet(t *testing.T, url string, headers ...string) { 2443 req, err := NewRequest("GET", url, nil) 2444 if err != nil { 2445 t.Fatal(err) 2446 } 2447 for len(headers) > 0 { 2448 req.Header.Add(headers[0], headers[1]) 2449 headers = headers[2:] 2450 } 2451 res, err := DefaultClient.Do(req) 2452 if err != nil { 2453 t.Errorf("Error fetching %s: %v", url, err) 2454 return 2455 } 2456 _, err = ioutil.ReadAll(res.Body) 2457 defer res.Body.Close() 2458 if err != nil { 2459 t.Errorf("Error reading %s: %v", url, err) 2460 } 2461 } 2462 2463 func TestServerKeepAlivesEnabled(t *testing.T) { 2464 defer afterTest(t) 2465 ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 2466 ts.Config.SetKeepAlivesEnabled(false) 2467 ts.Start() 2468 defer ts.Close() 2469 res, err := Get(ts.URL) 2470 if err != nil { 2471 t.Fatal(err) 2472 } 2473 defer res.Body.Close() 2474 if !res.Close { 2475 t.Errorf("Body.Close == false; want true") 2476 } 2477 } 2478 2479 // golang.org/issue/7856 2480 func TestServerEmptyBodyRace(t *testing.T) { 2481 defer afterTest(t) 2482 var n int32 2483 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 2484 atomic.AddInt32(&n, 1) 2485 })) 2486 defer ts.Close() 2487 var wg sync.WaitGroup 2488 const reqs = 20 2489 for i := 0; i < reqs; i++ { 2490 wg.Add(1) 2491 go func() { 2492 defer wg.Done() 2493 res, err := Get(ts.URL) 2494 if err != nil { 2495 t.Error(err) 2496 return 2497 } 2498 defer res.Body.Close() 2499 _, err = io.Copy(ioutil.Discard, res.Body) 2500 if err != nil { 2501 t.Error(err) 2502 return 2503 } 2504 }() 2505 } 2506 wg.Wait() 2507 if got := atomic.LoadInt32(&n); got != reqs { 2508 t.Errorf("handler ran %d times; want %d", got, reqs) 2509 } 2510 } 2511 2512 func TestServerConnStateNew(t *testing.T) { 2513 sawNew := false // if the test is buggy, we'll race on this variable. 2514 srv := &Server{ 2515 ConnState: func(c net.Conn, state ConnState) { 2516 if state == StateNew { 2517 sawNew = true // testing that this write isn't racy 2518 } 2519 }, 2520 Handler: HandlerFunc(func(w ResponseWriter, r *Request) {}), // irrelevant 2521 } 2522 srv.Serve(&oneConnListener{ 2523 conn: &rwTestConn{ 2524 Reader: strings.NewReader("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"), 2525 Writer: ioutil.Discard, 2526 }, 2527 }) 2528 if !sawNew { // testing that this read isn't racy 2529 t.Error("StateNew not seen") 2530 } 2531 } 2532 2533 func BenchmarkClientServer(b *testing.B) { 2534 b.ReportAllocs() 2535 b.StopTimer() 2536 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 2537 fmt.Fprintf(rw, "Hello world.\n") 2538 })) 2539 defer ts.Close() 2540 b.StartTimer() 2541 2542 for i := 0; i < b.N; i++ { 2543 res, err := Get(ts.URL) 2544 if err != nil { 2545 b.Fatal("Get:", err) 2546 } 2547 all, err := ioutil.ReadAll(res.Body) 2548 res.Body.Close() 2549 if err != nil { 2550 b.Fatal("ReadAll:", err) 2551 } 2552 body := string(all) 2553 if body != "Hello world.\n" { 2554 b.Fatal("Got body:", body) 2555 } 2556 } 2557 2558 b.StopTimer() 2559 } 2560 2561 func BenchmarkClientServerParallel4(b *testing.B) { 2562 benchmarkClientServerParallel(b, 4) 2563 } 2564 2565 func BenchmarkClientServerParallel64(b *testing.B) { 2566 benchmarkClientServerParallel(b, 64) 2567 } 2568 2569 func benchmarkClientServerParallel(b *testing.B, parallelism int) { 2570 b.ReportAllocs() 2571 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 2572 fmt.Fprintf(rw, "Hello world.\n") 2573 })) 2574 defer ts.Close() 2575 b.ResetTimer() 2576 b.SetParallelism(parallelism) 2577 b.RunParallel(func(pb *testing.PB) { 2578 for pb.Next() { 2579 res, err := Get(ts.URL) 2580 if err != nil { 2581 b.Logf("Get: %v", err) 2582 continue 2583 } 2584 all, err := ioutil.ReadAll(res.Body) 2585 res.Body.Close() 2586 if err != nil { 2587 b.Logf("ReadAll: %v", err) 2588 continue 2589 } 2590 body := string(all) 2591 if body != "Hello world.\n" { 2592 panic("Got body: " + body) 2593 } 2594 } 2595 }) 2596 } 2597 2598 // A benchmark for profiling the server without the HTTP client code. 2599 // The client code runs in a subprocess. 2600 // 2601 // For use like: 2602 // $ go test -c 2603 // $ ./http.test -test.run=XX -test.bench=BenchmarkServer -test.benchtime=15s -test.cpuprofile=http.prof 2604 // $ go tool pprof http.test http.prof 2605 // (pprof) web 2606 func BenchmarkServer(b *testing.B) { 2607 b.ReportAllocs() 2608 // Child process mode; 2609 if url := os.Getenv("TEST_BENCH_SERVER_URL"); url != "" { 2610 n, err := strconv.Atoi(os.Getenv("TEST_BENCH_CLIENT_N")) 2611 if err != nil { 2612 panic(err) 2613 } 2614 for i := 0; i < n; i++ { 2615 res, err := Get(url) 2616 if err != nil { 2617 log.Panicf("Get: %v", err) 2618 } 2619 all, err := ioutil.ReadAll(res.Body) 2620 res.Body.Close() 2621 if err != nil { 2622 log.Panicf("ReadAll: %v", err) 2623 } 2624 body := string(all) 2625 if body != "Hello world.\n" { 2626 log.Panicf("Got body: %q", body) 2627 } 2628 } 2629 os.Exit(0) 2630 return 2631 } 2632 2633 var res = []byte("Hello world.\n") 2634 b.StopTimer() 2635 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 2636 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 2637 rw.Write(res) 2638 })) 2639 defer ts.Close() 2640 b.StartTimer() 2641 2642 cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkServer") 2643 cmd.Env = append([]string{ 2644 fmt.Sprintf("TEST_BENCH_CLIENT_N=%d", b.N), 2645 fmt.Sprintf("TEST_BENCH_SERVER_URL=%s", ts.URL), 2646 }, os.Environ()...) 2647 out, err := cmd.CombinedOutput() 2648 if err != nil { 2649 b.Errorf("Test failure: %v, with output: %s", err, out) 2650 } 2651 } 2652 2653 func BenchmarkServerFakeConnNoKeepAlive(b *testing.B) { 2654 b.ReportAllocs() 2655 req := reqBytes(`GET / HTTP/1.0 2656 Host: golang.org 2657 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 2658 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 2659 Accept-Encoding: gzip,deflate,sdch 2660 Accept-Language: en-US,en;q=0.8 2661 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 2662 `) 2663 res := []byte("Hello world!\n") 2664 2665 conn := &testConn{ 2666 // testConn.Close will not push into the channel 2667 // if it's full. 2668 closec: make(chan bool, 1), 2669 } 2670 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 2671 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 2672 rw.Write(res) 2673 }) 2674 ln := new(oneConnListener) 2675 for i := 0; i < b.N; i++ { 2676 conn.readBuf.Reset() 2677 conn.writeBuf.Reset() 2678 conn.readBuf.Write(req) 2679 ln.conn = conn 2680 Serve(ln, handler) 2681 <-conn.closec 2682 } 2683 } 2684 2685 // repeatReader reads content count times, then EOFs. 2686 type repeatReader struct { 2687 content []byte 2688 count int 2689 off int 2690 } 2691 2692 func (r *repeatReader) Read(p []byte) (n int, err error) { 2693 if r.count <= 0 { 2694 return 0, io.EOF 2695 } 2696 n = copy(p, r.content[r.off:]) 2697 r.off += n 2698 if r.off == len(r.content) { 2699 r.count-- 2700 r.off = 0 2701 } 2702 return 2703 } 2704 2705 func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) { 2706 b.ReportAllocs() 2707 2708 req := reqBytes(`GET / HTTP/1.1 2709 Host: golang.org 2710 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 2711 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 2712 Accept-Encoding: gzip,deflate,sdch 2713 Accept-Language: en-US,en;q=0.8 2714 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 2715 `) 2716 res := []byte("Hello world!\n") 2717 2718 conn := &rwTestConn{ 2719 Reader: &repeatReader{content: req, count: b.N}, 2720 Writer: ioutil.Discard, 2721 closec: make(chan bool, 1), 2722 } 2723 handled := 0 2724 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 2725 handled++ 2726 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 2727 rw.Write(res) 2728 }) 2729 ln := &oneConnListener{conn: conn} 2730 go Serve(ln, handler) 2731 <-conn.closec 2732 if b.N != handled { 2733 b.Errorf("b.N=%d but handled %d", b.N, handled) 2734 } 2735 } 2736 2737 // same as above, but representing the most simple possible request 2738 // and handler. Notably: the handler does not call rw.Header(). 2739 func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) { 2740 b.ReportAllocs() 2741 2742 req := reqBytes(`GET / HTTP/1.1 2743 Host: golang.org 2744 `) 2745 res := []byte("Hello world!\n") 2746 2747 conn := &rwTestConn{ 2748 Reader: &repeatReader{content: req, count: b.N}, 2749 Writer: ioutil.Discard, 2750 closec: make(chan bool, 1), 2751 } 2752 handled := 0 2753 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 2754 handled++ 2755 rw.Write(res) 2756 }) 2757 ln := &oneConnListener{conn: conn} 2758 go Serve(ln, handler) 2759 <-conn.closec 2760 if b.N != handled { 2761 b.Errorf("b.N=%d but handled %d", b.N, handled) 2762 } 2763 } 2764 2765 const someResponse = "<html>some response</html>" 2766 2767 // A Response that's just no bigger than 2KB, the buffer-before-chunking threshold. 2768 var response = bytes.Repeat([]byte(someResponse), 2<<10/len(someResponse)) 2769 2770 // Both Content-Type and Content-Length set. Should be no buffering. 2771 func BenchmarkServerHandlerTypeLen(b *testing.B) { 2772 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 2773 w.Header().Set("Content-Type", "text/html") 2774 w.Header().Set("Content-Length", strconv.Itoa(len(response))) 2775 w.Write(response) 2776 })) 2777 } 2778 2779 // A Content-Type is set, but no length. No sniffing, but will count the Content-Length. 2780 func BenchmarkServerHandlerNoLen(b *testing.B) { 2781 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 2782 w.Header().Set("Content-Type", "text/html") 2783 w.Write(response) 2784 })) 2785 } 2786 2787 // A Content-Length is set, but the Content-Type will be sniffed. 2788 func BenchmarkServerHandlerNoType(b *testing.B) { 2789 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 2790 w.Header().Set("Content-Length", strconv.Itoa(len(response))) 2791 w.Write(response) 2792 })) 2793 } 2794 2795 // Neither a Content-Type or Content-Length, so sniffed and counted. 2796 func BenchmarkServerHandlerNoHeader(b *testing.B) { 2797 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 2798 w.Write(response) 2799 })) 2800 } 2801 2802 func benchmarkHandler(b *testing.B, h Handler) { 2803 b.ReportAllocs() 2804 req := reqBytes(`GET / HTTP/1.1 2805 Host: golang.org 2806 `) 2807 conn := &rwTestConn{ 2808 Reader: &repeatReader{content: req, count: b.N}, 2809 Writer: ioutil.Discard, 2810 closec: make(chan bool, 1), 2811 } 2812 handled := 0 2813 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 2814 handled++ 2815 h.ServeHTTP(rw, r) 2816 }) 2817 ln := &oneConnListener{conn: conn} 2818 go Serve(ln, handler) 2819 <-conn.closec 2820 if b.N != handled { 2821 b.Errorf("b.N=%d but handled %d", b.N, handled) 2822 } 2823 } 2824 2825 func BenchmarkServerHijack(b *testing.B) { 2826 b.ReportAllocs() 2827 req := reqBytes(`GET / HTTP/1.1 2828 Host: golang.org 2829 `) 2830 h := HandlerFunc(func(w ResponseWriter, r *Request) { 2831 conn, _, err := w.(Hijacker).Hijack() 2832 if err != nil { 2833 panic(err) 2834 } 2835 conn.Close() 2836 }) 2837 conn := &rwTestConn{ 2838 Writer: ioutil.Discard, 2839 closec: make(chan bool, 1), 2840 } 2841 ln := &oneConnListener{conn: conn} 2842 for i := 0; i < b.N; i++ { 2843 conn.Reader = bytes.NewReader(req) 2844 ln.conn = conn 2845 Serve(ln, h) 2846 <-conn.closec 2847 } 2848 }