/third_party/gofrontend/libgo/go/net/http/serve_test.go
Go | 3687 lines | 3131 code | 299 blank | 257 comment | 790 complexity | c2428b0a49ec4501730cd1924f9d265b MD5 | raw file
Possible License(s): BSD-3-Clause, MIT
Large files files are truncated, but you can click here to view the full file
- // Copyright 2010 The Go Authors. All rights reserved.
- // Use of this source code is governed by a BSD-style
- // license that can be found in the LICENSE file.
- // End-to-end serving tests
- package http_test
- import (
- "bufio"
- "bytes"
- "crypto/tls"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "log"
- "math/rand"
- "net"
- . "net/http"
- "net/http/httptest"
- "net/http/httputil"
- "net/http/internal"
- "net/url"
- "os"
- "os/exec"
- "reflect"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "syscall"
- "testing"
- "time"
- )
- type dummyAddr string
- type oneConnListener struct {
- conn net.Conn
- }
- func (l *oneConnListener) Accept() (c net.Conn, err error) {
- c = l.conn
- if c == nil {
- err = io.EOF
- return
- }
- err = nil
- l.conn = nil
- return
- }
- func (l *oneConnListener) Close() error {
- return nil
- }
- func (l *oneConnListener) Addr() net.Addr {
- return dummyAddr("test-address")
- }
- func (a dummyAddr) Network() string {
- return string(a)
- }
- func (a dummyAddr) String() string {
- return string(a)
- }
- type noopConn struct{}
- func (noopConn) LocalAddr() net.Addr { return dummyAddr("local-addr") }
- func (noopConn) RemoteAddr() net.Addr { return dummyAddr("remote-addr") }
- func (noopConn) SetDeadline(t time.Time) error { return nil }
- func (noopConn) SetReadDeadline(t time.Time) error { return nil }
- func (noopConn) SetWriteDeadline(t time.Time) error { return nil }
- type rwTestConn struct {
- io.Reader
- io.Writer
- noopConn
- closeFunc func() error // called if non-nil
- closec chan bool // else, if non-nil, send value to it on close
- }
- func (c *rwTestConn) Close() error {
- if c.closeFunc != nil {
- return c.closeFunc()
- }
- select {
- case c.closec <- true:
- default:
- }
- return nil
- }
- type testConn struct {
- readBuf bytes.Buffer
- writeBuf bytes.Buffer
- closec chan bool // if non-nil, send value to it on close
- noopConn
- }
- func (c *testConn) Read(b []byte) (int, error) {
- return c.readBuf.Read(b)
- }
- func (c *testConn) Write(b []byte) (int, error) {
- return c.writeBuf.Write(b)
- }
- func (c *testConn) Close() error {
- select {
- case c.closec <- true:
- default:
- }
- return nil
- }
- // reqBytes treats req as a request (with \n delimiters) and returns it with \r\n delimiters,
- // ending in \r\n\r\n
- func reqBytes(req string) []byte {
- return []byte(strings.Replace(strings.TrimSpace(req), "\n", "\r\n", -1) + "\r\n\r\n")
- }
- type handlerTest struct {
- handler Handler
- }
- func newHandlerTest(h Handler) handlerTest {
- return handlerTest{h}
- }
- func (ht handlerTest) rawResponse(req string) string {
- reqb := reqBytes(req)
- var output bytes.Buffer
- conn := &rwTestConn{
- Reader: bytes.NewReader(reqb),
- Writer: &output,
- closec: make(chan bool, 1),
- }
- ln := &oneConnListener{conn: conn}
- go Serve(ln, ht.handler)
- <-conn.closec
- return output.String()
- }
- func TestConsumingBodyOnNextConn(t *testing.T) {
- defer afterTest(t)
- conn := new(testConn)
- for i := 0; i < 2; i++ {
- conn.readBuf.Write([]byte(
- "POST / HTTP/1.1\r\n" +
- "Host: test\r\n" +
- "Content-Length: 11\r\n" +
- "\r\n" +
- "foo=1&bar=1"))
- }
- reqNum := 0
- ch := make(chan *Request)
- servech := make(chan error)
- listener := &oneConnListener{conn}
- handler := func(res ResponseWriter, req *Request) {
- reqNum++
- ch <- req
- }
- go func() {
- servech <- Serve(listener, HandlerFunc(handler))
- }()
- var req *Request
- req = <-ch
- if req == nil {
- t.Fatal("Got nil first request.")
- }
- if req.Method != "POST" {
- t.Errorf("For request #1's method, got %q; expected %q",
- req.Method, "POST")
- }
- req = <-ch
- if req == nil {
- t.Fatal("Got nil first request.")
- }
- if req.Method != "POST" {
- t.Errorf("For request #2's method, got %q; expected %q",
- req.Method, "POST")
- }
- if serveerr := <-servech; serveerr != io.EOF {
- t.Errorf("Serve returned %q; expected EOF", serveerr)
- }
- }
- type stringHandler string
- func (s stringHandler) ServeHTTP(w ResponseWriter, r *Request) {
- w.Header().Set("Result", string(s))
- }
- var handlers = []struct {
- pattern string
- msg string
- }{
- {"/", "Default"},
- {"/someDir/", "someDir"},
- {"/#/", "hash"},
- {"someHost.com/someDir/", "someHost.com/someDir"},
- }
- var vtests = []struct {
- url string
- expected string
- }{
- {"http://localhost/someDir/apage", "someDir"},
- {"http://localhost/%23/apage", "hash"},
- {"http://localhost/otherDir/apage", "Default"},
- {"http://someHost.com/someDir/apage", "someHost.com/someDir"},
- {"http://otherHost.com/someDir/apage", "someDir"},
- {"http://otherHost.com/aDir/apage", "Default"},
- // redirections for trees
- {"http://localhost/someDir", "/someDir/"},
- {"http://localhost/%23", "/%23/"},
- {"http://someHost.com/someDir", "/someDir/"},
- }
- func TestHostHandlers(t *testing.T) {
- defer afterTest(t)
- mux := NewServeMux()
- for _, h := range handlers {
- mux.Handle(h.pattern, stringHandler(h.msg))
- }
- ts := httptest.NewServer(mux)
- defer ts.Close()
- conn, err := net.Dial("tcp", ts.Listener.Addr().String())
- if err != nil {
- t.Fatal(err)
- }
- defer conn.Close()
- cc := httputil.NewClientConn(conn, nil)
- for _, vt := range vtests {
- var r *Response
- var req Request
- if req.URL, err = url.Parse(vt.url); err != nil {
- t.Errorf("cannot parse url: %v", err)
- continue
- }
- if err := cc.Write(&req); err != nil {
- t.Errorf("writing request: %v", err)
- continue
- }
- r, err := cc.Read(&req)
- if err != nil {
- t.Errorf("reading response: %v", err)
- continue
- }
- switch r.StatusCode {
- case StatusOK:
- s := r.Header.Get("Result")
- if s != vt.expected {
- t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
- }
- case StatusMovedPermanently:
- s := r.Header.Get("Location")
- if s != vt.expected {
- t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
- }
- default:
- t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode)
- }
- }
- }
- var serveMuxRegister = []struct {
- pattern string
- h Handler
- }{
- {"/dir/", serve(200)},
- {"/search", serve(201)},
- {"codesearch.google.com/search", serve(202)},
- {"codesearch.google.com/", serve(203)},
- {"example.com/", HandlerFunc(checkQueryStringHandler)},
- }
- // serve returns a handler that sends a response with the given code.
- func serve(code int) HandlerFunc {
- return func(w ResponseWriter, r *Request) {
- w.WriteHeader(code)
- }
- }
- // checkQueryStringHandler checks if r.URL.RawQuery has the same value
- // as the URL excluding the scheme and the query string and sends 200
- // response code if it is, 500 otherwise.
- func checkQueryStringHandler(w ResponseWriter, r *Request) {
- u := *r.URL
- u.Scheme = "http"
- u.Host = r.Host
- u.RawQuery = ""
- if "http://"+r.URL.RawQuery == u.String() {
- w.WriteHeader(200)
- } else {
- w.WriteHeader(500)
- }
- }
- var serveMuxTests = []struct {
- method string
- host string
- path string
- code int
- pattern string
- }{
- {"GET", "google.com", "/", 404, ""},
- {"GET", "google.com", "/dir", 301, "/dir/"},
- {"GET", "google.com", "/dir/", 200, "/dir/"},
- {"GET", "google.com", "/dir/file", 200, "/dir/"},
- {"GET", "google.com", "/search", 201, "/search"},
- {"GET", "google.com", "/search/", 404, ""},
- {"GET", "google.com", "/search/foo", 404, ""},
- {"GET", "codesearch.google.com", "/search", 202, "codesearch.google.com/search"},
- {"GET", "codesearch.google.com", "/search/", 203, "codesearch.google.com/"},
- {"GET", "codesearch.google.com", "/search/foo", 203, "codesearch.google.com/"},
- {"GET", "codesearch.google.com", "/", 203, "codesearch.google.com/"},
- {"GET", "images.google.com", "/search", 201, "/search"},
- {"GET", "images.google.com", "/search/", 404, ""},
- {"GET", "images.google.com", "/search/foo", 404, ""},
- {"GET", "google.com", "/../search", 301, "/search"},
- {"GET", "google.com", "/dir/..", 301, ""},
- {"GET", "google.com", "/dir/..", 301, ""},
- {"GET", "google.com", "/dir/./file", 301, "/dir/"},
- // The /foo -> /foo/ redirect applies to CONNECT requests
- // but the path canonicalization does not.
- {"CONNECT", "google.com", "/dir", 301, "/dir/"},
- {"CONNECT", "google.com", "/../search", 404, ""},
- {"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
- {"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
- {"CONNECT", "google.com", "/dir/./file", 200, "/dir/"},
- }
- func TestServeMuxHandler(t *testing.T) {
- mux := NewServeMux()
- for _, e := range serveMuxRegister {
- mux.Handle(e.pattern, e.h)
- }
- for _, tt := range serveMuxTests {
- r := &Request{
- Method: tt.method,
- Host: tt.host,
- URL: &url.URL{
- Path: tt.path,
- },
- }
- h, pattern := mux.Handler(r)
- rr := httptest.NewRecorder()
- h.ServeHTTP(rr, r)
- if pattern != tt.pattern || rr.Code != tt.code {
- t.Errorf("%s %s %s = %d, %q, want %d, %q", tt.method, tt.host, tt.path, rr.Code, pattern, tt.code, tt.pattern)
- }
- }
- }
- var serveMuxTests2 = []struct {
- method string
- host string
- url string
- code int
- redirOk bool
- }{
- {"GET", "google.com", "/", 404, false},
- {"GET", "example.com", "/test/?example.com/test/", 200, false},
- {"GET", "example.com", "test/?example.com/test/", 200, true},
- }
- // TestServeMuxHandlerRedirects tests that automatic redirects generated by
- // mux.Handler() shouldn't clear the request's query string.
- func TestServeMuxHandlerRedirects(t *testing.T) {
- mux := NewServeMux()
- for _, e := range serveMuxRegister {
- mux.Handle(e.pattern, e.h)
- }
- for _, tt := range serveMuxTests2 {
- tries := 1
- turl := tt.url
- for tries > 0 {
- u, e := url.Parse(turl)
- if e != nil {
- t.Fatal(e)
- }
- r := &Request{
- Method: tt.method,
- Host: tt.host,
- URL: u,
- }
- h, _ := mux.Handler(r)
- rr := httptest.NewRecorder()
- h.ServeHTTP(rr, r)
- if rr.Code != 301 {
- if rr.Code != tt.code {
- t.Errorf("%s %s %s = %d, want %d", tt.method, tt.host, tt.url, rr.Code, tt.code)
- }
- break
- }
- if !tt.redirOk {
- t.Errorf("%s %s %s, unexpected redirect", tt.method, tt.host, tt.url)
- break
- }
- turl = rr.HeaderMap.Get("Location")
- tries--
- }
- if tries < 0 {
- t.Errorf("%s %s %s, too many redirects", tt.method, tt.host, tt.url)
- }
- }
- }
- // Tests for https://golang.org/issue/900
- func TestMuxRedirectLeadingSlashes(t *testing.T) {
- paths := []string{"//foo.txt", "///foo.txt", "/../../foo.txt"}
- for _, path := range paths {
- req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n")))
- if err != nil {
- t.Errorf("%s", err)
- }
- mux := NewServeMux()
- resp := httptest.NewRecorder()
- mux.ServeHTTP(resp, req)
- if loc, expected := resp.Header().Get("Location"), "/foo.txt"; loc != expected {
- t.Errorf("Expected Location header set to %q; got %q", expected, loc)
- return
- }
- if code, expected := resp.Code, StatusMovedPermanently; code != expected {
- t.Errorf("Expected response code of StatusMovedPermanently; got %d", code)
- return
- }
- }
- }
- func TestServerTimeouts(t *testing.T) {
- if runtime.GOOS == "plan9" {
- t.Skip("skipping test; see https://golang.org/issue/7237")
- }
- defer afterTest(t)
- reqNum := 0
- ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
- reqNum++
- fmt.Fprintf(res, "req=%d", reqNum)
- }))
- ts.Config.ReadTimeout = 250 * time.Millisecond
- ts.Config.WriteTimeout = 250 * time.Millisecond
- ts.Start()
- defer ts.Close()
- // Hit the HTTP server successfully.
- tr := &Transport{DisableKeepAlives: true} // they interfere with this test
- defer tr.CloseIdleConnections()
- c := &Client{Transport: tr}
- r, err := c.Get(ts.URL)
- if err != nil {
- t.Fatalf("http Get #1: %v", err)
- }
- got, _ := ioutil.ReadAll(r.Body)
- expected := "req=1"
- if string(got) != expected {
- t.Errorf("Unexpected response for request #1; got %q; expected %q",
- string(got), expected)
- }
- // Slow client that should timeout.
- t1 := time.Now()
- conn, err := net.Dial("tcp", ts.Listener.Addr().String())
- if err != nil {
- t.Fatalf("Dial: %v", err)
- }
- buf := make([]byte, 1)
- n, err := conn.Read(buf)
- latency := time.Since(t1)
- if n != 0 || err != io.EOF {
- t.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF)
- }
- if latency < 200*time.Millisecond /* fudge from 250 ms above */ {
- t.Errorf("got EOF after %s, want >= %s", latency, 200*time.Millisecond)
- }
- // Hit the HTTP server successfully again, verifying that the
- // previous slow connection didn't run our handler. (that we
- // get "req=2", not "req=3")
- r, err = Get(ts.URL)
- if err != nil {
- t.Fatalf("http Get #2: %v", err)
- }
- got, _ = ioutil.ReadAll(r.Body)
- expected = "req=2"
- if string(got) != expected {
- t.Errorf("Get #2 got %q, want %q", string(got), expected)
- }
- if !testing.Short() {
- conn, err := net.Dial("tcp", ts.Listener.Addr().String())
- if err != nil {
- t.Fatalf("Dial: %v", err)
- }
- defer conn.Close()
- go io.Copy(ioutil.Discard, conn)
- for i := 0; i < 5; i++ {
- _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
- if err != nil {
- t.Fatalf("on write %d: %v", i, err)
- }
- time.Sleep(ts.Config.ReadTimeout / 2)
- }
- }
- }
- // golang.org/issue/4741 -- setting only a write timeout that triggers
- // shouldn't cause a handler to block forever on reads (next HTTP
- // request) that will never happen.
- func TestOnlyWriteTimeout(t *testing.T) {
- if runtime.GOOS == "plan9" {
- t.Skip("skipping test; see https://golang.org/issue/7237")
- }
- defer afterTest(t)
- var conn net.Conn
- var afterTimeoutErrc = make(chan error, 1)
- ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, req *Request) {
- buf := make([]byte, 512<<10)
- _, err := w.Write(buf)
- if err != nil {
- t.Errorf("handler Write error: %v", err)
- return
- }
- conn.SetWriteDeadline(time.Now().Add(-30 * time.Second))
- _, err = w.Write(buf)
- afterTimeoutErrc <- err
- }))
- ts.Listener = trackLastConnListener{ts.Listener, &conn}
- ts.Start()
- defer ts.Close()
- tr := &Transport{DisableKeepAlives: false}
- defer tr.CloseIdleConnections()
- c := &Client{Transport: tr}
- errc := make(chan error)
- go func() {
- res, err := c.Get(ts.URL)
- if err != nil {
- errc <- err
- return
- }
- _, err = io.Copy(ioutil.Discard, res.Body)
- errc <- err
- }()
- select {
- case err := <-errc:
- if err == nil {
- t.Errorf("expected an error from Get request")
- }
- case <-time.After(5 * time.Second):
- t.Fatal("timeout waiting for Get error")
- }
- if err := <-afterTimeoutErrc; err == nil {
- t.Error("expected write error after timeout")
- }
- }
- // trackLastConnListener tracks the last net.Conn that was accepted.
- type trackLastConnListener struct {
- net.Listener
- last *net.Conn // destination
- }
- func (l trackLastConnListener) Accept() (c net.Conn, err error) {
- c, err = l.Listener.Accept()
- *l.last = c
- return
- }
- // TestIdentityResponse verifies that a handler can unset
- func TestIdentityResponse(t *testing.T) {
- defer afterTest(t)
- handler := HandlerFunc(func(rw ResponseWriter, req *Request) {
- rw.Header().Set("Content-Length", "3")
- rw.Header().Set("Transfer-Encoding", req.FormValue("te"))
- switch {
- case req.FormValue("overwrite") == "1":
- _, err := rw.Write([]byte("foo TOO LONG"))
- if err != ErrContentLength {
- t.Errorf("expected ErrContentLength; got %v", err)
- }
- case req.FormValue("underwrite") == "1":
- rw.Header().Set("Content-Length", "500")
- rw.Write([]byte("too short"))
- default:
- rw.Write([]byte("foo"))
- }
- })
- ts := httptest.NewServer(handler)
- defer ts.Close()
- // Note: this relies on the assumption (which is true) that
- // Get sends HTTP/1.1 or greater requests. Otherwise the
- // server wouldn't have the choice to send back chunked
- // responses.
- for _, te := range []string{"", "identity"} {
- url := ts.URL + "/?te=" + te
- res, err := Get(url)
- if err != nil {
- t.Fatalf("error with Get of %s: %v", url, err)
- }
- if cl, expected := res.ContentLength, int64(3); cl != expected {
- t.Errorf("for %s expected res.ContentLength of %d; got %d", url, expected, cl)
- }
- if cl, expected := res.Header.Get("Content-Length"), "3"; cl != expected {
- t.Errorf("for %s expected Content-Length header of %q; got %q", url, expected, cl)
- }
- if tl, expected := len(res.TransferEncoding), 0; tl != expected {
- t.Errorf("for %s expected len(res.TransferEncoding) of %d; got %d (%v)",
- url, expected, tl, res.TransferEncoding)
- }
- res.Body.Close()
- }
- // Verify that ErrContentLength is returned
- url := ts.URL + "/?overwrite=1"
- res, err := Get(url)
- if err != nil {
- t.Fatalf("error with Get of %s: %v", url, err)
- }
- res.Body.Close()
- // Verify that the connection is closed when the declared Content-Length
- // is larger than what the handler wrote.
- conn, err := net.Dial("tcp", ts.Listener.Addr().String())
- if err != nil {
- t.Fatalf("error dialing: %v", err)
- }
- _, err = conn.Write([]byte("GET /?underwrite=1 HTTP/1.1\r\nHost: foo\r\n\r\n"))
- if err != nil {
- t.Fatalf("error writing: %v", err)
- }
- // The ReadAll will hang for a failing test, so use a Timer to
- // fail explicitly.
- goTimeout(t, 2*time.Second, func() {
- got, _ := ioutil.ReadAll(conn)
- expectedSuffix := "\r\n\r\ntoo short"
- if !strings.HasSuffix(string(got), expectedSuffix) {
- t.Errorf("Expected output to end with %q; got response body %q",
- expectedSuffix, string(got))
- }
- })
- }
- func testTCPConnectionCloses(t *testing.T, req string, h Handler) {
- defer afterTest(t)
- s := httptest.NewServer(h)
- defer s.Close()
- conn, err := net.Dial("tcp", s.Listener.Addr().String())
- if err != nil {
- t.Fatal("dial error:", err)
- }
- defer conn.Close()
- _, err = fmt.Fprint(conn, req)
- if err != nil {
- t.Fatal("print error:", err)
- }
- r := bufio.NewReader(conn)
- res, err := ReadResponse(r, &Request{Method: "GET"})
- if err != nil {
- t.Fatal("ReadResponse error:", err)
- }
- didReadAll := make(chan bool, 1)
- go func() {
- select {
- case <-time.After(5 * time.Second):
- t.Error("body not closed after 5s")
- return
- case <-didReadAll:
- }
- }()
- _, err = ioutil.ReadAll(r)
- if err != nil {
- t.Fatal("read error:", err)
- }
- didReadAll <- true
- if !res.Close {
- t.Errorf("Response.Close = false; want true")
- }
- }
- // TestServeHTTP10Close verifies that HTTP/1.0 requests won't be kept alive.
- func TestServeHTTP10Close(t *testing.T) {
- testTCPConnectionCloses(t, "GET / HTTP/1.0\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
- ServeFile(w, r, "testdata/file")
- }))
- }
- // TestClientCanClose verifies that clients can also force a connection to close.
- func TestClientCanClose(t *testing.T) {
- testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nConnection: close\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
- // Nothing.
- }))
- }
- // TestHandlersCanSetConnectionClose verifies that handlers can force a connection to close,
- // even for HTTP/1.1 requests.
- func TestHandlersCanSetConnectionClose11(t *testing.T) {
- testTCPConnectionCloses(t, "GET / HTTP/1.1\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
- w.Header().Set("Connection", "close")
- }))
- }
- func TestHandlersCanSetConnectionClose10(t *testing.T) {
- testTCPConnectionCloses(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
- w.Header().Set("Connection", "close")
- }))
- }
- func TestSetsRemoteAddr(t *testing.T) {
- defer afterTest(t)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- fmt.Fprintf(w, "%s", r.RemoteAddr)
- }))
- defer ts.Close()
- res, err := Get(ts.URL)
- if err != nil {
- t.Fatalf("Get error: %v", err)
- }
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- t.Fatalf("ReadAll error: %v", err)
- }
- ip := string(body)
- if !strings.HasPrefix(ip, "127.0.0.1:") && !strings.HasPrefix(ip, "[::1]:") {
- t.Fatalf("Expected local addr; got %q", ip)
- }
- }
- func TestChunkedResponseHeaders(t *testing.T) {
- defer afterTest(t)
- log.SetOutput(ioutil.Discard) // is noisy otherwise
- defer log.SetOutput(os.Stderr)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted
- w.(Flusher).Flush()
- fmt.Fprintf(w, "I am a chunked response.")
- }))
- defer ts.Close()
- res, err := Get(ts.URL)
- if err != nil {
- t.Fatalf("Get error: %v", err)
- }
- defer res.Body.Close()
- if g, e := res.ContentLength, int64(-1); g != e {
- t.Errorf("expected ContentLength of %d; got %d", e, g)
- }
- if g, e := res.TransferEncoding, []string{"chunked"}; !reflect.DeepEqual(g, e) {
- t.Errorf("expected TransferEncoding of %v; got %v", e, g)
- }
- if _, haveCL := res.Header["Content-Length"]; haveCL {
- t.Errorf("Unexpected Content-Length")
- }
- }
- func TestIdentityResponseHeaders(t *testing.T) {
- defer afterTest(t)
- log.SetOutput(ioutil.Discard) // is noisy otherwise
- defer log.SetOutput(os.Stderr)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- w.Header().Set("Transfer-Encoding", "identity")
- w.(Flusher).Flush()
- fmt.Fprintf(w, "I am an identity response.")
- }))
- defer ts.Close()
- res, err := Get(ts.URL)
- if err != nil {
- t.Fatalf("Get error: %v", err)
- }
- defer res.Body.Close()
- if g, e := res.TransferEncoding, []string(nil); !reflect.DeepEqual(g, e) {
- t.Errorf("expected TransferEncoding of %v; got %v", e, g)
- }
- if _, haveCL := res.Header["Content-Length"]; haveCL {
- t.Errorf("Unexpected Content-Length")
- }
- if !res.Close {
- t.Errorf("expected Connection: close; got %v", res.Close)
- }
- }
- // Test304Responses verifies that 304s don't declare that they're
- // chunking in their response headers and aren't allowed to produce
- // output.
- func Test304Responses(t *testing.T) {
- defer afterTest(t)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- w.WriteHeader(StatusNotModified)
- _, err := w.Write([]byte("illegal body"))
- if err != ErrBodyNotAllowed {
- t.Errorf("on Write, expected ErrBodyNotAllowed, got %v", err)
- }
- }))
- defer ts.Close()
- res, err := Get(ts.URL)
- if err != nil {
- t.Error(err)
- }
- if len(res.TransferEncoding) > 0 {
- t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
- }
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- t.Error(err)
- }
- if len(body) > 0 {
- t.Errorf("got unexpected body %q", string(body))
- }
- }
- // TestHeadResponses verifies that all MIME type sniffing and Content-Length
- // counting of GET requests also happens on HEAD requests.
- func TestHeadResponses(t *testing.T) {
- defer afterTest(t)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- _, err := w.Write([]byte("<html>"))
- if err != nil {
- t.Errorf("ResponseWriter.Write: %v", err)
- }
- // Also exercise the ReaderFrom path
- _, err = io.Copy(w, strings.NewReader("789a"))
- if err != nil {
- t.Errorf("Copy(ResponseWriter, ...): %v", err)
- }
- }))
- defer ts.Close()
- res, err := Head(ts.URL)
- if err != nil {
- t.Error(err)
- }
- if len(res.TransferEncoding) > 0 {
- t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
- }
- if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" {
- t.Errorf("Content-Type: %q; want text/html; charset=utf-8", ct)
- }
- if v := res.ContentLength; v != 10 {
- t.Errorf("Content-Length: %d; want 10", v)
- }
- body, err := ioutil.ReadAll(res.Body)
- if err != nil {
- t.Error(err)
- }
- if len(body) > 0 {
- t.Errorf("got unexpected body %q", string(body))
- }
- }
- func TestTLSHandshakeTimeout(t *testing.T) {
- if runtime.GOOS == "plan9" {
- t.Skip("skipping test; see https://golang.org/issue/7237")
- }
- defer afterTest(t)
- ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
- errc := make(chanWriter, 10) // but only expecting 1
- ts.Config.ReadTimeout = 250 * time.Millisecond
- ts.Config.ErrorLog = log.New(errc, "", 0)
- ts.StartTLS()
- defer ts.Close()
- conn, err := net.Dial("tcp", ts.Listener.Addr().String())
- if err != nil {
- t.Fatalf("Dial: %v", err)
- }
- defer conn.Close()
- goTimeout(t, 10*time.Second, func() {
- var buf [1]byte
- n, err := conn.Read(buf[:])
- if err == nil || n != 0 {
- t.Errorf("Read = %d, %v; want an error and no bytes", n, err)
- }
- })
- select {
- case v := <-errc:
- if !strings.Contains(v, "timeout") && !strings.Contains(v, "TLS handshake") {
- t.Errorf("expected a TLS handshake timeout error; got %q", v)
- }
- case <-time.After(5 * time.Second):
- t.Errorf("timeout waiting for logged error")
- }
- }
- func TestTLSServer(t *testing.T) {
- defer afterTest(t)
- ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- if r.TLS != nil {
- w.Header().Set("X-TLS-Set", "true")
- if r.TLS.HandshakeComplete {
- w.Header().Set("X-TLS-HandshakeComplete", "true")
- }
- }
- }))
- ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
- defer ts.Close()
- // Connect an idle TCP connection to this server before we run
- // our real tests. This idle connection used to block forever
- // in the TLS handshake, preventing future connections from
- // being accepted. It may prevent future accidental blocking
- // in newConn.
- idleConn, err := net.Dial("tcp", ts.Listener.Addr().String())
- if err != nil {
- t.Fatalf("Dial: %v", err)
- }
- defer idleConn.Close()
- goTimeout(t, 10*time.Second, func() {
- if !strings.HasPrefix(ts.URL, "https://") {
- t.Errorf("expected test TLS server to start with https://, got %q", ts.URL)
- return
- }
- noVerifyTransport := &Transport{
- TLSClientConfig: &tls.Config{
- InsecureSkipVerify: true,
- },
- }
- client := &Client{Transport: noVerifyTransport}
- res, err := client.Get(ts.URL)
- if err != nil {
- t.Error(err)
- return
- }
- if res == nil {
- t.Errorf("got nil Response")
- return
- }
- defer res.Body.Close()
- if res.Header.Get("X-TLS-Set") != "true" {
- t.Errorf("expected X-TLS-Set response header")
- return
- }
- if res.Header.Get("X-TLS-HandshakeComplete") != "true" {
- t.Errorf("expected X-TLS-HandshakeComplete header")
- }
- })
- }
- type serverExpectTest struct {
- contentLength int // of request body
- chunked bool
- expectation string // e.g. "100-continue"
- readBody bool // whether handler should read the body (if false, sends StatusUnauthorized)
- expectedResponse string // expected substring in first line of http response
- }
- func expectTest(contentLength int, expectation string, readBody bool, expectedResponse string) serverExpectTest {
- return serverExpectTest{
- contentLength: contentLength,
- expectation: expectation,
- readBody: readBody,
- expectedResponse: expectedResponse,
- }
- }
- var serverExpectTests = []serverExpectTest{
- // Normal 100-continues, case-insensitive.
- expectTest(100, "100-continue", true, "100 Continue"),
- expectTest(100, "100-cOntInUE", true, "100 Continue"),
- // No 100-continue.
- expectTest(100, "", true, "200 OK"),
- // 100-continue but requesting client to deny us,
- // so it never reads the body.
- expectTest(100, "100-continue", false, "401 Unauthorized"),
- // Likewise without 100-continue:
- expectTest(100, "", false, "401 Unauthorized"),
- // Non-standard expectations are failures
- expectTest(0, "a-pony", false, "417 Expectation Failed"),
- // Expect-100 requested but no body (is apparently okay: Issue 7625)
- expectTest(0, "100-continue", true, "200 OK"),
- // Expect-100 requested but handler doesn't read the body
- expectTest(0, "100-continue", false, "401 Unauthorized"),
- // Expect-100 continue with no body, but a chunked body.
- {
- expectation: "100-continue",
- readBody: true,
- chunked: true,
- expectedResponse: "100 Continue",
- },
- }
- // Tests that the server responds to the "Expect" request header
- // correctly.
- func TestServerExpect(t *testing.T) {
- defer afterTest(t)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- // Note using r.FormValue("readbody") because for POST
- // requests that would read from r.Body, which we only
- // conditionally want to do.
- if strings.Contains(r.URL.RawQuery, "readbody=true") {
- ioutil.ReadAll(r.Body)
- w.Write([]byte("Hi"))
- } else {
- w.WriteHeader(StatusUnauthorized)
- }
- }))
- defer ts.Close()
- runTest := func(test serverExpectTest) {
- conn, err := net.Dial("tcp", ts.Listener.Addr().String())
- if err != nil {
- t.Fatalf("Dial: %v", err)
- }
- defer conn.Close()
- // Only send the body immediately if we're acting like an HTTP client
- // that doesn't send 100-continue expectations.
- writeBody := test.contentLength != 0 && strings.ToLower(test.expectation) != "100-continue"
- go func() {
- contentLen := fmt.Sprintf("Content-Length: %d", test.contentLength)
- if test.chunked {
- contentLen = "Transfer-Encoding: chunked"
- }
- _, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+
- "Connection: close\r\n"+
- "%s\r\n"+
- "Expect: %s\r\nHost: foo\r\n\r\n",
- test.readBody, contentLen, test.expectation)
- if err != nil {
- t.Errorf("On test %#v, error writing request headers: %v", test, err)
- return
- }
- if writeBody {
- var targ io.WriteCloser = struct {
- io.Writer
- io.Closer
- }{
- conn,
- ioutil.NopCloser(nil),
- }
- if test.chunked {
- targ = httputil.NewChunkedWriter(conn)
- }
- body := strings.Repeat("A", test.contentLength)
- _, err = fmt.Fprint(targ, body)
- if err == nil {
- err = targ.Close()
- }
- if err != nil {
- if !test.readBody {
- // Server likely already hung up on us.
- // See larger comment below.
- t.Logf("On test %#v, acceptable error writing request body: %v", test, err)
- return
- }
- t.Errorf("On test %#v, error writing request body: %v", test, err)
- }
- }
- }()
- bufr := bufio.NewReader(conn)
- line, err := bufr.ReadString('\n')
- if err != nil {
- if writeBody && !test.readBody {
- // This is an acceptable failure due to a possible TCP race:
- // We were still writing data and the server hung up on us. A TCP
- // implementation may send a RST if our request body data was known
- // to be lost, which may trigger our reads to fail.
- // See RFC 1122 page 88.
- t.Logf("On test %#v, acceptable error from ReadString: %v", test, err)
- return
- }
- t.Fatalf("On test %#v, ReadString: %v", test, err)
- }
- if !strings.Contains(line, test.expectedResponse) {
- t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse)
- }
- }
- for _, test := range serverExpectTests {
- runTest(test)
- }
- }
- // Under a ~256KB (maxPostHandlerReadBytes) threshold, the server
- // should consume client request bodies that a handler didn't read.
- func TestServerUnreadRequestBodyLittle(t *testing.T) {
- defer afterTest(t)
- conn := new(testConn)
- body := strings.Repeat("x", 100<<10)
- conn.readBuf.Write([]byte(fmt.Sprintf(
- "POST / HTTP/1.1\r\n"+
- "Host: test\r\n"+
- "Content-Length: %d\r\n"+
- "\r\n", len(body))))
- conn.readBuf.Write([]byte(body))
- done := make(chan bool)
- ls := &oneConnListener{conn}
- go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
- defer close(done)
- if conn.readBuf.Len() < len(body)/2 {
- t.Errorf("on request, read buffer length is %d; expected about 100 KB", conn.readBuf.Len())
- }
- rw.WriteHeader(200)
- rw.(Flusher).Flush()
- if g, e := conn.readBuf.Len(), 0; g != e {
- t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e)
- }
- if c := rw.Header().Get("Connection"); c != "" {
- t.Errorf(`Connection header = %q; want ""`, c)
- }
- }))
- <-done
- }
- // Over a ~256KB (maxPostHandlerReadBytes) threshold, the server
- // should ignore client request bodies that a handler didn't read
- // and close the connection.
- func TestServerUnreadRequestBodyLarge(t *testing.T) {
- conn := new(testConn)
- body := strings.Repeat("x", 1<<20)
- conn.readBuf.Write([]byte(fmt.Sprintf(
- "POST / HTTP/1.1\r\n"+
- "Host: test\r\n"+
- "Content-Length: %d\r\n"+
- "\r\n", len(body))))
- conn.readBuf.Write([]byte(body))
- conn.closec = make(chan bool, 1)
- ls := &oneConnListener{conn}
- go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
- if conn.readBuf.Len() < len(body)/2 {
- t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
- }
- rw.WriteHeader(200)
- rw.(Flusher).Flush()
- if conn.readBuf.Len() < len(body)/2 {
- t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
- }
- }))
- <-conn.closec
- if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") {
- t.Errorf("Expected a Connection: close header; got response: %s", res)
- }
- }
- type handlerBodyCloseTest struct {
- bodySize int
- bodyChunked bool
- reqConnClose bool
- wantEOFSearch bool // should Handler's Body.Close do Reads, looking for EOF?
- wantNextReq bool // should it find the next request on the same conn?
- }
- func (t handlerBodyCloseTest) connectionHeader() string {
- if t.reqConnClose {
- return "Connection: close\r\n"
- }
- return ""
- }
- var handlerBodyCloseTests = [...]handlerBodyCloseTest{
- // Small enough to slurp past to the next request +
- // has Content-Length.
- 0: {
- bodySize: 20 << 10,
- bodyChunked: false,
- reqConnClose: false,
- wantEOFSearch: true,
- wantNextReq: true,
- },
- // Small enough to slurp past to the next request +
- // is chunked.
- 1: {
- bodySize: 20 << 10,
- bodyChunked: true,
- reqConnClose: false,
- wantEOFSearch: true,
- wantNextReq: true,
- },
- // Small enough to slurp past to the next request +
- // has Content-Length +
- // declares Connection: close (so pointless to read more).
- 2: {
- bodySize: 20 << 10,
- bodyChunked: false,
- reqConnClose: true,
- wantEOFSearch: false,
- wantNextReq: false,
- },
- // Small enough to slurp past to the next request +
- // declares Connection: close,
- // but chunked, so it might have trailers.
- // TODO: maybe skip this search if no trailers were declared
- // in the headers.
- 3: {
- bodySize: 20 << 10,
- bodyChunked: true,
- reqConnClose: true,
- wantEOFSearch: true,
- wantNextReq: false,
- },
- // Big with Content-Length, so give up immediately if we know it's too big.
- 4: {
- bodySize: 1 << 20,
- bodyChunked: false, // has a Content-Length
- reqConnClose: false,
- wantEOFSearch: false,
- wantNextReq: false,
- },
- // Big chunked, so read a bit before giving up.
- 5: {
- bodySize: 1 << 20,
- bodyChunked: true,
- reqConnClose: false,
- wantEOFSearch: true,
- wantNextReq: false,
- },
- // Big with Connection: close, but chunked, so search for trailers.
- // TODO: maybe skip this search if no trailers were declared
- // in the headers.
- 6: {
- bodySize: 1 << 20,
- bodyChunked: true,
- reqConnClose: true,
- wantEOFSearch: true,
- wantNextReq: false,
- },
- // Big with Connection: close, so don't do any reads on Close.
- // With Content-Length.
- 7: {
- bodySize: 1 << 20,
- bodyChunked: false,
- reqConnClose: true,
- wantEOFSearch: false,
- wantNextReq: false,
- },
- }
- func TestHandlerBodyClose(t *testing.T) {
- for i, tt := range handlerBodyCloseTests {
- testHandlerBodyClose(t, i, tt)
- }
- }
- func testHandlerBodyClose(t *testing.T, i int, tt handlerBodyCloseTest) {
- conn := new(testConn)
- body := strings.Repeat("x", tt.bodySize)
- if tt.bodyChunked {
- conn.readBuf.WriteString("POST / HTTP/1.1\r\n" +
- "Host: test\r\n" +
- tt.connectionHeader() +
- "Transfer-Encoding: chunked\r\n" +
- "\r\n")
- cw := internal.NewChunkedWriter(&conn.readBuf)
- io.WriteString(cw, body)
- cw.Close()
- conn.readBuf.WriteString("\r\n")
- } else {
- conn.readBuf.Write([]byte(fmt.Sprintf(
- "POST / HTTP/1.1\r\n"+
- "Host: test\r\n"+
- tt.connectionHeader()+
- "Content-Length: %d\r\n"+
- "\r\n", len(body))))
- conn.readBuf.Write([]byte(body))
- }
- if !tt.reqConnClose {
- conn.readBuf.WriteString("GET / HTTP/1.1\r\nHost: test\r\n\r\n")
- }
- conn.closec = make(chan bool, 1)
- ls := &oneConnListener{conn}
- var numReqs int
- var size0, size1 int
- go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
- numReqs++
- if numReqs == 1 {
- size0 = conn.readBuf.Len()
- req.Body.Close()
- size1 = conn.readBuf.Len()
- }
- }))
- <-conn.closec
- if numReqs < 1 || numReqs > 2 {
- t.Fatalf("%d. bug in test. unexpected number of requests = %d", i, numReqs)
- }
- didSearch := size0 != size1
- if didSearch != tt.wantEOFSearch {
- t.Errorf("%d. did EOF search = %v; want %v (size went from %d to %d)", i, didSearch, !didSearch, size0, size1)
- }
- if tt.wantNextReq && numReqs != 2 {
- t.Errorf("%d. numReq = %d; want 2", i, numReqs)
- }
- }
- // testHandlerBodyConsumer represents a function injected into a test handler to
- // vary work done on a request Body.
- type testHandlerBodyConsumer struct {
- name string
- f func(io.ReadCloser)
- }
- var testHandlerBodyConsumers = []testHandlerBodyConsumer{
- {"nil", func(io.ReadCloser) {}},
- {"close", func(r io.ReadCloser) { r.Close() }},
- {"discard", func(r io.ReadCloser) { io.Copy(ioutil.Discard, r) }},
- }
- func TestRequestBodyReadErrorClosesConnection(t *testing.T) {
- defer afterTest(t)
- for _, handler := range testHandlerBodyConsumers {
- conn := new(testConn)
- conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
- "Host: test\r\n" +
- "Transfer-Encoding: chunked\r\n" +
- "\r\n" +
- "hax\r\n" + // Invalid chunked encoding
- "GET /secret HTTP/1.1\r\n" +
- "Host: test\r\n" +
- "\r\n")
- conn.closec = make(chan bool, 1)
- ls := &oneConnListener{conn}
- var numReqs int
- go Serve(ls, HandlerFunc(func(_ ResponseWriter, req *Request) {
- numReqs++
- if strings.Contains(req.URL.Path, "secret") {
- t.Error("Request for /secret encountered, should not have happened.")
- }
- handler.f(req.Body)
- }))
- <-conn.closec
- if numReqs != 1 {
- t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
- }
- }
- }
- func TestInvalidTrailerClosesConnection(t *testing.T) {
- defer afterTest(t)
- for _, handler := range testHandlerBodyConsumers {
- conn := new(testConn)
- conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
- "Host: test\r\n" +
- "Trailer: hack\r\n" +
- "Transfer-Encoding: chunked\r\n" +
- "\r\n" +
- "3\r\n" +
- "hax\r\n" +
- "0\r\n" +
- "I'm not a valid trailer\r\n" +
- "GET /secret HTTP/1.1\r\n" +
- "Host: test\r\n" +
- "\r\n")
- conn.closec = make(chan bool, 1)
- ln := &oneConnListener{conn}
- var numReqs int
- go Serve(ln, HandlerFunc(func(_ ResponseWriter, req *Request) {
- numReqs++
- if strings.Contains(req.URL.Path, "secret") {
- t.Errorf("Handler %s, Request for /secret encountered, should not have happened.", handler.name)
- }
- handler.f(req.Body)
- }))
- <-conn.closec
- if numReqs != 1 {
- t.Errorf("Handler %s: got %d reqs; want 1", handler.name, numReqs)
- }
- }
- }
- // slowTestConn is a net.Conn that provides a means to simulate parts of a
- // request being received piecemeal. Deadlines can be set and enforced in both
- // Read and Write.
- type slowTestConn struct {
- // over multiple calls to Read, time.Durations are slept, strings are read.
- script []interface{}
- closec chan bool
- rd, wd time.Time // read, write deadline
- noopConn
- }
- func (c *slowTestConn) SetDeadline(t time.Time) error {
- c.SetReadDeadline(t)
- c.SetWriteDeadline(t)
- return nil
- }
- func (c *slowTestConn) SetReadDeadline(t time.Time) error {
- c.rd = t
- return nil
- }
- func (c *slowTestConn) SetWriteDeadline(t time.Time) error {
- c.wd = t
- return nil
- }
- func (c *slowTestConn) Read(b []byte) (n int, err error) {
- restart:
- if !c.rd.IsZero() && time.Now().After(c.rd) {
- return 0, syscall.ETIMEDOUT
- }
- if len(c.script) == 0 {
- return 0, io.EOF
- }
- switch cue := c.script[0].(type) {
- case time.Duration:
- if !c.rd.IsZero() {
- // If the deadline falls in the middle of our sleep window, deduct
- // part of the sleep, then return a timeout.
- if remaining := c.rd.Sub(time.Now()); remaining < cue {
- c.script[0] = cue - remaining
- time.Sleep(remaining)
- return 0, syscall.ETIMEDOUT
- }
- }
- c.script = c.script[1:]
- time.Sleep(cue)
- goto restart
- case string:
- n = copy(b, cue)
- // If cue is too big for the buffer, leave the end for the next Read.
- if len(cue) > n {
- c.script[0] = cue[n:]
- } else {
- c.script = c.script[1:]
- }
- default:
- panic("unknown cue in slowTestConn script")
- }
- return
- }
- func (c *slowTestConn) Close() error {
- select {
- case c.closec <- true:
- default:
- }
- return nil
- }
- func (c *slowTestConn) Write(b []byte) (int, error) {
- if !c.wd.IsZero() && time.Now().After(c.wd) {
- return 0, syscall.ETIMEDOUT
- }
- return len(b), nil
- }
- func TestRequestBodyTimeoutClosesConnection(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping in -short mode")
- }
- defer afterTest(t)
- for _, handler := range testHandlerBodyConsumers {
- conn := &slowTestConn{
- script: []interface{}{
- "POST /public HTTP/1.1\r\n" +
- "Host: test\r\n" +
- "Content-Length: 10000\r\n" +
- "\r\n",
- "foo bar baz",
- 600 * time.Millisecond, // Request deadline should hit here
- "GET /secret HTTP/1.1\r\n" +
- "Host: test\r\n" +
- "\r\n",
- },
- closec: make(chan bool, 1),
- }
- ls := &oneConnListener{conn}
- var numReqs int
- s := Server{
- Handler: HandlerFunc(func(_ ResponseWriter, req *Request) {
- numReqs++
- if strings.Contains(req.URL.Path, "secret") {
- t.Error("Request for /secret encountered, should not have happened.")
- }
- handler.f(req.Body)
- }),
- ReadTimeout: 400 * time.Millisecond,
- }
- go s.Serve(ls)
- <-conn.closec
- if numReqs != 1 {
- t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
- }
- }
- }
- func TestTimeoutHandler(t *testing.T) {
- defer afterTest(t)
- sendHi := make(chan bool, 1)
- writeErrors := make(chan error, 1)
- sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
- <-sendHi
- _, werr := w.Write([]byte("hi"))
- writeErrors <- werr
- })
- timeout := make(chan time.Time, 1) // write to this to force timeouts
- ts := httptest.NewServer(NewTestTimeoutHandler(sayHi, timeout))
- defer ts.Close()
- // Succeed without timing out:
- sendHi <- true
- res, err := Get(ts.URL)
- if err != nil {
- t.Error(err)
- }
- if g, e := res.StatusCode, StatusOK; g != e {
- t.Errorf("got res.StatusCode %d; expected %d", g, e)
- }
- body, _ := ioutil.ReadAll(res.Body)
- if g, e := string(body), "hi"; g != e {
- t.Errorf("got body %q; expected %q", g, e)
- }
- if g := <-writeErrors; g != nil {
- t.Errorf("got unexpected Write error on first request: %v", g)
- }
- // Times out:
- timeout <- time.Time{}
- res, err = Get(ts.URL)
- if err != nil {
- t.Error(err)
- }
- if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
- t.Errorf("got res.StatusCode %d; expected %d", g, e)
- }
- body, _ = ioutil.ReadAll(res.Body)
- if !strings.Contains(string(body), "<title>Timeout</title>") {
- t.Errorf("expected timeout body; got %q", string(body))
- }
- // Now make the previously-timed out handler speak again,
- // which verifies the panic is handled:
- sendHi <- true
- if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
- t.Errorf("expected Write error of %v; got %v", e, g)
- }
- }
- // See issues 8209 and 8414.
- func TestTimeoutHandlerRace(t *testing.T) {
- defer afterTest(t)
- delayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
- ms, _ := strconv.Atoi(r.URL.Path[1:])
- if ms == 0 {
- ms = 1
- }
- for i := 0; i < ms; i++ {
- w.Write([]byte("hi"))
- time.Sleep(time.Millisecond)
- }
- })
- ts := httptest.NewServer(TimeoutHandler(delayHi, 20*time.Millisecond, ""))
- defer ts.Close()
- var wg sync.WaitGroup
- gate := make(chan bool, 10)
- n := 50
- if testing.Short() {
- n = 10
- gate = make(chan bool, 3)
- }
- for i := 0; i < n; i++ {
- gate <- true
- wg.Add(1)
- go func() {
- defer wg.Done()
- defer func() { <-gate }()
- res, err := Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50)))
- if err == nil {
- io.Copy(ioutil.Discard, res.Body)
- res.Body.Close()
- }
- }()
- }
- wg.Wait()
- }
- // See issues 8209 and 8414.
- func TestTimeoutHandlerRaceHeader(t *testing.T) {
- defer afterTest(t)
- delay204 := HandlerFunc(func(w ResponseWriter, r *Request) {
- w.WriteHeader(204)
- })
- ts := httptest.NewServer(TimeoutHandler(delay204, time.Nanosecond, ""))
- defer ts.Close()
- var wg sync.WaitGroup
- gate := make(chan bool, 50)
- n := 500
- if testing.Short() {
- n = 10
- }
- for i := 0; i < n; i++ {
- gate <- true
- wg.Add(1)
- go func() {
- defer wg.Done()
- defer func() { <-gate }()
- res, err := Get(ts.URL)
- if err != nil {
- t.Error(err)
- return
- }
- defer res.Body.Close()
- io.Copy(ioutil.Discard, res.Body)
- }()
- }
- wg.Wait()
- }
- // Verifies we don't path.Clean() on the wrong parts in redirects.
- func TestRedirectMunging(t *testing.T) {
- req, _ := NewRequest("GET", "http://example.com/", nil)
- resp := httptest.NewRecorder()
- Redirect(resp, req, "/foo?next=http://bar.com/", 302)
- if g, e := resp.Header().Get("Location"), "/foo?next=http://bar.com/"; g != e {
- t.Errorf("Location header was %q; want %q", g, e)
- }
- resp = httptest.NewRecorder()
- Redirect(resp, req, "http://localhost:8080/_ah/login?continue=http://localhost:8080/", 302)
- if g, e := resp.Header().Get("Location"), "http://localhost:8080/_ah/login?continue=http://localhost:8080/"; g != e {
- t.Errorf("Location header was %q; want %q", g, e)
- }
- }
- func TestRedirectBadPath(t *testing.T) {
- // This used to crash. It's not valid input (bad path), but it
- // shouldn't crash.
- rr := httptest.NewRecorder()
- req := &Request{
- Method: "GET",
- URL: &url.URL{
- Scheme: "http",
- Path: "not-empty-but-no-leading-slash", // bogus
- },
- }
- Redirect(rr, req, "", 304)
- if rr.Code != 304 {
- t.Errorf("Code = %d; want 304", rr.Code)
- }
- }
- // TestZeroLengthPostAndResponse exercises an optimization done by the Transport:
- // when there is no body (either because the method doesn't permit a body, or an
- // explicit Content-Length of zero is present), then the transport can re-use the
- // connection immediately. But when it re-uses the connection, it typically closes
- // the previous request's body, which is not optimal for zero-lengthed bodies,
- // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF.
- func TestZeroLengthPostAndResponse(t *testing.T) {
- defer afterTest(t)
- ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
- all, err := ioutil.ReadAll(r.Body)
- if err != nil {
- t.Fatalf("handler ReadAll: %v", err)
- }
- if len(all) != 0 {
- t.Errorf("handler got %d bytes; expected 0", len(all))
- }
- rw.Header().Set("Content-Length", "0")
- }))
- defer ts.Close()
- req, err := NewRequest("POST", ts.URL, strings.NewReader(""))
- if err != nil {
- t.Fatal(err)
- }
- req.ContentLength = 0
- var resp [5]*Response
- for i := range resp {
- resp[i], err = DefaultClient.Do(req)
- if err != nil {
- t.Fatalf("client post #%d: %v", i, err)
- }
- }
- for i := range resp {
- all, err := ioutil.ReadAll(resp[i].Body)
- if err != nil {
- t.Fatalf("req #%d: client ReadAll: %v", i, err)
- }
- if len(all) != 0 {
- t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all))
- }
- }
- }
- func TestHandlerPanicNil(t *testing.T) {
- testHandlerPanic(t, false, nil)
- }
- func TestHandlerPanic(t *testing.T) {
- testHandlerPanic(t, false, "intentional death for testing")
- }
- func TestHandlerPanicWithHijack(t *testing.T) {
- testHandlerPanic(t, true, "intentional death for testing")
- }
- func testHandlerPanic(t *testing.T, withHijack bool, panicValue interface{}) {
- defer afterTest(t)
- // Unlike the other tests that set the log output to ioutil.Discard
- // to quiet the output, this test uses a pipe. The pipe serves three
- // purposes:
- //
- // 1) The log.Print from the http server (generated by the caught
- // panic) will go to the pipe instead of stderr, making the
- // output quiet.
- //
- // 2) We read from the pipe to verify that the handler
- // actually caught the panic and logged something.
- //
- // 3) The blocking Read call prevents this TestHandlerPanic
- // function from exiting before the HTTP server handler
- // finishes crashing. If this text function exited too
- // early (and its defer log.SetOutput(os.Stderr) ran),
- // then the crash output could spill into the next test.
- pr, pw := io.Pipe()
- log.SetOutput(pw)
- defer log.SetOutput(os.Stderr)
- defer pw.Close()
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- if withHijack {
- rwc, _, err := w.(Hijacker).Hijack()
- if err != nil {
- t.Logf("unexpected error: %v", err)
- }
- defer rwc.Close()
- }
- panic(panicValue)
- }))
- defer ts.Close()
- // Do a blocking read on the log output pipe so its logging
- // doesn't bleed into the next test. But wait only 5 seconds
- // for it.
- done := make(chan bool, 1)
- go func() {
- buf := make([]byte, 4<<10)
- _, err := pr.Read(buf)
- pr.Close()
- if err != nil && err != io.EOF {
- t.Error(err)
- }
- done <- true
- }()
- _, err := Get(ts.URL)
- if err == nil {
- t.Logf("expected an error")
- }
- if panicValue == nil {
- return
- }
- select {
- case <-done:
- return
- case <-time.After(5 * time.Second):
- t.Fatal("expected server handler to log an error")
- }
- }
- func TestServerNoDate(t *testing.T) { testServerNoHeader(t, "Date") }
- func TestServerNoContentType(t *testing.T) { testServerNoHeader(t, "Content-Type") }
- func testServerNoHeader(t *testing.T, header string) {
- defer afterTest(t)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- w.Header()[header] = nil
- io.WriteString(w, "<html>foo</html>") // non-empty
- }))
- defer ts.Close()
- res, err := Get(ts.URL)
- if err != nil {
- t.Fatal(err)
- }
- res.Body.Close()
- if got, ok := res.Header[header]; ok {
- t.Fatalf("Expected no %s header; got %q", header, got)
- }
- }
- func TestStripPrefix(t *testing.T) {
- defer afterTest(t)
- h := HandlerFunc(func(w ResponseWriter, r *Request) {
- w.Header().Set("X-Path", r.URL.Path)
- })
- ts := httptest.NewServer(StripPrefix("/foo", h))
- defer ts.Close()
- res, err := Get(ts.URL + "/foo/bar")
- if err != nil {
- t.Fatal(err)
- }
- if g, e := res.Header.Get("X-Path"), "/bar"; g != e {
- t.Errorf("test 1: got %s, want %s", g, e)
- }
- res.Body.Close()
- res, err = Get(ts.URL + "/bar")
- if err != nil {
- t.Fatal(err)
- }
- if g, e := res.StatusCode, 404; g != e {
- t.Errorf("test 2: got status %v, want %v", g, e)
- }
- res.Body.Close()
- }
- func TestRequestLimit(t *testing.T) {
- defer afterTest(t)
- ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
- t.Fatalf("didn't expect to get request in Handler")
- }))
- defer ts.Close()
- req, _ := NewRequest("GET", ts.URL, nil)
- var b…
Large files files are truncated, but you can click here to view the full file