github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/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 func TestConsumingBodyOnNextConn(t *testing.T) { 120 conn := new(testConn) 121 for i := 0; i < 2; i++ { 122 conn.readBuf.Write([]byte( 123 "POST / HTTP/1.1\r\n" + 124 "Host: test\r\n" + 125 "Content-Length: 11\r\n" + 126 "\r\n" + 127 "foo=1&bar=1")) 128 } 129 130 reqNum := 0 131 ch := make(chan *Request) 132 servech := make(chan error) 133 listener := &oneConnListener{conn} 134 handler := func(res ResponseWriter, req *Request) { 135 reqNum++ 136 ch <- req 137 } 138 139 go func() { 140 servech <- Serve(listener, HandlerFunc(handler)) 141 }() 142 143 var req *Request 144 req = <-ch 145 if req == nil { 146 t.Fatal("Got nil first request.") 147 } 148 if req.Method != "POST" { 149 t.Errorf("For request #1's method, got %q; expected %q", 150 req.Method, "POST") 151 } 152 153 req = <-ch 154 if req == nil { 155 t.Fatal("Got nil first request.") 156 } 157 if req.Method != "POST" { 158 t.Errorf("For request #2's method, got %q; expected %q", 159 req.Method, "POST") 160 } 161 162 if serveerr := <-servech; serveerr != io.EOF { 163 t.Errorf("Serve returned %q; expected EOF", serveerr) 164 } 165 } 166 167 type stringHandler string 168 169 func (s stringHandler) ServeHTTP(w ResponseWriter, r *Request) { 170 w.Header().Set("Result", string(s)) 171 } 172 173 var handlers = []struct { 174 pattern string 175 msg string 176 }{ 177 {"/", "Default"}, 178 {"/someDir/", "someDir"}, 179 {"someHost.com/someDir/", "someHost.com/someDir"}, 180 } 181 182 var vtests = []struct { 183 url string 184 expected string 185 }{ 186 {"http://localhost/someDir/apage", "someDir"}, 187 {"http://localhost/otherDir/apage", "Default"}, 188 {"http://someHost.com/someDir/apage", "someHost.com/someDir"}, 189 {"http://otherHost.com/someDir/apage", "someDir"}, 190 {"http://otherHost.com/aDir/apage", "Default"}, 191 // redirections for trees 192 {"http://localhost/someDir", "/someDir/"}, 193 {"http://someHost.com/someDir", "/someDir/"}, 194 } 195 196 func TestHostHandlers(t *testing.T) { 197 defer afterTest(t) 198 mux := NewServeMux() 199 for _, h := range handlers { 200 mux.Handle(h.pattern, stringHandler(h.msg)) 201 } 202 ts := httptest.NewServer(mux) 203 defer ts.Close() 204 205 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 206 if err != nil { 207 t.Fatal(err) 208 } 209 defer conn.Close() 210 cc := httputil.NewClientConn(conn, nil) 211 for _, vt := range vtests { 212 var r *Response 213 var req Request 214 if req.URL, err = url.Parse(vt.url); err != nil { 215 t.Errorf("cannot parse url: %v", err) 216 continue 217 } 218 if err := cc.Write(&req); err != nil { 219 t.Errorf("writing request: %v", err) 220 continue 221 } 222 r, err := cc.Read(&req) 223 if err != nil { 224 t.Errorf("reading response: %v", err) 225 continue 226 } 227 switch r.StatusCode { 228 case StatusOK: 229 s := r.Header.Get("Result") 230 if s != vt.expected { 231 t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) 232 } 233 case StatusMovedPermanently: 234 s := r.Header.Get("Location") 235 if s != vt.expected { 236 t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected) 237 } 238 default: 239 t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode) 240 } 241 } 242 } 243 244 // Tests for http://code.google.com/p/go/issues/detail?id=900 245 func TestMuxRedirectLeadingSlashes(t *testing.T) { 246 paths := []string{"//foo.txt", "///foo.txt", "/../../foo.txt"} 247 for _, path := range paths { 248 req, err := ReadRequest(bufio.NewReader(bytes.NewBufferString("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n"))) 249 if err != nil { 250 t.Errorf("%s", err) 251 } 252 mux := NewServeMux() 253 resp := httptest.NewRecorder() 254 255 mux.ServeHTTP(resp, req) 256 257 if loc, expected := resp.Header().Get("Location"), "/foo.txt"; loc != expected { 258 t.Errorf("Expected Location header set to %q; got %q", expected, loc) 259 return 260 } 261 262 if code, expected := resp.Code, StatusMovedPermanently; code != expected { 263 t.Errorf("Expected response code of StatusMovedPermanently; got %d", code) 264 return 265 } 266 } 267 } 268 269 func TestServerTimeouts(t *testing.T) { 270 defer afterTest(t) 271 reqNum := 0 272 ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) { 273 reqNum++ 274 fmt.Fprintf(res, "req=%d", reqNum) 275 })) 276 ts.Config.ReadTimeout = 250 * time.Millisecond 277 ts.Config.WriteTimeout = 250 * time.Millisecond 278 ts.Start() 279 defer ts.Close() 280 281 // Hit the HTTP server successfully. 282 tr := &Transport{DisableKeepAlives: true} // they interfere with this test 283 defer tr.CloseIdleConnections() 284 c := &Client{Transport: tr} 285 r, err := c.Get(ts.URL) 286 if err != nil { 287 t.Fatalf("http Get #1: %v", err) 288 } 289 got, _ := ioutil.ReadAll(r.Body) 290 expected := "req=1" 291 if string(got) != expected { 292 t.Errorf("Unexpected response for request #1; got %q; expected %q", 293 string(got), expected) 294 } 295 296 // Slow client that should timeout. 297 t1 := time.Now() 298 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 299 if err != nil { 300 t.Fatalf("Dial: %v", err) 301 } 302 buf := make([]byte, 1) 303 n, err := conn.Read(buf) 304 latency := time.Since(t1) 305 if n != 0 || err != io.EOF { 306 t.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF) 307 } 308 if latency < 200*time.Millisecond /* fudge from 250 ms above */ { 309 t.Errorf("got EOF after %s, want >= %s", latency, 200*time.Millisecond) 310 } 311 312 // Hit the HTTP server successfully again, verifying that the 313 // previous slow connection didn't run our handler. (that we 314 // get "req=2", not "req=3") 315 r, err = Get(ts.URL) 316 if err != nil { 317 t.Fatalf("http Get #2: %v", err) 318 } 319 got, _ = ioutil.ReadAll(r.Body) 320 expected = "req=2" 321 if string(got) != expected { 322 t.Errorf("Get #2 got %q, want %q", string(got), expected) 323 } 324 325 if !testing.Short() { 326 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 327 if err != nil { 328 t.Fatalf("Dial: %v", err) 329 } 330 defer conn.Close() 331 go io.Copy(ioutil.Discard, conn) 332 for i := 0; i < 5; i++ { 333 _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n")) 334 if err != nil { 335 t.Fatalf("on write %d: %v", i, err) 336 } 337 time.Sleep(ts.Config.ReadTimeout / 2) 338 } 339 } 340 } 341 342 // golang.org/issue/4741 -- setting only a write timeout that triggers 343 // shouldn't cause a handler to block forever on reads (next HTTP 344 // request) that will never happen. 345 func TestOnlyWriteTimeout(t *testing.T) { 346 defer afterTest(t) 347 var conn net.Conn 348 var afterTimeoutErrc = make(chan error, 1) 349 ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, req *Request) { 350 buf := make([]byte, 512<<10) 351 _, err := w.Write(buf) 352 if err != nil { 353 t.Errorf("handler Write error: %v", err) 354 return 355 } 356 conn.SetWriteDeadline(time.Now().Add(-30 * time.Second)) 357 _, err = w.Write(buf) 358 afterTimeoutErrc <- err 359 })) 360 ts.Listener = trackLastConnListener{ts.Listener, &conn} 361 ts.Start() 362 defer ts.Close() 363 364 tr := &Transport{DisableKeepAlives: false} 365 defer tr.CloseIdleConnections() 366 c := &Client{Transport: tr} 367 368 errc := make(chan error) 369 go func() { 370 res, err := c.Get(ts.URL) 371 if err != nil { 372 errc <- err 373 return 374 } 375 _, err = io.Copy(ioutil.Discard, res.Body) 376 errc <- err 377 }() 378 select { 379 case err := <-errc: 380 if err == nil { 381 t.Errorf("expected an error from Get request") 382 } 383 case <-time.After(5 * time.Second): 384 t.Fatal("timeout waiting for Get error") 385 } 386 if err := <-afterTimeoutErrc; err == nil { 387 t.Error("expected write error after timeout") 388 } 389 } 390 391 // trackLastConnListener tracks the last net.Conn that was accepted. 392 type trackLastConnListener struct { 393 net.Listener 394 last *net.Conn // destination 395 } 396 397 func (l trackLastConnListener) Accept() (c net.Conn, err error) { 398 c, err = l.Listener.Accept() 399 *l.last = c 400 return 401 } 402 403 // TestIdentityResponse verifies that a handler can unset 404 func TestIdentityResponse(t *testing.T) { 405 defer afterTest(t) 406 handler := HandlerFunc(func(rw ResponseWriter, req *Request) { 407 rw.Header().Set("Content-Length", "3") 408 rw.Header().Set("Transfer-Encoding", req.FormValue("te")) 409 switch { 410 case req.FormValue("overwrite") == "1": 411 _, err := rw.Write([]byte("foo TOO LONG")) 412 if err != ErrContentLength { 413 t.Errorf("expected ErrContentLength; got %v", err) 414 } 415 case req.FormValue("underwrite") == "1": 416 rw.Header().Set("Content-Length", "500") 417 rw.Write([]byte("too short")) 418 default: 419 rw.Write([]byte("foo")) 420 } 421 }) 422 423 ts := httptest.NewServer(handler) 424 defer ts.Close() 425 426 // Note: this relies on the assumption (which is true) that 427 // Get sends HTTP/1.1 or greater requests. Otherwise the 428 // server wouldn't have the choice to send back chunked 429 // responses. 430 for _, te := range []string{"", "identity"} { 431 url := ts.URL + "/?te=" + te 432 res, err := Get(url) 433 if err != nil { 434 t.Fatalf("error with Get of %s: %v", url, err) 435 } 436 if cl, expected := res.ContentLength, int64(3); cl != expected { 437 t.Errorf("for %s expected res.ContentLength of %d; got %d", url, expected, cl) 438 } 439 if cl, expected := res.Header.Get("Content-Length"), "3"; cl != expected { 440 t.Errorf("for %s expected Content-Length header of %q; got %q", url, expected, cl) 441 } 442 if tl, expected := len(res.TransferEncoding), 0; tl != expected { 443 t.Errorf("for %s expected len(res.TransferEncoding) of %d; got %d (%v)", 444 url, expected, tl, res.TransferEncoding) 445 } 446 res.Body.Close() 447 } 448 449 // Verify that ErrContentLength is returned 450 url := ts.URL + "/?overwrite=1" 451 res, err := Get(url) 452 if err != nil { 453 t.Fatalf("error with Get of %s: %v", url, err) 454 } 455 res.Body.Close() 456 457 // Verify that the connection is closed when the declared Content-Length 458 // is larger than what the handler wrote. 459 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 460 if err != nil { 461 t.Fatalf("error dialing: %v", err) 462 } 463 _, err = conn.Write([]byte("GET /?underwrite=1 HTTP/1.1\r\nHost: foo\r\n\r\n")) 464 if err != nil { 465 t.Fatalf("error writing: %v", err) 466 } 467 468 // The ReadAll will hang for a failing test, so use a Timer to 469 // fail explicitly. 470 goTimeout(t, 2*time.Second, func() { 471 got, _ := ioutil.ReadAll(conn) 472 expectedSuffix := "\r\n\r\ntoo short" 473 if !strings.HasSuffix(string(got), expectedSuffix) { 474 t.Errorf("Expected output to end with %q; got response body %q", 475 expectedSuffix, string(got)) 476 } 477 }) 478 } 479 480 func testTCPConnectionCloses(t *testing.T, req string, h Handler) { 481 defer afterTest(t) 482 s := httptest.NewServer(h) 483 defer s.Close() 484 485 conn, err := net.Dial("tcp", s.Listener.Addr().String()) 486 if err != nil { 487 t.Fatal("dial error:", err) 488 } 489 defer conn.Close() 490 491 _, err = fmt.Fprint(conn, req) 492 if err != nil { 493 t.Fatal("print error:", err) 494 } 495 496 r := bufio.NewReader(conn) 497 res, err := ReadResponse(r, &Request{Method: "GET"}) 498 if err != nil { 499 t.Fatal("ReadResponse error:", err) 500 } 501 502 didReadAll := make(chan bool, 1) 503 go func() { 504 select { 505 case <-time.After(5 * time.Second): 506 t.Error("body not closed after 5s") 507 return 508 case <-didReadAll: 509 } 510 }() 511 512 _, err = ioutil.ReadAll(r) 513 if err != nil { 514 t.Fatal("read error:", err) 515 } 516 didReadAll <- true 517 518 if !res.Close { 519 t.Errorf("Response.Close = false; want true") 520 } 521 } 522 523 // TestServeHTTP10Close verifies that HTTP/1.0 requests won't be kept alive. 524 func TestServeHTTP10Close(t *testing.T) { 525 testTCPConnectionCloses(t, "GET / HTTP/1.0\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 526 ServeFile(w, r, "testdata/file") 527 })) 528 } 529 530 // TestClientCanClose verifies that clients can also force a connection to close. 531 func TestClientCanClose(t *testing.T) { 532 testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nConnection: close\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 533 // Nothing. 534 })) 535 } 536 537 // TestHandlersCanSetConnectionClose verifies that handlers can force a connection to close, 538 // even for HTTP/1.1 requests. 539 func TestHandlersCanSetConnectionClose11(t *testing.T) { 540 testTCPConnectionCloses(t, "GET / HTTP/1.1\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 541 w.Header().Set("Connection", "close") 542 })) 543 } 544 545 func TestHandlersCanSetConnectionClose10(t *testing.T) { 546 testTCPConnectionCloses(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) { 547 w.Header().Set("Connection", "close") 548 })) 549 } 550 551 func TestSetsRemoteAddr(t *testing.T) { 552 defer afterTest(t) 553 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 554 fmt.Fprintf(w, "%s", r.RemoteAddr) 555 })) 556 defer ts.Close() 557 558 res, err := Get(ts.URL) 559 if err != nil { 560 t.Fatalf("Get error: %v", err) 561 } 562 body, err := ioutil.ReadAll(res.Body) 563 if err != nil { 564 t.Fatalf("ReadAll error: %v", err) 565 } 566 ip := string(body) 567 if !strings.HasPrefix(ip, "127.0.0.1:") && !strings.HasPrefix(ip, "[::1]:") { 568 t.Fatalf("Expected local addr; got %q", ip) 569 } 570 } 571 572 func TestChunkedResponseHeaders(t *testing.T) { 573 defer afterTest(t) 574 log.SetOutput(ioutil.Discard) // is noisy otherwise 575 defer log.SetOutput(os.Stderr) 576 577 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 578 w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted 579 w.(Flusher).Flush() 580 fmt.Fprintf(w, "I am a chunked response.") 581 })) 582 defer ts.Close() 583 584 res, err := Get(ts.URL) 585 if err != nil { 586 t.Fatalf("Get error: %v", err) 587 } 588 defer res.Body.Close() 589 if g, e := res.ContentLength, int64(-1); g != e { 590 t.Errorf("expected ContentLength of %d; got %d", e, g) 591 } 592 if g, e := res.TransferEncoding, []string{"chunked"}; !reflect.DeepEqual(g, e) { 593 t.Errorf("expected TransferEncoding of %v; got %v", e, g) 594 } 595 if _, haveCL := res.Header["Content-Length"]; haveCL { 596 t.Errorf("Unexpected Content-Length") 597 } 598 } 599 600 // Test304Responses verifies that 304s don't declare that they're 601 // chunking in their response headers and aren't allowed to produce 602 // output. 603 func Test304Responses(t *testing.T) { 604 defer afterTest(t) 605 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 606 w.WriteHeader(StatusNotModified) 607 _, err := w.Write([]byte("illegal body")) 608 if err != ErrBodyNotAllowed { 609 t.Errorf("on Write, expected ErrBodyNotAllowed, got %v", err) 610 } 611 })) 612 defer ts.Close() 613 res, err := Get(ts.URL) 614 if err != nil { 615 t.Error(err) 616 } 617 if len(res.TransferEncoding) > 0 { 618 t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding) 619 } 620 body, err := ioutil.ReadAll(res.Body) 621 if err != nil { 622 t.Error(err) 623 } 624 if len(body) > 0 { 625 t.Errorf("got unexpected body %q", string(body)) 626 } 627 } 628 629 // TestHeadResponses verifies that responses to HEAD requests don't 630 // declare that they're chunking in their response headers, aren't 631 // allowed to produce output, and don't set a Content-Type since 632 // the real type of the body data cannot be inferred. 633 func TestHeadResponses(t *testing.T) { 634 defer afterTest(t) 635 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 636 _, err := w.Write([]byte("Ignored body")) 637 if err != ErrBodyNotAllowed { 638 t.Errorf("on Write, expected ErrBodyNotAllowed, got %v", err) 639 } 640 641 // Also exercise the ReaderFrom path 642 _, err = io.Copy(w, strings.NewReader("Ignored body")) 643 if err != ErrBodyNotAllowed { 644 t.Errorf("on Copy, expected ErrBodyNotAllowed, got %v", err) 645 } 646 })) 647 defer ts.Close() 648 res, err := Head(ts.URL) 649 if err != nil { 650 t.Error(err) 651 } 652 if len(res.TransferEncoding) > 0 { 653 t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding) 654 } 655 ct := res.Header.Get("Content-Type") 656 if ct != "" { 657 t.Errorf("expected no Content-Type; got %s", ct) 658 } 659 body, err := ioutil.ReadAll(res.Body) 660 if err != nil { 661 t.Error(err) 662 } 663 if len(body) > 0 { 664 t.Errorf("got unexpected body %q", string(body)) 665 } 666 } 667 668 func TestTLSHandshakeTimeout(t *testing.T) { 669 defer afterTest(t) 670 ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 671 ts.Config.ReadTimeout = 250 * time.Millisecond 672 ts.StartTLS() 673 defer ts.Close() 674 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 675 if err != nil { 676 t.Fatalf("Dial: %v", err) 677 } 678 defer conn.Close() 679 goTimeout(t, 10*time.Second, func() { 680 var buf [1]byte 681 n, err := conn.Read(buf[:]) 682 if err == nil || n != 0 { 683 t.Errorf("Read = %d, %v; want an error and no bytes", n, err) 684 } 685 }) 686 } 687 688 func TestTLSServer(t *testing.T) { 689 defer afterTest(t) 690 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 691 if r.TLS != nil { 692 w.Header().Set("X-TLS-Set", "true") 693 if r.TLS.HandshakeComplete { 694 w.Header().Set("X-TLS-HandshakeComplete", "true") 695 } 696 } 697 })) 698 defer ts.Close() 699 700 // Connect an idle TCP connection to this server before we run 701 // our real tests. This idle connection used to block forever 702 // in the TLS handshake, preventing future connections from 703 // being accepted. It may prevent future accidental blocking 704 // in newConn. 705 idleConn, err := net.Dial("tcp", ts.Listener.Addr().String()) 706 if err != nil { 707 t.Fatalf("Dial: %v", err) 708 } 709 defer idleConn.Close() 710 goTimeout(t, 10*time.Second, func() { 711 if !strings.HasPrefix(ts.URL, "https://") { 712 t.Errorf("expected test TLS server to start with https://, got %q", ts.URL) 713 return 714 } 715 noVerifyTransport := &Transport{ 716 TLSClientConfig: &tls.Config{ 717 InsecureSkipVerify: true, 718 }, 719 } 720 client := &Client{Transport: noVerifyTransport} 721 res, err := client.Get(ts.URL) 722 if err != nil { 723 t.Error(err) 724 return 725 } 726 if res == nil { 727 t.Errorf("got nil Response") 728 return 729 } 730 defer res.Body.Close() 731 if res.Header.Get("X-TLS-Set") != "true" { 732 t.Errorf("expected X-TLS-Set response header") 733 return 734 } 735 if res.Header.Get("X-TLS-HandshakeComplete") != "true" { 736 t.Errorf("expected X-TLS-HandshakeComplete header") 737 } 738 }) 739 } 740 741 type serverExpectTest struct { 742 contentLength int // of request body 743 expectation string // e.g. "100-continue" 744 readBody bool // whether handler should read the body (if false, sends StatusUnauthorized) 745 expectedResponse string // expected substring in first line of http response 746 } 747 748 var serverExpectTests = []serverExpectTest{ 749 // Normal 100-continues, case-insensitive. 750 {100, "100-continue", true, "100 Continue"}, 751 {100, "100-cOntInUE", true, "100 Continue"}, 752 753 // No 100-continue. 754 {100, "", true, "200 OK"}, 755 756 // 100-continue but requesting client to deny us, 757 // so it never reads the body. 758 {100, "100-continue", false, "401 Unauthorized"}, 759 // Likewise without 100-continue: 760 {100, "", false, "401 Unauthorized"}, 761 762 // Non-standard expectations are failures 763 {0, "a-pony", false, "417 Expectation Failed"}, 764 765 // Expect-100 requested but no body 766 {0, "100-continue", true, "400 Bad Request"}, 767 } 768 769 // Tests that the server responds to the "Expect" request header 770 // correctly. 771 func TestServerExpect(t *testing.T) { 772 defer afterTest(t) 773 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 774 // Note using r.FormValue("readbody") because for POST 775 // requests that would read from r.Body, which we only 776 // conditionally want to do. 777 if strings.Contains(r.URL.RawQuery, "readbody=true") { 778 ioutil.ReadAll(r.Body) 779 w.Write([]byte("Hi")) 780 } else { 781 w.WriteHeader(StatusUnauthorized) 782 } 783 })) 784 defer ts.Close() 785 786 runTest := func(test serverExpectTest) { 787 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 788 if err != nil { 789 t.Fatalf("Dial: %v", err) 790 } 791 defer conn.Close() 792 793 // Only send the body immediately if we're acting like an HTTP client 794 // that doesn't send 100-continue expectations. 795 writeBody := test.contentLength > 0 && strings.ToLower(test.expectation) != "100-continue" 796 797 go func() { 798 _, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+ 799 "Connection: close\r\n"+ 800 "Content-Length: %d\r\n"+ 801 "Expect: %s\r\nHost: foo\r\n\r\n", 802 test.readBody, test.contentLength, test.expectation) 803 if err != nil { 804 t.Errorf("On test %#v, error writing request headers: %v", test, err) 805 return 806 } 807 if writeBody { 808 body := strings.Repeat("A", test.contentLength) 809 _, err = fmt.Fprint(conn, body) 810 if err != nil { 811 if !test.readBody { 812 // Server likely already hung up on us. 813 // See larger comment below. 814 t.Logf("On test %#v, acceptable error writing request body: %v", test, err) 815 return 816 } 817 t.Errorf("On test %#v, error writing request body: %v", test, err) 818 } 819 } 820 }() 821 bufr := bufio.NewReader(conn) 822 line, err := bufr.ReadString('\n') 823 if err != nil { 824 if writeBody && !test.readBody { 825 // This is an acceptable failure due to a possible TCP race: 826 // We were still writing data and the server hung up on us. A TCP 827 // implementation may send a RST if our request body data was known 828 // to be lost, which may trigger our reads to fail. 829 // See RFC 1122 page 88. 830 t.Logf("On test %#v, acceptable error from ReadString: %v", test, err) 831 return 832 } 833 t.Fatalf("On test %#v, ReadString: %v", test, err) 834 } 835 if !strings.Contains(line, test.expectedResponse) { 836 t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse) 837 } 838 } 839 840 for _, test := range serverExpectTests { 841 runTest(test) 842 } 843 } 844 845 // Under a ~256KB (maxPostHandlerReadBytes) threshold, the server 846 // should consume client request bodies that a handler didn't read. 847 func TestServerUnreadRequestBodyLittle(t *testing.T) { 848 conn := new(testConn) 849 body := strings.Repeat("x", 100<<10) 850 conn.readBuf.Write([]byte(fmt.Sprintf( 851 "POST / HTTP/1.1\r\n"+ 852 "Host: test\r\n"+ 853 "Content-Length: %d\r\n"+ 854 "\r\n", len(body)))) 855 conn.readBuf.Write([]byte(body)) 856 857 done := make(chan bool) 858 859 ls := &oneConnListener{conn} 860 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 861 defer close(done) 862 if conn.readBuf.Len() < len(body)/2 { 863 t.Errorf("on request, read buffer length is %d; expected about 100 KB", conn.readBuf.Len()) 864 } 865 rw.WriteHeader(200) 866 rw.(Flusher).Flush() 867 if g, e := conn.readBuf.Len(), 0; g != e { 868 t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e) 869 } 870 if c := rw.Header().Get("Connection"); c != "" { 871 t.Errorf(`Connection header = %q; want ""`, c) 872 } 873 })) 874 <-done 875 } 876 877 // Over a ~256KB (maxPostHandlerReadBytes) threshold, the server 878 // should ignore client request bodies that a handler didn't read 879 // and close the connection. 880 func TestServerUnreadRequestBodyLarge(t *testing.T) { 881 conn := new(testConn) 882 body := strings.Repeat("x", 1<<20) 883 conn.readBuf.Write([]byte(fmt.Sprintf( 884 "POST / HTTP/1.1\r\n"+ 885 "Host: test\r\n"+ 886 "Content-Length: %d\r\n"+ 887 "\r\n", len(body)))) 888 conn.readBuf.Write([]byte(body)) 889 conn.closec = make(chan bool, 1) 890 891 ls := &oneConnListener{conn} 892 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 893 if conn.readBuf.Len() < len(body)/2 { 894 t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len()) 895 } 896 rw.WriteHeader(200) 897 rw.(Flusher).Flush() 898 if conn.readBuf.Len() < len(body)/2 { 899 t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len()) 900 } 901 })) 902 <-conn.closec 903 904 if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") { 905 t.Errorf("Expected a Connection: close header; got response: %s", res) 906 } 907 } 908 909 func TestTimeoutHandler(t *testing.T) { 910 defer afterTest(t) 911 sendHi := make(chan bool, 1) 912 writeErrors := make(chan error, 1) 913 sayHi := HandlerFunc(func(w ResponseWriter, r *Request) { 914 <-sendHi 915 _, werr := w.Write([]byte("hi")) 916 writeErrors <- werr 917 }) 918 timeout := make(chan time.Time, 1) // write to this to force timeouts 919 ts := httptest.NewServer(NewTestTimeoutHandler(sayHi, timeout)) 920 defer ts.Close() 921 922 // Succeed without timing out: 923 sendHi <- true 924 res, err := Get(ts.URL) 925 if err != nil { 926 t.Error(err) 927 } 928 if g, e := res.StatusCode, StatusOK; g != e { 929 t.Errorf("got res.StatusCode %d; expected %d", g, e) 930 } 931 body, _ := ioutil.ReadAll(res.Body) 932 if g, e := string(body), "hi"; g != e { 933 t.Errorf("got body %q; expected %q", g, e) 934 } 935 if g := <-writeErrors; g != nil { 936 t.Errorf("got unexpected Write error on first request: %v", g) 937 } 938 939 // Times out: 940 timeout <- time.Time{} 941 res, err = Get(ts.URL) 942 if err != nil { 943 t.Error(err) 944 } 945 if g, e := res.StatusCode, StatusServiceUnavailable; g != e { 946 t.Errorf("got res.StatusCode %d; expected %d", g, e) 947 } 948 body, _ = ioutil.ReadAll(res.Body) 949 if !strings.Contains(string(body), "<title>Timeout</title>") { 950 t.Errorf("expected timeout body; got %q", string(body)) 951 } 952 953 // Now make the previously-timed out handler speak again, 954 // which verifies the panic is handled: 955 sendHi <- true 956 if g, e := <-writeErrors, ErrHandlerTimeout; g != e { 957 t.Errorf("expected Write error of %v; got %v", e, g) 958 } 959 } 960 961 // Verifies we don't path.Clean() on the wrong parts in redirects. 962 func TestRedirectMunging(t *testing.T) { 963 req, _ := NewRequest("GET", "http://example.com/", nil) 964 965 resp := httptest.NewRecorder() 966 Redirect(resp, req, "/foo?next=http://bar.com/", 302) 967 if g, e := resp.Header().Get("Location"), "/foo?next=http://bar.com/"; g != e { 968 t.Errorf("Location header was %q; want %q", g, e) 969 } 970 971 resp = httptest.NewRecorder() 972 Redirect(resp, req, "http://localhost:8080/_ah/login?continue=http://localhost:8080/", 302) 973 if g, e := resp.Header().Get("Location"), "http://localhost:8080/_ah/login?continue=http://localhost:8080/"; g != e { 974 t.Errorf("Location header was %q; want %q", g, e) 975 } 976 } 977 978 // TestZeroLengthPostAndResponse exercises an optimization done by the Transport: 979 // when there is no body (either because the method doesn't permit a body, or an 980 // explicit Content-Length of zero is present), then the transport can re-use the 981 // connection immediately. But when it re-uses the connection, it typically closes 982 // the previous request's body, which is not optimal for zero-lengthed bodies, 983 // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF. 984 func TestZeroLengthPostAndResponse(t *testing.T) { 985 defer afterTest(t) 986 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 987 all, err := ioutil.ReadAll(r.Body) 988 if err != nil { 989 t.Fatalf("handler ReadAll: %v", err) 990 } 991 if len(all) != 0 { 992 t.Errorf("handler got %d bytes; expected 0", len(all)) 993 } 994 rw.Header().Set("Content-Length", "0") 995 })) 996 defer ts.Close() 997 998 req, err := NewRequest("POST", ts.URL, strings.NewReader("")) 999 if err != nil { 1000 t.Fatal(err) 1001 } 1002 req.ContentLength = 0 1003 1004 var resp [5]*Response 1005 for i := range resp { 1006 resp[i], err = DefaultClient.Do(req) 1007 if err != nil { 1008 t.Fatalf("client post #%d: %v", i, err) 1009 } 1010 } 1011 1012 for i := range resp { 1013 all, err := ioutil.ReadAll(resp[i].Body) 1014 if err != nil { 1015 t.Fatalf("req #%d: client ReadAll: %v", i, err) 1016 } 1017 if len(all) != 0 { 1018 t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all)) 1019 } 1020 } 1021 } 1022 1023 func TestHandlerPanicNil(t *testing.T) { 1024 testHandlerPanic(t, false, nil) 1025 } 1026 1027 func TestHandlerPanic(t *testing.T) { 1028 testHandlerPanic(t, false, "intentional death for testing") 1029 } 1030 1031 func TestHandlerPanicWithHijack(t *testing.T) { 1032 testHandlerPanic(t, true, "intentional death for testing") 1033 } 1034 1035 func testHandlerPanic(t *testing.T, withHijack bool, panicValue interface{}) { 1036 defer afterTest(t) 1037 // Unlike the other tests that set the log output to ioutil.Discard 1038 // to quiet the output, this test uses a pipe. The pipe serves three 1039 // purposes: 1040 // 1041 // 1) The log.Print from the http server (generated by the caught 1042 // panic) will go to the pipe instead of stderr, making the 1043 // output quiet. 1044 // 1045 // 2) We read from the pipe to verify that the handler 1046 // actually caught the panic and logged something. 1047 // 1048 // 3) The blocking Read call prevents this TestHandlerPanic 1049 // function from exiting before the HTTP server handler 1050 // finishes crashing. If this text function exited too 1051 // early (and its defer log.SetOutput(os.Stderr) ran), 1052 // then the crash output could spill into the next test. 1053 pr, pw := io.Pipe() 1054 log.SetOutput(pw) 1055 defer log.SetOutput(os.Stderr) 1056 defer pw.Close() 1057 1058 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1059 if withHijack { 1060 rwc, _, err := w.(Hijacker).Hijack() 1061 if err != nil { 1062 t.Logf("unexpected error: %v", err) 1063 } 1064 defer rwc.Close() 1065 } 1066 panic(panicValue) 1067 })) 1068 defer ts.Close() 1069 1070 // Do a blocking read on the log output pipe so its logging 1071 // doesn't bleed into the next test. But wait only 5 seconds 1072 // for it. 1073 done := make(chan bool, 1) 1074 go func() { 1075 buf := make([]byte, 4<<10) 1076 _, err := pr.Read(buf) 1077 pr.Close() 1078 if err != nil && err != io.EOF { 1079 t.Error(err) 1080 } 1081 done <- true 1082 }() 1083 1084 _, err := Get(ts.URL) 1085 if err == nil { 1086 t.Logf("expected an error") 1087 } 1088 1089 if panicValue == nil { 1090 return 1091 } 1092 1093 select { 1094 case <-done: 1095 return 1096 case <-time.After(5 * time.Second): 1097 t.Fatal("expected server handler to log an error") 1098 } 1099 } 1100 1101 func TestNoDate(t *testing.T) { 1102 defer afterTest(t) 1103 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1104 w.Header()["Date"] = nil 1105 })) 1106 defer ts.Close() 1107 res, err := Get(ts.URL) 1108 if err != nil { 1109 t.Fatal(err) 1110 } 1111 _, present := res.Header["Date"] 1112 if present { 1113 t.Fatalf("Expected no Date header; got %v", res.Header["Date"]) 1114 } 1115 } 1116 1117 func TestStripPrefix(t *testing.T) { 1118 defer afterTest(t) 1119 h := HandlerFunc(func(w ResponseWriter, r *Request) { 1120 w.Header().Set("X-Path", r.URL.Path) 1121 }) 1122 ts := httptest.NewServer(StripPrefix("/foo", h)) 1123 defer ts.Close() 1124 1125 res, err := Get(ts.URL + "/foo/bar") 1126 if err != nil { 1127 t.Fatal(err) 1128 } 1129 if g, e := res.Header.Get("X-Path"), "/bar"; g != e { 1130 t.Errorf("test 1: got %s, want %s", g, e) 1131 } 1132 res.Body.Close() 1133 1134 res, err = Get(ts.URL + "/bar") 1135 if err != nil { 1136 t.Fatal(err) 1137 } 1138 if g, e := res.StatusCode, 404; g != e { 1139 t.Errorf("test 2: got status %v, want %v", g, e) 1140 } 1141 res.Body.Close() 1142 } 1143 1144 func TestRequestLimit(t *testing.T) { 1145 defer afterTest(t) 1146 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1147 t.Fatalf("didn't expect to get request in Handler") 1148 })) 1149 defer ts.Close() 1150 req, _ := NewRequest("GET", ts.URL, nil) 1151 var bytesPerHeader = len("header12345: val12345\r\n") 1152 for i := 0; i < ((DefaultMaxHeaderBytes+4096)/bytesPerHeader)+1; i++ { 1153 req.Header.Set(fmt.Sprintf("header%05d", i), fmt.Sprintf("val%05d", i)) 1154 } 1155 res, err := DefaultClient.Do(req) 1156 if err != nil { 1157 // Some HTTP clients may fail on this undefined behavior (server replying and 1158 // closing the connection while the request is still being written), but 1159 // we do support it (at least currently), so we expect a response below. 1160 t.Fatalf("Do: %v", err) 1161 } 1162 defer res.Body.Close() 1163 if res.StatusCode != 413 { 1164 t.Fatalf("expected 413 response status; got: %d %s", res.StatusCode, res.Status) 1165 } 1166 } 1167 1168 type neverEnding byte 1169 1170 func (b neverEnding) Read(p []byte) (n int, err error) { 1171 for i := range p { 1172 p[i] = byte(b) 1173 } 1174 return len(p), nil 1175 } 1176 1177 type countReader struct { 1178 r io.Reader 1179 n *int64 1180 } 1181 1182 func (cr countReader) Read(p []byte) (n int, err error) { 1183 n, err = cr.r.Read(p) 1184 atomic.AddInt64(cr.n, int64(n)) 1185 return 1186 } 1187 1188 func TestRequestBodyLimit(t *testing.T) { 1189 defer afterTest(t) 1190 const limit = 1 << 20 1191 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1192 r.Body = MaxBytesReader(w, r.Body, limit) 1193 n, err := io.Copy(ioutil.Discard, r.Body) 1194 if err == nil { 1195 t.Errorf("expected error from io.Copy") 1196 } 1197 if n != limit { 1198 t.Errorf("io.Copy = %d, want %d", n, limit) 1199 } 1200 })) 1201 defer ts.Close() 1202 1203 nWritten := new(int64) 1204 req, _ := NewRequest("POST", ts.URL, io.LimitReader(countReader{neverEnding('a'), nWritten}, limit*200)) 1205 1206 // Send the POST, but don't care it succeeds or not. The 1207 // remote side is going to reply and then close the TCP 1208 // connection, and HTTP doesn't really define if that's 1209 // allowed or not. Some HTTP clients will get the response 1210 // and some (like ours, currently) will complain that the 1211 // request write failed, without reading the response. 1212 // 1213 // But that's okay, since what we're really testing is that 1214 // the remote side hung up on us before we wrote too much. 1215 _, _ = DefaultClient.Do(req) 1216 1217 if atomic.LoadInt64(nWritten) > limit*100 { 1218 t.Errorf("handler restricted the request body to %d bytes, but client managed to write %d", 1219 limit, nWritten) 1220 } 1221 } 1222 1223 // TestClientWriteShutdown tests that if the client shuts down the write 1224 // side of their TCP connection, the server doesn't send a 400 Bad Request. 1225 func TestClientWriteShutdown(t *testing.T) { 1226 defer afterTest(t) 1227 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 1228 defer ts.Close() 1229 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1230 if err != nil { 1231 t.Fatalf("Dial: %v", err) 1232 } 1233 err = conn.(*net.TCPConn).CloseWrite() 1234 if err != nil { 1235 t.Fatalf("Dial: %v", err) 1236 } 1237 donec := make(chan bool) 1238 go func() { 1239 defer close(donec) 1240 bs, err := ioutil.ReadAll(conn) 1241 if err != nil { 1242 t.Fatalf("ReadAll: %v", err) 1243 } 1244 got := string(bs) 1245 if got != "" { 1246 t.Errorf("read %q from server; want nothing", got) 1247 } 1248 }() 1249 select { 1250 case <-donec: 1251 case <-time.After(10 * time.Second): 1252 t.Fatalf("timeout") 1253 } 1254 } 1255 1256 // Tests that chunked server responses that write 1 byte at a time are 1257 // buffered before chunk headers are added, not after chunk headers. 1258 func TestServerBufferedChunking(t *testing.T) { 1259 conn := new(testConn) 1260 conn.readBuf.Write([]byte("GET / HTTP/1.1\r\n\r\n")) 1261 conn.closec = make(chan bool, 1) 1262 ls := &oneConnListener{conn} 1263 go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) { 1264 rw.(Flusher).Flush() // force the Header to be sent, in chunking mode, not counting the length 1265 rw.Write([]byte{'x'}) 1266 rw.Write([]byte{'y'}) 1267 rw.Write([]byte{'z'}) 1268 })) 1269 <-conn.closec 1270 if !bytes.HasSuffix(conn.writeBuf.Bytes(), []byte("\r\n\r\n3\r\nxyz\r\n0\r\n\r\n")) { 1271 t.Errorf("response didn't end with a single 3 byte 'xyz' chunk; got:\n%q", 1272 conn.writeBuf.Bytes()) 1273 } 1274 } 1275 1276 // Tests that the server flushes its response headers out when it's 1277 // ignoring the response body and waits a bit before forcefully 1278 // closing the TCP connection, causing the client to get a RST. 1279 // See http://golang.org/issue/3595 1280 func TestServerGracefulClose(t *testing.T) { 1281 defer afterTest(t) 1282 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1283 Error(w, "bye", StatusUnauthorized) 1284 })) 1285 defer ts.Close() 1286 1287 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1288 if err != nil { 1289 t.Fatal(err) 1290 } 1291 defer conn.Close() 1292 const bodySize = 5 << 20 1293 req := []byte(fmt.Sprintf("POST / HTTP/1.1\r\nHost: foo.com\r\nContent-Length: %d\r\n\r\n", bodySize)) 1294 for i := 0; i < bodySize; i++ { 1295 req = append(req, 'x') 1296 } 1297 writeErr := make(chan error) 1298 go func() { 1299 _, err := conn.Write(req) 1300 writeErr <- err 1301 }() 1302 br := bufio.NewReader(conn) 1303 lineNum := 0 1304 for { 1305 line, err := br.ReadString('\n') 1306 if err == io.EOF { 1307 break 1308 } 1309 if err != nil { 1310 t.Fatalf("ReadLine: %v", err) 1311 } 1312 lineNum++ 1313 if lineNum == 1 && !strings.Contains(line, "401 Unauthorized") { 1314 t.Errorf("Response line = %q; want a 401", line) 1315 } 1316 } 1317 // Wait for write to finish. This is a broken pipe on both 1318 // Darwin and Linux, but checking this isn't the point of 1319 // the test. 1320 <-writeErr 1321 } 1322 1323 func TestCaseSensitiveMethod(t *testing.T) { 1324 defer afterTest(t) 1325 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1326 if r.Method != "get" { 1327 t.Errorf(`Got method %q; want "get"`, r.Method) 1328 } 1329 })) 1330 defer ts.Close() 1331 req, _ := NewRequest("get", ts.URL, nil) 1332 res, err := DefaultClient.Do(req) 1333 if err != nil { 1334 t.Error(err) 1335 return 1336 } 1337 res.Body.Close() 1338 } 1339 1340 // TestContentLengthZero tests that for both an HTTP/1.0 and HTTP/1.1 1341 // request (both keep-alive), when a Handler never writes any 1342 // response, the net/http package adds a "Content-Length: 0" response 1343 // header. 1344 func TestContentLengthZero(t *testing.T) { 1345 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {})) 1346 defer ts.Close() 1347 1348 for _, version := range []string{"HTTP/1.0", "HTTP/1.1"} { 1349 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1350 if err != nil { 1351 t.Fatalf("error dialing: %v", err) 1352 } 1353 _, err = fmt.Fprintf(conn, "GET / %v\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n", version) 1354 if err != nil { 1355 t.Fatalf("error writing: %v", err) 1356 } 1357 req, _ := NewRequest("GET", "/", nil) 1358 res, err := ReadResponse(bufio.NewReader(conn), req) 1359 if err != nil { 1360 t.Fatalf("error reading response: %v", err) 1361 } 1362 if te := res.TransferEncoding; len(te) > 0 { 1363 t.Errorf("For version %q, Transfer-Encoding = %q; want none", version, te) 1364 } 1365 if cl := res.ContentLength; cl != 0 { 1366 t.Errorf("For version %q, Content-Length = %v; want 0", version, cl) 1367 } 1368 conn.Close() 1369 } 1370 } 1371 1372 func TestCloseNotifier(t *testing.T) { 1373 defer afterTest(t) 1374 gotReq := make(chan bool, 1) 1375 sawClose := make(chan bool, 1) 1376 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 1377 gotReq <- true 1378 cc := rw.(CloseNotifier).CloseNotify() 1379 <-cc 1380 sawClose <- true 1381 })) 1382 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1383 if err != nil { 1384 t.Fatalf("error dialing: %v", err) 1385 } 1386 diec := make(chan bool) 1387 go func() { 1388 _, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n") 1389 if err != nil { 1390 t.Fatal(err) 1391 } 1392 <-diec 1393 conn.Close() 1394 }() 1395 For: 1396 for { 1397 select { 1398 case <-gotReq: 1399 diec <- true 1400 case <-sawClose: 1401 break For 1402 case <-time.After(5 * time.Second): 1403 t.Fatal("timeout") 1404 } 1405 } 1406 ts.Close() 1407 } 1408 1409 func TestCloseNotifierChanLeak(t *testing.T) { 1410 defer afterTest(t) 1411 req := []byte(strings.Replace(`GET / HTTP/1.0 1412 Host: golang.org 1413 1414 `, "\n", "\r\n", -1)) 1415 for i := 0; i < 20; i++ { 1416 var output bytes.Buffer 1417 conn := &rwTestConn{ 1418 Reader: bytes.NewReader(req), 1419 Writer: &output, 1420 closec: make(chan bool, 1), 1421 } 1422 ln := &oneConnListener{conn: conn} 1423 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 1424 // Ignore the return value and never read from 1425 // it, testing that we don't leak goroutines 1426 // on the sending side: 1427 _ = rw.(CloseNotifier).CloseNotify() 1428 }) 1429 go Serve(ln, handler) 1430 <-conn.closec 1431 } 1432 } 1433 1434 func TestOptions(t *testing.T) { 1435 uric := make(chan string, 2) // only expect 1, but leave space for 2 1436 mux := NewServeMux() 1437 mux.HandleFunc("/", func(w ResponseWriter, r *Request) { 1438 uric <- r.RequestURI 1439 }) 1440 ts := httptest.NewServer(mux) 1441 defer ts.Close() 1442 1443 conn, err := net.Dial("tcp", ts.Listener.Addr().String()) 1444 if err != nil { 1445 t.Fatal(err) 1446 } 1447 defer conn.Close() 1448 1449 // An OPTIONS * request should succeed. 1450 _, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n")) 1451 if err != nil { 1452 t.Fatal(err) 1453 } 1454 br := bufio.NewReader(conn) 1455 res, err := ReadResponse(br, &Request{Method: "OPTIONS"}) 1456 if err != nil { 1457 t.Fatal(err) 1458 } 1459 if res.StatusCode != 200 { 1460 t.Errorf("Got non-200 response to OPTIONS *: %#v", res) 1461 } 1462 1463 // A GET * request on a ServeMux should fail. 1464 _, err = conn.Write([]byte("GET * HTTP/1.1\r\nHost: foo.com\r\n\r\n")) 1465 if err != nil { 1466 t.Fatal(err) 1467 } 1468 res, err = ReadResponse(br, &Request{Method: "GET"}) 1469 if err != nil { 1470 t.Fatal(err) 1471 } 1472 if res.StatusCode != 400 { 1473 t.Errorf("Got non-400 response to GET *: %#v", res) 1474 } 1475 1476 res, err = Get(ts.URL + "/second") 1477 if err != nil { 1478 t.Fatal(err) 1479 } 1480 res.Body.Close() 1481 if got := <-uric; got != "/second" { 1482 t.Errorf("Handler saw request for %q; want /second", got) 1483 } 1484 } 1485 1486 // Tests regarding the ordering of Write, WriteHeader, Header, and 1487 // Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the 1488 // (*response).header to the wire. In Go 1.1, the actual wire flush is 1489 // delayed, so we could maybe tack on a Content-Length and better 1490 // Content-Type after we see more (or all) of the output. To preserve 1491 // compatibility with Go 1, we need to be careful to track which 1492 // headers were live at the time of WriteHeader, so we write the same 1493 // ones, even if the handler modifies them (~erroneously) after the 1494 // first Write. 1495 func TestHeaderToWire(t *testing.T) { 1496 req := []byte(strings.Replace(`GET / HTTP/1.1 1497 Host: golang.org 1498 1499 `, "\n", "\r\n", -1)) 1500 1501 tests := []struct { 1502 name string 1503 handler func(ResponseWriter, *Request) 1504 check func(output string) error 1505 }{ 1506 { 1507 name: "write without Header", 1508 handler: func(rw ResponseWriter, r *Request) { 1509 rw.Write([]byte("hello world")) 1510 }, 1511 check: func(got string) error { 1512 if !strings.Contains(got, "Content-Length:") { 1513 return errors.New("no content-length") 1514 } 1515 if !strings.Contains(got, "Content-Type: text/plain") { 1516 return errors.New("no content-length") 1517 } 1518 return nil 1519 }, 1520 }, 1521 { 1522 name: "Header mutation before write", 1523 handler: func(rw ResponseWriter, r *Request) { 1524 h := rw.Header() 1525 h.Set("Content-Type", "some/type") 1526 rw.Write([]byte("hello world")) 1527 h.Set("Too-Late", "bogus") 1528 }, 1529 check: func(got string) error { 1530 if !strings.Contains(got, "Content-Length:") { 1531 return errors.New("no content-length") 1532 } 1533 if !strings.Contains(got, "Content-Type: some/type") { 1534 return errors.New("wrong content-type") 1535 } 1536 if strings.Contains(got, "Too-Late") { 1537 return errors.New("don't want too-late header") 1538 } 1539 return nil 1540 }, 1541 }, 1542 { 1543 name: "write then useless Header mutation", 1544 handler: func(rw ResponseWriter, r *Request) { 1545 rw.Write([]byte("hello world")) 1546 rw.Header().Set("Too-Late", "Write already wrote headers") 1547 }, 1548 check: func(got string) error { 1549 if strings.Contains(got, "Too-Late") { 1550 return errors.New("header appeared from after WriteHeader") 1551 } 1552 return nil 1553 }, 1554 }, 1555 { 1556 name: "flush then write", 1557 handler: func(rw ResponseWriter, r *Request) { 1558 rw.(Flusher).Flush() 1559 rw.Write([]byte("post-flush")) 1560 rw.Header().Set("Too-Late", "Write already wrote headers") 1561 }, 1562 check: func(got string) error { 1563 if !strings.Contains(got, "Transfer-Encoding: chunked") { 1564 return errors.New("not chunked") 1565 } 1566 if strings.Contains(got, "Too-Late") { 1567 return errors.New("header appeared from after WriteHeader") 1568 } 1569 return nil 1570 }, 1571 }, 1572 { 1573 name: "header then flush", 1574 handler: func(rw ResponseWriter, r *Request) { 1575 rw.Header().Set("Content-Type", "some/type") 1576 rw.(Flusher).Flush() 1577 rw.Write([]byte("post-flush")) 1578 rw.Header().Set("Too-Late", "Write already wrote headers") 1579 }, 1580 check: func(got string) error { 1581 if !strings.Contains(got, "Transfer-Encoding: chunked") { 1582 return errors.New("not chunked") 1583 } 1584 if strings.Contains(got, "Too-Late") { 1585 return errors.New("header appeared from after WriteHeader") 1586 } 1587 if !strings.Contains(got, "Content-Type: some/type") { 1588 return errors.New("wrong content-length") 1589 } 1590 return nil 1591 }, 1592 }, 1593 { 1594 name: "sniff-on-first-write content-type", 1595 handler: func(rw ResponseWriter, r *Request) { 1596 rw.Write([]byte("<html><head></head><body>some html</body></html>")) 1597 rw.Header().Set("Content-Type", "x/wrong") 1598 }, 1599 check: func(got string) error { 1600 if !strings.Contains(got, "Content-Type: text/html") { 1601 return errors.New("wrong content-length; want html") 1602 } 1603 return nil 1604 }, 1605 }, 1606 { 1607 name: "explicit content-type wins", 1608 handler: func(rw ResponseWriter, r *Request) { 1609 rw.Header().Set("Content-Type", "some/type") 1610 rw.Write([]byte("<html><head></head><body>some html</body></html>")) 1611 }, 1612 check: func(got string) error { 1613 if !strings.Contains(got, "Content-Type: some/type") { 1614 return errors.New("wrong content-length; want html") 1615 } 1616 return nil 1617 }, 1618 }, 1619 { 1620 name: "empty handler", 1621 handler: func(rw ResponseWriter, r *Request) { 1622 }, 1623 check: func(got string) error { 1624 if !strings.Contains(got, "Content-Type: text/plain") { 1625 return errors.New("wrong content-length; want text/plain") 1626 } 1627 if !strings.Contains(got, "Content-Length: 0") { 1628 return errors.New("want 0 content-length") 1629 } 1630 return nil 1631 }, 1632 }, 1633 { 1634 name: "only Header, no write", 1635 handler: func(rw ResponseWriter, r *Request) { 1636 rw.Header().Set("Some-Header", "some-value") 1637 }, 1638 check: func(got string) error { 1639 if !strings.Contains(got, "Some-Header") { 1640 return errors.New("didn't get header") 1641 } 1642 return nil 1643 }, 1644 }, 1645 { 1646 name: "WriteHeader call", 1647 handler: func(rw ResponseWriter, r *Request) { 1648 rw.WriteHeader(404) 1649 rw.Header().Set("Too-Late", "some-value") 1650 }, 1651 check: func(got string) error { 1652 if !strings.Contains(got, "404") { 1653 return errors.New("wrong status") 1654 } 1655 if strings.Contains(got, "Some-Header") { 1656 return errors.New("shouldn't have seen Too-Late") 1657 } 1658 return nil 1659 }, 1660 }, 1661 } 1662 for _, tc := range tests { 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 go Serve(ln, HandlerFunc(tc.handler)) 1671 <-conn.closec 1672 if err := tc.check(output.String()); err != nil { 1673 t.Errorf("%s: %v\nGot response:\n%s", tc.name, err, output.Bytes()) 1674 } 1675 } 1676 } 1677 1678 // goTimeout runs f, failing t if f takes more than ns to complete. 1679 func goTimeout(t *testing.T, d time.Duration, f func()) { 1680 ch := make(chan bool, 2) 1681 timer := time.AfterFunc(d, func() { 1682 t.Errorf("Timeout expired after %v", d) 1683 ch <- true 1684 }) 1685 defer timer.Stop() 1686 go func() { 1687 defer func() { ch <- true }() 1688 f() 1689 }() 1690 <-ch 1691 } 1692 1693 type errorListener struct { 1694 errs []error 1695 } 1696 1697 func (l *errorListener) Accept() (c net.Conn, err error) { 1698 if len(l.errs) == 0 { 1699 return nil, io.EOF 1700 } 1701 err = l.errs[0] 1702 l.errs = l.errs[1:] 1703 return 1704 } 1705 1706 func (l *errorListener) Close() error { 1707 return nil 1708 } 1709 1710 func (l *errorListener) Addr() net.Addr { 1711 return dummyAddr("test-address") 1712 } 1713 1714 func TestAcceptMaxFds(t *testing.T) { 1715 log.SetOutput(ioutil.Discard) // is noisy otherwise 1716 defer log.SetOutput(os.Stderr) 1717 1718 ln := &errorListener{[]error{ 1719 &net.OpError{ 1720 Op: "accept", 1721 Err: syscall.EMFILE, 1722 }}} 1723 err := Serve(ln, HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {}))) 1724 if err != io.EOF { 1725 t.Errorf("got error %v, want EOF", err) 1726 } 1727 } 1728 1729 func BenchmarkClientServer(b *testing.B) { 1730 b.StopTimer() 1731 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 1732 fmt.Fprintf(rw, "Hello world.\n") 1733 })) 1734 defer ts.Close() 1735 b.StartTimer() 1736 1737 for i := 0; i < b.N; i++ { 1738 res, err := Get(ts.URL) 1739 if err != nil { 1740 b.Fatal("Get:", err) 1741 } 1742 all, err := ioutil.ReadAll(res.Body) 1743 if err != nil { 1744 b.Fatal("ReadAll:", err) 1745 } 1746 body := string(all) 1747 if body != "Hello world.\n" { 1748 b.Fatal("Got body:", body) 1749 } 1750 } 1751 1752 b.StopTimer() 1753 } 1754 1755 func BenchmarkClientServerParallel4(b *testing.B) { 1756 benchmarkClientServerParallel(b, 4) 1757 } 1758 1759 func BenchmarkClientServerParallel64(b *testing.B) { 1760 benchmarkClientServerParallel(b, 64) 1761 } 1762 1763 func benchmarkClientServerParallel(b *testing.B, conc int) { 1764 b.StopTimer() 1765 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 1766 fmt.Fprintf(rw, "Hello world.\n") 1767 })) 1768 defer ts.Close() 1769 b.StartTimer() 1770 1771 numProcs := runtime.GOMAXPROCS(-1) * conc 1772 var wg sync.WaitGroup 1773 wg.Add(numProcs) 1774 n := int32(b.N) 1775 for p := 0; p < numProcs; p++ { 1776 go func() { 1777 for atomic.AddInt32(&n, -1) >= 0 { 1778 res, err := Get(ts.URL) 1779 if err != nil { 1780 b.Logf("Get: %v", err) 1781 continue 1782 } 1783 all, err := ioutil.ReadAll(res.Body) 1784 if err != nil { 1785 b.Logf("ReadAll: %v", err) 1786 continue 1787 } 1788 body := string(all) 1789 if body != "Hello world.\n" { 1790 panic("Got body: " + body) 1791 } 1792 } 1793 wg.Done() 1794 }() 1795 } 1796 wg.Wait() 1797 } 1798 1799 // A benchmark for profiling the server without the HTTP client code. 1800 // The client code runs in a subprocess. 1801 // 1802 // For use like: 1803 // $ go test -c 1804 // $ ./http.test -test.run=XX -test.bench=BenchmarkServer -test.benchtime=15s -test.cpuprofile=http.prof 1805 // $ go tool pprof http.test http.prof 1806 // (pprof) web 1807 func BenchmarkServer(b *testing.B) { 1808 // Child process mode; 1809 if url := os.Getenv("TEST_BENCH_SERVER_URL"); url != "" { 1810 n, err := strconv.Atoi(os.Getenv("TEST_BENCH_CLIENT_N")) 1811 if err != nil { 1812 panic(err) 1813 } 1814 for i := 0; i < n; i++ { 1815 res, err := Get(url) 1816 if err != nil { 1817 log.Panicf("Get: %v", err) 1818 } 1819 all, err := ioutil.ReadAll(res.Body) 1820 if err != nil { 1821 log.Panicf("ReadAll: %v", err) 1822 } 1823 body := string(all) 1824 if body != "Hello world.\n" { 1825 log.Panicf("Got body: %q", body) 1826 } 1827 } 1828 os.Exit(0) 1829 return 1830 } 1831 1832 var res = []byte("Hello world.\n") 1833 b.StopTimer() 1834 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) { 1835 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 1836 rw.Write(res) 1837 })) 1838 defer ts.Close() 1839 b.StartTimer() 1840 1841 cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkServer") 1842 cmd.Env = append([]string{ 1843 fmt.Sprintf("TEST_BENCH_CLIENT_N=%d", b.N), 1844 fmt.Sprintf("TEST_BENCH_SERVER_URL=%s", ts.URL), 1845 }, os.Environ()...) 1846 out, err := cmd.CombinedOutput() 1847 if err != nil { 1848 b.Errorf("Test failure: %v, with output: %s", err, out) 1849 } 1850 } 1851 1852 func BenchmarkServerFakeConnNoKeepAlive(b *testing.B) { 1853 b.ReportAllocs() 1854 req := []byte(strings.Replace(`GET / HTTP/1.0 1855 Host: golang.org 1856 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 1857 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 1858 Accept-Encoding: gzip,deflate,sdch 1859 Accept-Language: en-US,en;q=0.8 1860 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 1861 1862 `, "\n", "\r\n", -1)) 1863 res := []byte("Hello world!\n") 1864 1865 conn := &testConn{ 1866 // testConn.Close will not push into the channel 1867 // if it's full. 1868 closec: make(chan bool, 1), 1869 } 1870 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 1871 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 1872 rw.Write(res) 1873 }) 1874 ln := new(oneConnListener) 1875 for i := 0; i < b.N; i++ { 1876 conn.readBuf.Reset() 1877 conn.writeBuf.Reset() 1878 conn.readBuf.Write(req) 1879 ln.conn = conn 1880 Serve(ln, handler) 1881 <-conn.closec 1882 } 1883 } 1884 1885 // repeatReader reads content count times, then EOFs. 1886 type repeatReader struct { 1887 content []byte 1888 count int 1889 off int 1890 } 1891 1892 func (r *repeatReader) Read(p []byte) (n int, err error) { 1893 if r.count <= 0 { 1894 return 0, io.EOF 1895 } 1896 n = copy(p, r.content[r.off:]) 1897 r.off += n 1898 if r.off == len(r.content) { 1899 r.count-- 1900 r.off = 0 1901 } 1902 return 1903 } 1904 1905 func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) { 1906 b.ReportAllocs() 1907 1908 req := []byte(strings.Replace(`GET / HTTP/1.1 1909 Host: golang.org 1910 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 1911 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 1912 Accept-Encoding: gzip,deflate,sdch 1913 Accept-Language: en-US,en;q=0.8 1914 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 1915 1916 `, "\n", "\r\n", -1)) 1917 res := []byte("Hello world!\n") 1918 1919 conn := &rwTestConn{ 1920 Reader: &repeatReader{content: req, count: b.N}, 1921 Writer: ioutil.Discard, 1922 closec: make(chan bool, 1), 1923 } 1924 handled := 0 1925 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 1926 handled++ 1927 rw.Header().Set("Content-Type", "text/html; charset=utf-8") 1928 rw.Write(res) 1929 }) 1930 ln := &oneConnListener{conn: conn} 1931 go Serve(ln, handler) 1932 <-conn.closec 1933 if b.N != handled { 1934 b.Errorf("b.N=%d but handled %d", b.N, handled) 1935 } 1936 } 1937 1938 // same as above, but representing the most simple possible request 1939 // and handler. Notably: the handler does not call rw.Header(). 1940 func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) { 1941 b.ReportAllocs() 1942 1943 req := []byte(strings.Replace(`GET / HTTP/1.1 1944 Host: golang.org 1945 1946 `, "\n", "\r\n", -1)) 1947 res := []byte("Hello world!\n") 1948 1949 conn := &rwTestConn{ 1950 Reader: &repeatReader{content: req, count: b.N}, 1951 Writer: ioutil.Discard, 1952 closec: make(chan bool, 1), 1953 } 1954 handled := 0 1955 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 1956 handled++ 1957 rw.Write(res) 1958 }) 1959 ln := &oneConnListener{conn: conn} 1960 go Serve(ln, handler) 1961 <-conn.closec 1962 if b.N != handled { 1963 b.Errorf("b.N=%d but handled %d", b.N, handled) 1964 } 1965 } 1966 1967 const someResponse = "<html>some response</html>" 1968 1969 // A Response that's just no bigger than 2KB, the buffer-before-chunking threshold. 1970 var response = bytes.Repeat([]byte(someResponse), 2<<10/len(someResponse)) 1971 1972 // Both Content-Type and Content-Length set. Should be no buffering. 1973 func BenchmarkServerHandlerTypeLen(b *testing.B) { 1974 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 1975 w.Header().Set("Content-Type", "text/html") 1976 w.Header().Set("Content-Length", strconv.Itoa(len(response))) 1977 w.Write(response) 1978 })) 1979 } 1980 1981 // A Content-Type is set, but no length. No sniffing, but will count the Content-Length. 1982 func BenchmarkServerHandlerNoLen(b *testing.B) { 1983 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 1984 w.Header().Set("Content-Type", "text/html") 1985 w.Write(response) 1986 })) 1987 } 1988 1989 // A Content-Length is set, but the Content-Type will be sniffed. 1990 func BenchmarkServerHandlerNoType(b *testing.B) { 1991 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 1992 w.Header().Set("Content-Length", strconv.Itoa(len(response))) 1993 w.Write(response) 1994 })) 1995 } 1996 1997 // Neither a Content-Type or Content-Length, so sniffed and counted. 1998 func BenchmarkServerHandlerNoHeader(b *testing.B) { 1999 benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) { 2000 w.Write(response) 2001 })) 2002 } 2003 2004 func benchmarkHandler(b *testing.B, h Handler) { 2005 b.ReportAllocs() 2006 req := []byte(strings.Replace(`GET / HTTP/1.1 2007 Host: golang.org 2008 2009 `, "\n", "\r\n", -1)) 2010 conn := &rwTestConn{ 2011 Reader: &repeatReader{content: req, count: b.N}, 2012 Writer: ioutil.Discard, 2013 closec: make(chan bool, 1), 2014 } 2015 handled := 0 2016 handler := HandlerFunc(func(rw ResponseWriter, r *Request) { 2017 handled++ 2018 h.ServeHTTP(rw, r) 2019 }) 2020 ln := &oneConnListener{conn: conn} 2021 go Serve(ln, handler) 2022 <-conn.closec 2023 if b.N != handled { 2024 b.Errorf("b.N=%d but handled %d", b.N, handled) 2025 } 2026 }