...
Run Format

Source file src/net/http/serve_test.go

Documentation: net/http

     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  	"compress/gzip"
    13  	"context"
    14  	"crypto/tls"
    15  	"encoding/json"
    16  	"errors"
    17  	"fmt"
    18  	"internal/testenv"
    19  	"io"
    20  	"io/ioutil"
    21  	"log"
    22  	"math/rand"
    23  	"net"
    24  	. "net/http"
    25  	"net/http/httptest"
    26  	"net/http/httputil"
    27  	"net/http/internal"
    28  	"net/url"
    29  	"os"
    30  	"os/exec"
    31  	"reflect"
    32  	"runtime"
    33  	"runtime/debug"
    34  	"sort"
    35  	"strconv"
    36  	"strings"
    37  	"sync"
    38  	"sync/atomic"
    39  	"syscall"
    40  	"testing"
    41  	"time"
    42  )
    43  
    44  type dummyAddr string
    45  type oneConnListener struct {
    46  	conn net.Conn
    47  }
    48  
    49  func (l *oneConnListener) Accept() (c net.Conn, err error) {
    50  	c = l.conn
    51  	if c == nil {
    52  		err = io.EOF
    53  		return
    54  	}
    55  	err = nil
    56  	l.conn = nil
    57  	return
    58  }
    59  
    60  func (l *oneConnListener) Close() error {
    61  	return nil
    62  }
    63  
    64  func (l *oneConnListener) Addr() net.Addr {
    65  	return dummyAddr("test-address")
    66  }
    67  
    68  func (a dummyAddr) Network() string {
    69  	return string(a)
    70  }
    71  
    72  func (a dummyAddr) String() string {
    73  	return string(a)
    74  }
    75  
    76  type noopConn struct{}
    77  
    78  func (noopConn) LocalAddr() net.Addr                { return dummyAddr("local-addr") }
    79  func (noopConn) RemoteAddr() net.Addr               { return dummyAddr("remote-addr") }
    80  func (noopConn) SetDeadline(t time.Time) error      { return nil }
    81  func (noopConn) SetReadDeadline(t time.Time) error  { return nil }
    82  func (noopConn) SetWriteDeadline(t time.Time) error { return nil }
    83  
    84  type rwTestConn struct {
    85  	io.Reader
    86  	io.Writer
    87  	noopConn
    88  
    89  	closeFunc func() error // called if non-nil
    90  	closec    chan bool    // else, if non-nil, send value to it on close
    91  }
    92  
    93  func (c *rwTestConn) Close() error {
    94  	if c.closeFunc != nil {
    95  		return c.closeFunc()
    96  	}
    97  	select {
    98  	case c.closec <- true:
    99  	default:
   100  	}
   101  	return nil
   102  }
   103  
   104  type testConn struct {
   105  	readMu   sync.Mutex // for TestHandlerBodyClose
   106  	readBuf  bytes.Buffer
   107  	writeBuf bytes.Buffer
   108  	closec   chan bool // if non-nil, send value to it on close
   109  	noopConn
   110  }
   111  
   112  func (c *testConn) Read(b []byte) (int, error) {
   113  	c.readMu.Lock()
   114  	defer c.readMu.Unlock()
   115  	return c.readBuf.Read(b)
   116  }
   117  
   118  func (c *testConn) Write(b []byte) (int, error) {
   119  	return c.writeBuf.Write(b)
   120  }
   121  
   122  func (c *testConn) Close() error {
   123  	select {
   124  	case c.closec <- true:
   125  	default:
   126  	}
   127  	return nil
   128  }
   129  
   130  // reqBytes treats req as a request (with \n delimiters) and returns it with \r\n delimiters,
   131  // ending in \r\n\r\n
   132  func reqBytes(req string) []byte {
   133  	return []byte(strings.Replace(strings.TrimSpace(req), "\n", "\r\n", -1) + "\r\n\r\n")
   134  }
   135  
   136  type handlerTest struct {
   137  	logbuf  bytes.Buffer
   138  	handler Handler
   139  }
   140  
   141  func newHandlerTest(h Handler) handlerTest {
   142  	return handlerTest{handler: h}
   143  }
   144  
   145  func (ht *handlerTest) rawResponse(req string) string {
   146  	reqb := reqBytes(req)
   147  	var output bytes.Buffer
   148  	conn := &rwTestConn{
   149  		Reader: bytes.NewReader(reqb),
   150  		Writer: &output,
   151  		closec: make(chan bool, 1),
   152  	}
   153  	ln := &oneConnListener{conn: conn}
   154  	srv := &Server{
   155  		ErrorLog: log.New(&ht.logbuf, "", 0),
   156  		Handler:  ht.handler,
   157  	}
   158  	go srv.Serve(ln)
   159  	<-conn.closec
   160  	return output.String()
   161  }
   162  
   163  func TestConsumingBodyOnNextConn(t *testing.T) {
   164  	t.Parallel()
   165  	defer afterTest(t)
   166  	conn := new(testConn)
   167  	for i := 0; i < 2; i++ {
   168  		conn.readBuf.Write([]byte(
   169  			"POST / HTTP/1.1\r\n" +
   170  				"Host: test\r\n" +
   171  				"Content-Length: 11\r\n" +
   172  				"\r\n" +
   173  				"foo=1&bar=1"))
   174  	}
   175  
   176  	reqNum := 0
   177  	ch := make(chan *Request)
   178  	servech := make(chan error)
   179  	listener := &oneConnListener{conn}
   180  	handler := func(res ResponseWriter, req *Request) {
   181  		reqNum++
   182  		ch <- req
   183  	}
   184  
   185  	go func() {
   186  		servech <- Serve(listener, HandlerFunc(handler))
   187  	}()
   188  
   189  	var req *Request
   190  	req = <-ch
   191  	if req == nil {
   192  		t.Fatal("Got nil first request.")
   193  	}
   194  	if req.Method != "POST" {
   195  		t.Errorf("For request #1's method, got %q; expected %q",
   196  			req.Method, "POST")
   197  	}
   198  
   199  	req = <-ch
   200  	if req == nil {
   201  		t.Fatal("Got nil first request.")
   202  	}
   203  	if req.Method != "POST" {
   204  		t.Errorf("For request #2's method, got %q; expected %q",
   205  			req.Method, "POST")
   206  	}
   207  
   208  	if serveerr := <-servech; serveerr != io.EOF {
   209  		t.Errorf("Serve returned %q; expected EOF", serveerr)
   210  	}
   211  }
   212  
   213  type stringHandler string
   214  
   215  func (s stringHandler) ServeHTTP(w ResponseWriter, r *Request) {
   216  	w.Header().Set("Result", string(s))
   217  }
   218  
   219  var handlers = []struct {
   220  	pattern string
   221  	msg     string
   222  }{
   223  	{"/", "Default"},
   224  	{"/someDir/", "someDir"},
   225  	{"/#/", "hash"},
   226  	{"someHost.com/someDir/", "someHost.com/someDir"},
   227  }
   228  
   229  var vtests = []struct {
   230  	url      string
   231  	expected string
   232  }{
   233  	{"http://localhost/someDir/apage", "someDir"},
   234  	{"http://localhost/%23/apage", "hash"},
   235  	{"http://localhost/otherDir/apage", "Default"},
   236  	{"http://someHost.com/someDir/apage", "someHost.com/someDir"},
   237  	{"http://otherHost.com/someDir/apage", "someDir"},
   238  	{"http://otherHost.com/aDir/apage", "Default"},
   239  	// redirections for trees
   240  	{"http://localhost/someDir", "/someDir/"},
   241  	{"http://localhost/%23", "/%23/"},
   242  	{"http://someHost.com/someDir", "/someDir/"},
   243  }
   244  
   245  func TestHostHandlers(t *testing.T) {
   246  	setParallel(t)
   247  	defer afterTest(t)
   248  	mux := NewServeMux()
   249  	for _, h := range handlers {
   250  		mux.Handle(h.pattern, stringHandler(h.msg))
   251  	}
   252  	ts := httptest.NewServer(mux)
   253  	defer ts.Close()
   254  
   255  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
   256  	if err != nil {
   257  		t.Fatal(err)
   258  	}
   259  	defer conn.Close()
   260  	cc := httputil.NewClientConn(conn, nil)
   261  	for _, vt := range vtests {
   262  		var r *Response
   263  		var req Request
   264  		if req.URL, err = url.Parse(vt.url); err != nil {
   265  			t.Errorf("cannot parse url: %v", err)
   266  			continue
   267  		}
   268  		if err := cc.Write(&req); err != nil {
   269  			t.Errorf("writing request: %v", err)
   270  			continue
   271  		}
   272  		r, err := cc.Read(&req)
   273  		if err != nil {
   274  			t.Errorf("reading response: %v", err)
   275  			continue
   276  		}
   277  		switch r.StatusCode {
   278  		case StatusOK:
   279  			s := r.Header.Get("Result")
   280  			if s != vt.expected {
   281  				t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
   282  			}
   283  		case StatusMovedPermanently:
   284  			s := r.Header.Get("Location")
   285  			if s != vt.expected {
   286  				t.Errorf("Get(%q) = %q, want %q", vt.url, s, vt.expected)
   287  			}
   288  		default:
   289  			t.Errorf("Get(%q) unhandled status code %d", vt.url, r.StatusCode)
   290  		}
   291  	}
   292  }
   293  
   294  var serveMuxRegister = []struct {
   295  	pattern string
   296  	h       Handler
   297  }{
   298  	{"/dir/", serve(200)},
   299  	{"/search", serve(201)},
   300  	{"codesearch.google.com/search", serve(202)},
   301  	{"codesearch.google.com/", serve(203)},
   302  	{"example.com/", HandlerFunc(checkQueryStringHandler)},
   303  }
   304  
   305  // serve returns a handler that sends a response with the given code.
   306  func serve(code int) HandlerFunc {
   307  	return func(w ResponseWriter, r *Request) {
   308  		w.WriteHeader(code)
   309  	}
   310  }
   311  
   312  // checkQueryStringHandler checks if r.URL.RawQuery has the same value
   313  // as the URL excluding the scheme and the query string and sends 200
   314  // response code if it is, 500 otherwise.
   315  func checkQueryStringHandler(w ResponseWriter, r *Request) {
   316  	u := *r.URL
   317  	u.Scheme = "http"
   318  	u.Host = r.Host
   319  	u.RawQuery = ""
   320  	if "http://"+r.URL.RawQuery == u.String() {
   321  		w.WriteHeader(200)
   322  	} else {
   323  		w.WriteHeader(500)
   324  	}
   325  }
   326  
   327  var serveMuxTests = []struct {
   328  	method  string
   329  	host    string
   330  	path    string
   331  	code    int
   332  	pattern string
   333  }{
   334  	{"GET", "google.com", "/", 404, ""},
   335  	{"GET", "google.com", "/dir", 301, "/dir/"},
   336  	{"GET", "google.com", "/dir/", 200, "/dir/"},
   337  	{"GET", "google.com", "/dir/file", 200, "/dir/"},
   338  	{"GET", "google.com", "/search", 201, "/search"},
   339  	{"GET", "google.com", "/search/", 404, ""},
   340  	{"GET", "google.com", "/search/foo", 404, ""},
   341  	{"GET", "codesearch.google.com", "/search", 202, "codesearch.google.com/search"},
   342  	{"GET", "codesearch.google.com", "/search/", 203, "codesearch.google.com/"},
   343  	{"GET", "codesearch.google.com", "/search/foo", 203, "codesearch.google.com/"},
   344  	{"GET", "codesearch.google.com", "/", 203, "codesearch.google.com/"},
   345  	{"GET", "codesearch.google.com:443", "/", 203, "codesearch.google.com/"},
   346  	{"GET", "images.google.com", "/search", 201, "/search"},
   347  	{"GET", "images.google.com", "/search/", 404, ""},
   348  	{"GET", "images.google.com", "/search/foo", 404, ""},
   349  	{"GET", "google.com", "/../search", 301, "/search"},
   350  	{"GET", "google.com", "/dir/..", 301, ""},
   351  	{"GET", "google.com", "/dir/..", 301, ""},
   352  	{"GET", "google.com", "/dir/./file", 301, "/dir/"},
   353  
   354  	// The /foo -> /foo/ redirect applies to CONNECT requests
   355  	// but the path canonicalization does not.
   356  	{"CONNECT", "google.com", "/dir", 301, "/dir/"},
   357  	{"CONNECT", "google.com", "/../search", 404, ""},
   358  	{"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
   359  	{"CONNECT", "google.com", "/dir/..", 200, "/dir/"},
   360  	{"CONNECT", "google.com", "/dir/./file", 200, "/dir/"},
   361  }
   362  
   363  func TestServeMuxHandler(t *testing.T) {
   364  	setParallel(t)
   365  	mux := NewServeMux()
   366  	for _, e := range serveMuxRegister {
   367  		mux.Handle(e.pattern, e.h)
   368  	}
   369  
   370  	for _, tt := range serveMuxTests {
   371  		r := &Request{
   372  			Method: tt.method,
   373  			Host:   tt.host,
   374  			URL: &url.URL{
   375  				Path: tt.path,
   376  			},
   377  		}
   378  		h, pattern := mux.Handler(r)
   379  		rr := httptest.NewRecorder()
   380  		h.ServeHTTP(rr, r)
   381  		if pattern != tt.pattern || rr.Code != tt.code {
   382  			t.Errorf("%s %s %s = %d, %q, want %d, %q", tt.method, tt.host, tt.path, rr.Code, pattern, tt.code, tt.pattern)
   383  		}
   384  	}
   385  }
   386  
   387  // Issue 24297
   388  func TestServeMuxHandleFuncWithNilHandler(t *testing.T) {
   389  	setParallel(t)
   390  	defer func() {
   391  		if err := recover(); err == nil {
   392  			t.Error("expected call to mux.HandleFunc to panic")
   393  		}
   394  	}()
   395  	mux := NewServeMux()
   396  	mux.HandleFunc("/", nil)
   397  }
   398  
   399  var serveMuxTests2 = []struct {
   400  	method  string
   401  	host    string
   402  	url     string
   403  	code    int
   404  	redirOk bool
   405  }{
   406  	{"GET", "google.com", "/", 404, false},
   407  	{"GET", "example.com", "/test/?example.com/test/", 200, false},
   408  	{"GET", "example.com", "test/?example.com/test/", 200, true},
   409  }
   410  
   411  // TestServeMuxHandlerRedirects tests that automatic redirects generated by
   412  // mux.Handler() shouldn't clear the request's query string.
   413  func TestServeMuxHandlerRedirects(t *testing.T) {
   414  	setParallel(t)
   415  	mux := NewServeMux()
   416  	for _, e := range serveMuxRegister {
   417  		mux.Handle(e.pattern, e.h)
   418  	}
   419  
   420  	for _, tt := range serveMuxTests2 {
   421  		tries := 1 // expect at most 1 redirection if redirOk is true.
   422  		turl := tt.url
   423  		for {
   424  			u, e := url.Parse(turl)
   425  			if e != nil {
   426  				t.Fatal(e)
   427  			}
   428  			r := &Request{
   429  				Method: tt.method,
   430  				Host:   tt.host,
   431  				URL:    u,
   432  			}
   433  			h, _ := mux.Handler(r)
   434  			rr := httptest.NewRecorder()
   435  			h.ServeHTTP(rr, r)
   436  			if rr.Code != 301 {
   437  				if rr.Code != tt.code {
   438  					t.Errorf("%s %s %s = %d, want %d", tt.method, tt.host, tt.url, rr.Code, tt.code)
   439  				}
   440  				break
   441  			}
   442  			if !tt.redirOk {
   443  				t.Errorf("%s %s %s, unexpected redirect", tt.method, tt.host, tt.url)
   444  				break
   445  			}
   446  			turl = rr.HeaderMap.Get("Location")
   447  			tries--
   448  		}
   449  		if tries < 0 {
   450  			t.Errorf("%s %s %s, too many redirects", tt.method, tt.host, tt.url)
   451  		}
   452  	}
   453  }
   454  
   455  // Tests for https://golang.org/issue/900
   456  func TestMuxRedirectLeadingSlashes(t *testing.T) {
   457  	setParallel(t)
   458  	paths := []string{"//foo.txt", "///foo.txt", "/../../foo.txt"}
   459  	for _, path := range paths {
   460  		req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET " + path + " HTTP/1.1\r\nHost: test\r\n\r\n")))
   461  		if err != nil {
   462  			t.Errorf("%s", err)
   463  		}
   464  		mux := NewServeMux()
   465  		resp := httptest.NewRecorder()
   466  
   467  		mux.ServeHTTP(resp, req)
   468  
   469  		if loc, expected := resp.Header().Get("Location"), "/foo.txt"; loc != expected {
   470  			t.Errorf("Expected Location header set to %q; got %q", expected, loc)
   471  			return
   472  		}
   473  
   474  		if code, expected := resp.Code, StatusMovedPermanently; code != expected {
   475  			t.Errorf("Expected response code of StatusMovedPermanently; got %d", code)
   476  			return
   477  		}
   478  	}
   479  }
   480  
   481  // Test that the special cased "/route" redirect
   482  // implicitly created by a registered "/route/"
   483  // properly sets the query string in the redirect URL.
   484  // See Issue 17841.
   485  func TestServeWithSlashRedirectKeepsQueryString(t *testing.T) {
   486  	setParallel(t)
   487  	defer afterTest(t)
   488  
   489  	writeBackQuery := func(w ResponseWriter, r *Request) {
   490  		fmt.Fprintf(w, "%s", r.URL.RawQuery)
   491  	}
   492  
   493  	mux := NewServeMux()
   494  	mux.HandleFunc("/testOne", writeBackQuery)
   495  	mux.HandleFunc("/testTwo/", writeBackQuery)
   496  	mux.HandleFunc("/testThree", writeBackQuery)
   497  	mux.HandleFunc("/testThree/", func(w ResponseWriter, r *Request) {
   498  		fmt.Fprintf(w, "%s:bar", r.URL.RawQuery)
   499  	})
   500  
   501  	ts := httptest.NewServer(mux)
   502  	defer ts.Close()
   503  
   504  	tests := [...]struct {
   505  		path     string
   506  		method   string
   507  		want     string
   508  		statusOk bool
   509  	}{
   510  		0: {"/testOne?this=that", "GET", "this=that", true},
   511  		1: {"/testTwo?foo=bar", "GET", "foo=bar", true},
   512  		2: {"/testTwo?a=1&b=2&a=3", "GET", "a=1&b=2&a=3", true},
   513  		3: {"/testTwo?", "GET", "", true},
   514  		4: {"/testThree?foo", "GET", "foo", true},
   515  		5: {"/testThree/?foo", "GET", "foo:bar", true},
   516  		6: {"/testThree?foo", "CONNECT", "foo", true},
   517  		7: {"/testThree/?foo", "CONNECT", "foo:bar", true},
   518  
   519  		// canonicalization or not
   520  		8: {"/testOne/foo/..?foo", "GET", "foo", true},
   521  		9: {"/testOne/foo/..?foo", "CONNECT", "404 page not found\n", false},
   522  	}
   523  
   524  	for i, tt := range tests {
   525  		req, _ := NewRequest(tt.method, ts.URL+tt.path, nil)
   526  		res, err := ts.Client().Do(req)
   527  		if err != nil {
   528  			continue
   529  		}
   530  		slurp, _ := ioutil.ReadAll(res.Body)
   531  		res.Body.Close()
   532  		if !tt.statusOk {
   533  			if got, want := res.StatusCode, 404; got != want {
   534  				t.Errorf("#%d: Status = %d; want = %d", i, got, want)
   535  			}
   536  		}
   537  		if got, want := string(slurp), tt.want; got != want {
   538  			t.Errorf("#%d: Body = %q; want = %q", i, got, want)
   539  		}
   540  	}
   541  }
   542  
   543  func TestServeWithSlashRedirectForHostPatterns(t *testing.T) {
   544  	setParallel(t)
   545  	defer afterTest(t)
   546  
   547  	mux := NewServeMux()
   548  	mux.Handle("example.com/pkg/foo/", stringHandler("example.com/pkg/foo/"))
   549  	mux.Handle("example.com/pkg/bar", stringHandler("example.com/pkg/bar"))
   550  	mux.Handle("example.com/pkg/bar/", stringHandler("example.com/pkg/bar/"))
   551  	mux.Handle("example.com:3000/pkg/connect/", stringHandler("example.com:3000/pkg/connect/"))
   552  	mux.Handle("example.com:9000/", stringHandler("example.com:9000/"))
   553  	mux.Handle("/pkg/baz/", stringHandler("/pkg/baz/"))
   554  
   555  	tests := []struct {
   556  		method string
   557  		url    string
   558  		code   int
   559  		loc    string
   560  		want   string
   561  	}{
   562  		{"GET", "http://example.com/", 404, "", ""},
   563  		{"GET", "http://example.com/pkg/foo", 301, "/pkg/foo/", ""},
   564  		{"GET", "http://example.com/pkg/bar", 200, "", "example.com/pkg/bar"},
   565  		{"GET", "http://example.com/pkg/bar/", 200, "", "example.com/pkg/bar/"},
   566  		{"GET", "http://example.com/pkg/baz", 301, "/pkg/baz/", ""},
   567  		{"GET", "http://example.com:3000/pkg/foo", 301, "/pkg/foo/", ""},
   568  		{"CONNECT", "http://example.com/", 404, "", ""},
   569  		{"CONNECT", "http://example.com:3000/", 404, "", ""},
   570  		{"CONNECT", "http://example.com:9000/", 200, "", "example.com:9000/"},
   571  		{"CONNECT", "http://example.com/pkg/foo", 301, "/pkg/foo/", ""},
   572  		{"CONNECT", "http://example.com:3000/pkg/foo", 404, "", ""},
   573  		{"CONNECT", "http://example.com:3000/pkg/baz", 301, "/pkg/baz/", ""},
   574  		{"CONNECT", "http://example.com:3000/pkg/connect", 301, "/pkg/connect/", ""},
   575  	}
   576  
   577  	ts := httptest.NewServer(mux)
   578  	defer ts.Close()
   579  
   580  	for i, tt := range tests {
   581  		req, _ := NewRequest(tt.method, tt.url, nil)
   582  		w := httptest.NewRecorder()
   583  		mux.ServeHTTP(w, req)
   584  
   585  		if got, want := w.Code, tt.code; got != want {
   586  			t.Errorf("#%d: Status = %d; want = %d", i, got, want)
   587  		}
   588  
   589  		if tt.code == 301 {
   590  			if got, want := w.HeaderMap.Get("Location"), tt.loc; got != want {
   591  				t.Errorf("#%d: Location = %q; want = %q", i, got, want)
   592  			}
   593  		} else {
   594  			if got, want := w.HeaderMap.Get("Result"), tt.want; got != want {
   595  				t.Errorf("#%d: Result = %q; want = %q", i, got, want)
   596  			}
   597  		}
   598  	}
   599  }
   600  
   601  func TestShouldRedirectConcurrency(t *testing.T) {
   602  	setParallel(t)
   603  	defer afterTest(t)
   604  
   605  	mux := NewServeMux()
   606  	ts := httptest.NewServer(mux)
   607  	defer ts.Close()
   608  	mux.HandleFunc("/", func(w ResponseWriter, r *Request) {})
   609  }
   610  
   611  func BenchmarkServeMux(b *testing.B)           { benchmarkServeMux(b, true) }
   612  func BenchmarkServeMux_SkipServe(b *testing.B) { benchmarkServeMux(b, false) }
   613  func benchmarkServeMux(b *testing.B, runHandler bool) {
   614  	type test struct {
   615  		path string
   616  		code int
   617  		req  *Request
   618  	}
   619  
   620  	// Build example handlers and requests
   621  	var tests []test
   622  	endpoints := []string{"search", "dir", "file", "change", "count", "s"}
   623  	for _, e := range endpoints {
   624  		for i := 200; i < 230; i++ {
   625  			p := fmt.Sprintf("/%s/%d/", e, i)
   626  			tests = append(tests, test{
   627  				path: p,
   628  				code: i,
   629  				req:  &Request{Method: "GET", Host: "localhost", URL: &url.URL{Path: p}},
   630  			})
   631  		}
   632  	}
   633  	mux := NewServeMux()
   634  	for _, tt := range tests {
   635  		mux.Handle(tt.path, serve(tt.code))
   636  	}
   637  
   638  	rw := httptest.NewRecorder()
   639  	b.ReportAllocs()
   640  	b.ResetTimer()
   641  	for i := 0; i < b.N; i++ {
   642  		for _, tt := range tests {
   643  			*rw = httptest.ResponseRecorder{}
   644  			h, pattern := mux.Handler(tt.req)
   645  			if runHandler {
   646  				h.ServeHTTP(rw, tt.req)
   647  				if pattern != tt.path || rw.Code != tt.code {
   648  					b.Fatalf("got %d, %q, want %d, %q", rw.Code, pattern, tt.code, tt.path)
   649  				}
   650  			}
   651  		}
   652  	}
   653  }
   654  
   655  func TestServerTimeouts(t *testing.T) {
   656  	setParallel(t)
   657  	defer afterTest(t)
   658  	// Try three times, with increasing timeouts.
   659  	tries := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second}
   660  	for i, timeout := range tries {
   661  		err := testServerTimeouts(timeout)
   662  		if err == nil {
   663  			return
   664  		}
   665  		t.Logf("failed at %v: %v", timeout, err)
   666  		if i != len(tries)-1 {
   667  			t.Logf("retrying at %v ...", tries[i+1])
   668  		}
   669  	}
   670  	t.Fatal("all attempts failed")
   671  }
   672  
   673  func testServerTimeouts(timeout time.Duration) error {
   674  	reqNum := 0
   675  	ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
   676  		reqNum++
   677  		fmt.Fprintf(res, "req=%d", reqNum)
   678  	}))
   679  	ts.Config.ReadTimeout = timeout
   680  	ts.Config.WriteTimeout = timeout
   681  	ts.Start()
   682  	defer ts.Close()
   683  
   684  	// Hit the HTTP server successfully.
   685  	c := ts.Client()
   686  	r, err := c.Get(ts.URL)
   687  	if err != nil {
   688  		return fmt.Errorf("http Get #1: %v", err)
   689  	}
   690  	got, err := ioutil.ReadAll(r.Body)
   691  	expected := "req=1"
   692  	if string(got) != expected || err != nil {
   693  		return fmt.Errorf("Unexpected response for request #1; got %q ,%v; expected %q, nil",
   694  			string(got), err, expected)
   695  	}
   696  
   697  	// Slow client that should timeout.
   698  	t1 := time.Now()
   699  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
   700  	if err != nil {
   701  		return fmt.Errorf("Dial: %v", err)
   702  	}
   703  	buf := make([]byte, 1)
   704  	n, err := conn.Read(buf)
   705  	conn.Close()
   706  	latency := time.Since(t1)
   707  	if n != 0 || err != io.EOF {
   708  		return fmt.Errorf("Read = %v, %v, wanted %v, %v", n, err, 0, io.EOF)
   709  	}
   710  	minLatency := timeout / 5 * 4
   711  	if latency < minLatency {
   712  		return fmt.Errorf("got EOF after %s, want >= %s", latency, minLatency)
   713  	}
   714  
   715  	// Hit the HTTP server successfully again, verifying that the
   716  	// previous slow connection didn't run our handler.  (that we
   717  	// get "req=2", not "req=3")
   718  	r, err = c.Get(ts.URL)
   719  	if err != nil {
   720  		return fmt.Errorf("http Get #2: %v", err)
   721  	}
   722  	got, err = ioutil.ReadAll(r.Body)
   723  	r.Body.Close()
   724  	expected = "req=2"
   725  	if string(got) != expected || err != nil {
   726  		return fmt.Errorf("Get #2 got %q, %v, want %q, nil", string(got), err, expected)
   727  	}
   728  
   729  	if !testing.Short() {
   730  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
   731  		if err != nil {
   732  			return fmt.Errorf("long Dial: %v", err)
   733  		}
   734  		defer conn.Close()
   735  		go io.Copy(ioutil.Discard, conn)
   736  		for i := 0; i < 5; i++ {
   737  			_, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
   738  			if err != nil {
   739  				return fmt.Errorf("on write %d: %v", i, err)
   740  			}
   741  			time.Sleep(timeout / 2)
   742  		}
   743  	}
   744  	return nil
   745  }
   746  
   747  // Test that the HTTP/2 server handles Server.WriteTimeout (Issue 18437)
   748  func TestHTTP2WriteDeadlineExtendedOnNewRequest(t *testing.T) {
   749  	if testing.Short() {
   750  		t.Skip("skipping in short mode")
   751  	}
   752  	setParallel(t)
   753  	defer afterTest(t)
   754  	ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {}))
   755  	ts.Config.WriteTimeout = 250 * time.Millisecond
   756  	ts.TLS = &tls.Config{NextProtos: []string{"h2"}}
   757  	ts.StartTLS()
   758  	defer ts.Close()
   759  
   760  	c := ts.Client()
   761  	if err := ExportHttp2ConfigureTransport(c.Transport.(*Transport)); err != nil {
   762  		t.Fatal(err)
   763  	}
   764  
   765  	for i := 1; i <= 3; i++ {
   766  		req, err := NewRequest("GET", ts.URL, nil)
   767  		if err != nil {
   768  			t.Fatal(err)
   769  		}
   770  
   771  		// fail test if no response after 1 second
   772  		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
   773  		defer cancel()
   774  		req = req.WithContext(ctx)
   775  
   776  		r, err := c.Do(req)
   777  		if ctx.Err() == context.DeadlineExceeded {
   778  			t.Fatalf("http2 Get #%d response timed out", i)
   779  		}
   780  		if err != nil {
   781  			t.Fatalf("http2 Get #%d: %v", i, err)
   782  		}
   783  		r.Body.Close()
   784  		if r.ProtoMajor != 2 {
   785  			t.Fatalf("http2 Get expected HTTP/2.0, got %q", r.Proto)
   786  		}
   787  		time.Sleep(ts.Config.WriteTimeout / 2)
   788  	}
   789  }
   790  
   791  // tryTimeouts runs testFunc with increasing timeouts. Test passes on first success,
   792  // and fails if all timeouts fail.
   793  func tryTimeouts(t *testing.T, testFunc func(timeout time.Duration) error) {
   794  	tries := []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second}
   795  	for i, timeout := range tries {
   796  		err := testFunc(timeout)
   797  		if err == nil {
   798  			return
   799  		}
   800  		t.Logf("failed at %v: %v", timeout, err)
   801  		if i != len(tries)-1 {
   802  			t.Logf("retrying at %v ...", tries[i+1])
   803  		}
   804  	}
   805  	t.Fatal("all attempts failed")
   806  }
   807  
   808  // Test that the HTTP/2 server RSTs stream on slow write.
   809  func TestHTTP2WriteDeadlineEnforcedPerStream(t *testing.T) {
   810  	if testing.Short() {
   811  		t.Skip("skipping in short mode")
   812  	}
   813  	setParallel(t)
   814  	defer afterTest(t)
   815  	tryTimeouts(t, testHTTP2WriteDeadlineEnforcedPerStream)
   816  }
   817  
   818  func testHTTP2WriteDeadlineEnforcedPerStream(timeout time.Duration) error {
   819  	reqNum := 0
   820  	ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
   821  		reqNum++
   822  		if reqNum == 1 {
   823  			return // first request succeeds
   824  		}
   825  		time.Sleep(timeout) // second request times out
   826  	}))
   827  	ts.Config.WriteTimeout = timeout / 2
   828  	ts.TLS = &tls.Config{NextProtos: []string{"h2"}}
   829  	ts.StartTLS()
   830  	defer ts.Close()
   831  
   832  	c := ts.Client()
   833  	if err := ExportHttp2ConfigureTransport(c.Transport.(*Transport)); err != nil {
   834  		return fmt.Errorf("ExportHttp2ConfigureTransport: %v", err)
   835  	}
   836  
   837  	req, err := NewRequest("GET", ts.URL, nil)
   838  	if err != nil {
   839  		return fmt.Errorf("NewRequest: %v", err)
   840  	}
   841  	r, err := c.Do(req)
   842  	if err != nil {
   843  		return fmt.Errorf("http2 Get #1: %v", err)
   844  	}
   845  	r.Body.Close()
   846  	if r.ProtoMajor != 2 {
   847  		return fmt.Errorf("http2 Get expected HTTP/2.0, got %q", r.Proto)
   848  	}
   849  
   850  	req, err = NewRequest("GET", ts.URL, nil)
   851  	if err != nil {
   852  		return fmt.Errorf("NewRequest: %v", err)
   853  	}
   854  	r, err = c.Do(req)
   855  	if err == nil {
   856  		r.Body.Close()
   857  		if r.ProtoMajor != 2 {
   858  			return fmt.Errorf("http2 Get expected HTTP/2.0, got %q", r.Proto)
   859  		}
   860  		return fmt.Errorf("http2 Get #2 expected error, got nil")
   861  	}
   862  	expected := "stream ID 3; INTERNAL_ERROR" // client IDs are odd, second stream should be 3
   863  	if !strings.Contains(err.Error(), expected) {
   864  		return fmt.Errorf("http2 Get #2: expected error to contain %q, got %q", expected, err)
   865  	}
   866  	return nil
   867  }
   868  
   869  // Test that the HTTP/2 server does not send RST when WriteDeadline not set.
   870  func TestHTTP2NoWriteDeadline(t *testing.T) {
   871  	if testing.Short() {
   872  		t.Skip("skipping in short mode")
   873  	}
   874  	setParallel(t)
   875  	defer afterTest(t)
   876  	tryTimeouts(t, testHTTP2NoWriteDeadline)
   877  }
   878  
   879  func testHTTP2NoWriteDeadline(timeout time.Duration) error {
   880  	reqNum := 0
   881  	ts := httptest.NewUnstartedServer(HandlerFunc(func(res ResponseWriter, req *Request) {
   882  		reqNum++
   883  		if reqNum == 1 {
   884  			return // first request succeeds
   885  		}
   886  		time.Sleep(timeout) // second request timesout
   887  	}))
   888  	ts.TLS = &tls.Config{NextProtos: []string{"h2"}}
   889  	ts.StartTLS()
   890  	defer ts.Close()
   891  
   892  	c := ts.Client()
   893  	if err := ExportHttp2ConfigureTransport(c.Transport.(*Transport)); err != nil {
   894  		return fmt.Errorf("ExportHttp2ConfigureTransport: %v", err)
   895  	}
   896  
   897  	for i := 0; i < 2; i++ {
   898  		req, err := NewRequest("GET", ts.URL, nil)
   899  		if err != nil {
   900  			return fmt.Errorf("NewRequest: %v", err)
   901  		}
   902  		r, err := c.Do(req)
   903  		if err != nil {
   904  			return fmt.Errorf("http2 Get #%d: %v", i, err)
   905  		}
   906  		r.Body.Close()
   907  		if r.ProtoMajor != 2 {
   908  			return fmt.Errorf("http2 Get expected HTTP/2.0, got %q", r.Proto)
   909  		}
   910  	}
   911  	return nil
   912  }
   913  
   914  // golang.org/issue/4741 -- setting only a write timeout that triggers
   915  // shouldn't cause a handler to block forever on reads (next HTTP
   916  // request) that will never happen.
   917  func TestOnlyWriteTimeout(t *testing.T) {
   918  	setParallel(t)
   919  	defer afterTest(t)
   920  	var (
   921  		mu   sync.RWMutex
   922  		conn net.Conn
   923  	)
   924  	var afterTimeoutErrc = make(chan error, 1)
   925  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, req *Request) {
   926  		buf := make([]byte, 512<<10)
   927  		_, err := w.Write(buf)
   928  		if err != nil {
   929  			t.Errorf("handler Write error: %v", err)
   930  			return
   931  		}
   932  		mu.RLock()
   933  		defer mu.RUnlock()
   934  		if conn == nil {
   935  			t.Error("no established connection found")
   936  			return
   937  		}
   938  		conn.SetWriteDeadline(time.Now().Add(-30 * time.Second))
   939  		_, err = w.Write(buf)
   940  		afterTimeoutErrc <- err
   941  	}))
   942  	ts.Listener = trackLastConnListener{ts.Listener, &mu, &conn}
   943  	ts.Start()
   944  	defer ts.Close()
   945  
   946  	c := ts.Client()
   947  
   948  	errc := make(chan error)
   949  	go func() {
   950  		res, err := c.Get(ts.URL)
   951  		if err != nil {
   952  			errc <- err
   953  			return
   954  		}
   955  		_, err = io.Copy(ioutil.Discard, res.Body)
   956  		res.Body.Close()
   957  		errc <- err
   958  	}()
   959  	select {
   960  	case err := <-errc:
   961  		if err == nil {
   962  			t.Errorf("expected an error from Get request")
   963  		}
   964  	case <-time.After(10 * time.Second):
   965  		t.Fatal("timeout waiting for Get error")
   966  	}
   967  	if err := <-afterTimeoutErrc; err == nil {
   968  		t.Error("expected write error after timeout")
   969  	}
   970  }
   971  
   972  // trackLastConnListener tracks the last net.Conn that was accepted.
   973  type trackLastConnListener struct {
   974  	net.Listener
   975  
   976  	mu   *sync.RWMutex
   977  	last *net.Conn // destination
   978  }
   979  
   980  func (l trackLastConnListener) Accept() (c net.Conn, err error) {
   981  	c, err = l.Listener.Accept()
   982  	if err == nil {
   983  		l.mu.Lock()
   984  		*l.last = c
   985  		l.mu.Unlock()
   986  	}
   987  	return
   988  }
   989  
   990  // TestIdentityResponse verifies that a handler can unset
   991  func TestIdentityResponse(t *testing.T) {
   992  	setParallel(t)
   993  	defer afterTest(t)
   994  	handler := HandlerFunc(func(rw ResponseWriter, req *Request) {
   995  		rw.Header().Set("Content-Length", "3")
   996  		rw.Header().Set("Transfer-Encoding", req.FormValue("te"))
   997  		switch {
   998  		case req.FormValue("overwrite") == "1":
   999  			_, err := rw.Write([]byte("foo TOO LONG"))
  1000  			if err != ErrContentLength {
  1001  				t.Errorf("expected ErrContentLength; got %v", err)
  1002  			}
  1003  		case req.FormValue("underwrite") == "1":
  1004  			rw.Header().Set("Content-Length", "500")
  1005  			rw.Write([]byte("too short"))
  1006  		default:
  1007  			rw.Write([]byte("foo"))
  1008  		}
  1009  	})
  1010  
  1011  	ts := httptest.NewServer(handler)
  1012  	defer ts.Close()
  1013  
  1014  	c := ts.Client()
  1015  
  1016  	// Note: this relies on the assumption (which is true) that
  1017  	// Get sends HTTP/1.1 or greater requests. Otherwise the
  1018  	// server wouldn't have the choice to send back chunked
  1019  	// responses.
  1020  	for _, te := range []string{"", "identity"} {
  1021  		url := ts.URL + "/?te=" + te
  1022  		res, err := c.Get(url)
  1023  		if err != nil {
  1024  			t.Fatalf("error with Get of %s: %v", url, err)
  1025  		}
  1026  		if cl, expected := res.ContentLength, int64(3); cl != expected {
  1027  			t.Errorf("for %s expected res.ContentLength of %d; got %d", url, expected, cl)
  1028  		}
  1029  		if cl, expected := res.Header.Get("Content-Length"), "3"; cl != expected {
  1030  			t.Errorf("for %s expected Content-Length header of %q; got %q", url, expected, cl)
  1031  		}
  1032  		if tl, expected := len(res.TransferEncoding), 0; tl != expected {
  1033  			t.Errorf("for %s expected len(res.TransferEncoding) of %d; got %d (%v)",
  1034  				url, expected, tl, res.TransferEncoding)
  1035  		}
  1036  		res.Body.Close()
  1037  	}
  1038  
  1039  	// Verify that ErrContentLength is returned
  1040  	url := ts.URL + "/?overwrite=1"
  1041  	res, err := c.Get(url)
  1042  	if err != nil {
  1043  		t.Fatalf("error with Get of %s: %v", url, err)
  1044  	}
  1045  	res.Body.Close()
  1046  
  1047  	// Verify that the connection is closed when the declared Content-Length
  1048  	// is larger than what the handler wrote.
  1049  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  1050  	if err != nil {
  1051  		t.Fatalf("error dialing: %v", err)
  1052  	}
  1053  	_, err = conn.Write([]byte("GET /?underwrite=1 HTTP/1.1\r\nHost: foo\r\n\r\n"))
  1054  	if err != nil {
  1055  		t.Fatalf("error writing: %v", err)
  1056  	}
  1057  
  1058  	// The ReadAll will hang for a failing test, so use a Timer to
  1059  	// fail explicitly.
  1060  	goTimeout(t, 2*time.Second, func() {
  1061  		got, _ := ioutil.ReadAll(conn)
  1062  		expectedSuffix := "\r\n\r\ntoo short"
  1063  		if !strings.HasSuffix(string(got), expectedSuffix) {
  1064  			t.Errorf("Expected output to end with %q; got response body %q",
  1065  				expectedSuffix, string(got))
  1066  		}
  1067  	})
  1068  }
  1069  
  1070  func testTCPConnectionCloses(t *testing.T, req string, h Handler) {
  1071  	setParallel(t)
  1072  	defer afterTest(t)
  1073  	s := httptest.NewServer(h)
  1074  	defer s.Close()
  1075  
  1076  	conn, err := net.Dial("tcp", s.Listener.Addr().String())
  1077  	if err != nil {
  1078  		t.Fatal("dial error:", err)
  1079  	}
  1080  	defer conn.Close()
  1081  
  1082  	_, err = fmt.Fprint(conn, req)
  1083  	if err != nil {
  1084  		t.Fatal("print error:", err)
  1085  	}
  1086  
  1087  	r := bufio.NewReader(conn)
  1088  	res, err := ReadResponse(r, &Request{Method: "GET"})
  1089  	if err != nil {
  1090  		t.Fatal("ReadResponse error:", err)
  1091  	}
  1092  
  1093  	didReadAll := make(chan bool, 1)
  1094  	go func() {
  1095  		select {
  1096  		case <-time.After(5 * time.Second):
  1097  			t.Error("body not closed after 5s")
  1098  			return
  1099  		case <-didReadAll:
  1100  		}
  1101  	}()
  1102  
  1103  	_, err = ioutil.ReadAll(r)
  1104  	if err != nil {
  1105  		t.Fatal("read error:", err)
  1106  	}
  1107  	didReadAll <- true
  1108  
  1109  	if !res.Close {
  1110  		t.Errorf("Response.Close = false; want true")
  1111  	}
  1112  }
  1113  
  1114  func testTCPConnectionStaysOpen(t *testing.T, req string, handler Handler) {
  1115  	setParallel(t)
  1116  	defer afterTest(t)
  1117  	ts := httptest.NewServer(handler)
  1118  	defer ts.Close()
  1119  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  1120  	if err != nil {
  1121  		t.Fatal(err)
  1122  	}
  1123  	defer conn.Close()
  1124  	br := bufio.NewReader(conn)
  1125  	for i := 0; i < 2; i++ {
  1126  		if _, err := io.WriteString(conn, req); err != nil {
  1127  			t.Fatal(err)
  1128  		}
  1129  		res, err := ReadResponse(br, nil)
  1130  		if err != nil {
  1131  			t.Fatalf("res %d: %v", i+1, err)
  1132  		}
  1133  		if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
  1134  			t.Fatalf("res %d body copy: %v", i+1, err)
  1135  		}
  1136  		res.Body.Close()
  1137  	}
  1138  }
  1139  
  1140  // TestServeHTTP10Close verifies that HTTP/1.0 requests won't be kept alive.
  1141  func TestServeHTTP10Close(t *testing.T) {
  1142  	testTCPConnectionCloses(t, "GET / HTTP/1.0\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  1143  		ServeFile(w, r, "testdata/file")
  1144  	}))
  1145  }
  1146  
  1147  // TestClientCanClose verifies that clients can also force a connection to close.
  1148  func TestClientCanClose(t *testing.T) {
  1149  	testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nHost: foo\r\nConnection: close\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  1150  		// Nothing.
  1151  	}))
  1152  }
  1153  
  1154  // TestHandlersCanSetConnectionClose verifies that handlers can force a connection to close,
  1155  // even for HTTP/1.1 requests.
  1156  func TestHandlersCanSetConnectionClose11(t *testing.T) {
  1157  	testTCPConnectionCloses(t, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  1158  		w.Header().Set("Connection", "close")
  1159  	}))
  1160  }
  1161  
  1162  func TestHandlersCanSetConnectionClose10(t *testing.T) {
  1163  	testTCPConnectionCloses(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  1164  		w.Header().Set("Connection", "close")
  1165  	}))
  1166  }
  1167  
  1168  func TestHTTP2UpgradeClosesConnection(t *testing.T) {
  1169  	testTCPConnectionCloses(t, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", HandlerFunc(func(w ResponseWriter, r *Request) {
  1170  		// Nothing. (if not hijacked, the server should close the connection
  1171  		// afterwards)
  1172  	}))
  1173  }
  1174  
  1175  func send204(w ResponseWriter, r *Request) { w.WriteHeader(204) }
  1176  func send304(w ResponseWriter, r *Request) { w.WriteHeader(304) }
  1177  
  1178  // Issue 15647: 204 responses can't have bodies, so HTTP/1.0 keep-alive conns should stay open.
  1179  func TestHTTP10KeepAlive204Response(t *testing.T) {
  1180  	testTCPConnectionStaysOpen(t, "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n", HandlerFunc(send204))
  1181  }
  1182  
  1183  func TestHTTP11KeepAlive204Response(t *testing.T) {
  1184  	testTCPConnectionStaysOpen(t, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n", HandlerFunc(send204))
  1185  }
  1186  
  1187  func TestHTTP10KeepAlive304Response(t *testing.T) {
  1188  	testTCPConnectionStaysOpen(t,
  1189  		"GET / HTTP/1.0\r\nConnection: keep-alive\r\nIf-Modified-Since: Mon, 02 Jan 2006 15:04:05 GMT\r\n\r\n",
  1190  		HandlerFunc(send304))
  1191  }
  1192  
  1193  // Issue 15703
  1194  func TestKeepAliveFinalChunkWithEOF(t *testing.T) {
  1195  	setParallel(t)
  1196  	defer afterTest(t)
  1197  	cst := newClientServerTest(t, false /* h1 */, HandlerFunc(func(w ResponseWriter, r *Request) {
  1198  		w.(Flusher).Flush() // force chunked encoding
  1199  		w.Write([]byte("{\"Addr\": \"" + r.RemoteAddr + "\"}"))
  1200  	}))
  1201  	defer cst.close()
  1202  	type data struct {
  1203  		Addr string
  1204  	}
  1205  	var addrs [2]data
  1206  	for i := range addrs {
  1207  		res, err := cst.c.Get(cst.ts.URL)
  1208  		if err != nil {
  1209  			t.Fatal(err)
  1210  		}
  1211  		if err := json.NewDecoder(res.Body).Decode(&addrs[i]); err != nil {
  1212  			t.Fatal(err)
  1213  		}
  1214  		if addrs[i].Addr == "" {
  1215  			t.Fatal("no address")
  1216  		}
  1217  		res.Body.Close()
  1218  	}
  1219  	if addrs[0] != addrs[1] {
  1220  		t.Fatalf("connection not reused")
  1221  	}
  1222  }
  1223  
  1224  func TestSetsRemoteAddr_h1(t *testing.T) { testSetsRemoteAddr(t, h1Mode) }
  1225  func TestSetsRemoteAddr_h2(t *testing.T) { testSetsRemoteAddr(t, h2Mode) }
  1226  
  1227  func testSetsRemoteAddr(t *testing.T, h2 bool) {
  1228  	setParallel(t)
  1229  	defer afterTest(t)
  1230  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  1231  		fmt.Fprintf(w, "%s", r.RemoteAddr)
  1232  	}))
  1233  	defer cst.close()
  1234  
  1235  	res, err := cst.c.Get(cst.ts.URL)
  1236  	if err != nil {
  1237  		t.Fatalf("Get error: %v", err)
  1238  	}
  1239  	body, err := ioutil.ReadAll(res.Body)
  1240  	if err != nil {
  1241  		t.Fatalf("ReadAll error: %v", err)
  1242  	}
  1243  	ip := string(body)
  1244  	if !strings.HasPrefix(ip, "127.0.0.1:") && !strings.HasPrefix(ip, "[::1]:") {
  1245  		t.Fatalf("Expected local addr; got %q", ip)
  1246  	}
  1247  }
  1248  
  1249  type blockingRemoteAddrListener struct {
  1250  	net.Listener
  1251  	conns chan<- net.Conn
  1252  }
  1253  
  1254  func (l *blockingRemoteAddrListener) Accept() (net.Conn, error) {
  1255  	c, err := l.Listener.Accept()
  1256  	if err != nil {
  1257  		return nil, err
  1258  	}
  1259  	brac := &blockingRemoteAddrConn{
  1260  		Conn:  c,
  1261  		addrs: make(chan net.Addr, 1),
  1262  	}
  1263  	l.conns <- brac
  1264  	return brac, nil
  1265  }
  1266  
  1267  type blockingRemoteAddrConn struct {
  1268  	net.Conn
  1269  	addrs chan net.Addr
  1270  }
  1271  
  1272  func (c *blockingRemoteAddrConn) RemoteAddr() net.Addr {
  1273  	return <-c.addrs
  1274  }
  1275  
  1276  // Issue 12943
  1277  func TestServerAllowsBlockingRemoteAddr(t *testing.T) {
  1278  	defer afterTest(t)
  1279  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1280  		fmt.Fprintf(w, "RA:%s", r.RemoteAddr)
  1281  	}))
  1282  	conns := make(chan net.Conn)
  1283  	ts.Listener = &blockingRemoteAddrListener{
  1284  		Listener: ts.Listener,
  1285  		conns:    conns,
  1286  	}
  1287  	ts.Start()
  1288  	defer ts.Close()
  1289  
  1290  	c := ts.Client()
  1291  	c.Timeout = time.Second
  1292  	// Force separate connection for each:
  1293  	c.Transport.(*Transport).DisableKeepAlives = true
  1294  
  1295  	fetch := func(num int, response chan<- string) {
  1296  		resp, err := c.Get(ts.URL)
  1297  		if err != nil {
  1298  			t.Errorf("Request %d: %v", num, err)
  1299  			response <- ""
  1300  			return
  1301  		}
  1302  		defer resp.Body.Close()
  1303  		body, err := ioutil.ReadAll(resp.Body)
  1304  		if err != nil {
  1305  			t.Errorf("Request %d: %v", num, err)
  1306  			response <- ""
  1307  			return
  1308  		}
  1309  		response <- string(body)
  1310  	}
  1311  
  1312  	// Start a request. The server will block on getting conn.RemoteAddr.
  1313  	response1c := make(chan string, 1)
  1314  	go fetch(1, response1c)
  1315  
  1316  	// Wait for the server to accept it; grab the connection.
  1317  	conn1 := <-conns
  1318  
  1319  	// Start another request and grab its connection
  1320  	response2c := make(chan string, 1)
  1321  	go fetch(2, response2c)
  1322  	var conn2 net.Conn
  1323  
  1324  	select {
  1325  	case conn2 = <-conns:
  1326  	case <-time.After(time.Second):
  1327  		t.Fatal("Second Accept didn't happen")
  1328  	}
  1329  
  1330  	// Send a response on connection 2.
  1331  	conn2.(*blockingRemoteAddrConn).addrs <- &net.TCPAddr{
  1332  		IP: net.ParseIP("12.12.12.12"), Port: 12}
  1333  
  1334  	// ... and see it
  1335  	response2 := <-response2c
  1336  	if g, e := response2, "RA:12.12.12.12:12"; g != e {
  1337  		t.Fatalf("response 2 addr = %q; want %q", g, e)
  1338  	}
  1339  
  1340  	// Finish the first response.
  1341  	conn1.(*blockingRemoteAddrConn).addrs <- &net.TCPAddr{
  1342  		IP: net.ParseIP("21.21.21.21"), Port: 21}
  1343  
  1344  	// ... and see it
  1345  	response1 := <-response1c
  1346  	if g, e := response1, "RA:21.21.21.21:21"; g != e {
  1347  		t.Fatalf("response 1 addr = %q; want %q", g, e)
  1348  	}
  1349  }
  1350  
  1351  func TestIdentityResponseHeaders(t *testing.T) {
  1352  	// Not parallel; changes log output.
  1353  	defer afterTest(t)
  1354  	log.SetOutput(ioutil.Discard) // is noisy otherwise
  1355  	defer log.SetOutput(os.Stderr)
  1356  
  1357  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1358  		w.Header().Set("Transfer-Encoding", "identity")
  1359  		w.(Flusher).Flush()
  1360  		fmt.Fprintf(w, "I am an identity response.")
  1361  	}))
  1362  	defer ts.Close()
  1363  
  1364  	c := ts.Client()
  1365  	res, err := c.Get(ts.URL)
  1366  	if err != nil {
  1367  		t.Fatalf("Get error: %v", err)
  1368  	}
  1369  	defer res.Body.Close()
  1370  
  1371  	if g, e := res.TransferEncoding, []string(nil); !reflect.DeepEqual(g, e) {
  1372  		t.Errorf("expected TransferEncoding of %v; got %v", e, g)
  1373  	}
  1374  	if _, haveCL := res.Header["Content-Length"]; haveCL {
  1375  		t.Errorf("Unexpected Content-Length")
  1376  	}
  1377  	if !res.Close {
  1378  		t.Errorf("expected Connection: close; got %v", res.Close)
  1379  	}
  1380  }
  1381  
  1382  // TestHeadResponses verifies that all MIME type sniffing and Content-Length
  1383  // counting of GET requests also happens on HEAD requests.
  1384  func TestHeadResponses_h1(t *testing.T) { testHeadResponses(t, h1Mode) }
  1385  func TestHeadResponses_h2(t *testing.T) { testHeadResponses(t, h2Mode) }
  1386  
  1387  func testHeadResponses(t *testing.T, h2 bool) {
  1388  	setParallel(t)
  1389  	defer afterTest(t)
  1390  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  1391  		_, err := w.Write([]byte("<html>"))
  1392  		if err != nil {
  1393  			t.Errorf("ResponseWriter.Write: %v", err)
  1394  		}
  1395  
  1396  		// Also exercise the ReaderFrom path
  1397  		_, err = io.Copy(w, strings.NewReader("789a"))
  1398  		if err != nil {
  1399  			t.Errorf("Copy(ResponseWriter, ...): %v", err)
  1400  		}
  1401  	}))
  1402  	defer cst.close()
  1403  	res, err := cst.c.Head(cst.ts.URL)
  1404  	if err != nil {
  1405  		t.Error(err)
  1406  	}
  1407  	if len(res.TransferEncoding) > 0 {
  1408  		t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding)
  1409  	}
  1410  	if ct := res.Header.Get("Content-Type"); ct != "text/html; charset=utf-8" {
  1411  		t.Errorf("Content-Type: %q; want text/html; charset=utf-8", ct)
  1412  	}
  1413  	if v := res.ContentLength; v != 10 {
  1414  		t.Errorf("Content-Length: %d; want 10", v)
  1415  	}
  1416  	body, err := ioutil.ReadAll(res.Body)
  1417  	if err != nil {
  1418  		t.Error(err)
  1419  	}
  1420  	if len(body) > 0 {
  1421  		t.Errorf("got unexpected body %q", string(body))
  1422  	}
  1423  }
  1424  
  1425  func TestTLSHandshakeTimeout(t *testing.T) {
  1426  	setParallel(t)
  1427  	defer afterTest(t)
  1428  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  1429  	errc := make(chanWriter, 10) // but only expecting 1
  1430  	ts.Config.ReadTimeout = 250 * time.Millisecond
  1431  	ts.Config.ErrorLog = log.New(errc, "", 0)
  1432  	ts.StartTLS()
  1433  	defer ts.Close()
  1434  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  1435  	if err != nil {
  1436  		t.Fatalf("Dial: %v", err)
  1437  	}
  1438  	defer conn.Close()
  1439  	goTimeout(t, 10*time.Second, func() {
  1440  		var buf [1]byte
  1441  		n, err := conn.Read(buf[:])
  1442  		if err == nil || n != 0 {
  1443  			t.Errorf("Read = %d, %v; want an error and no bytes", n, err)
  1444  		}
  1445  	})
  1446  	select {
  1447  	case v := <-errc:
  1448  		if !strings.Contains(v, "timeout") && !strings.Contains(v, "TLS handshake") {
  1449  			t.Errorf("expected a TLS handshake timeout error; got %q", v)
  1450  		}
  1451  	case <-time.After(5 * time.Second):
  1452  		t.Errorf("timeout waiting for logged error")
  1453  	}
  1454  }
  1455  
  1456  func TestTLSServer(t *testing.T) {
  1457  	setParallel(t)
  1458  	defer afterTest(t)
  1459  	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1460  		if r.TLS != nil {
  1461  			w.Header().Set("X-TLS-Set", "true")
  1462  			if r.TLS.HandshakeComplete {
  1463  				w.Header().Set("X-TLS-HandshakeComplete", "true")
  1464  			}
  1465  		}
  1466  	}))
  1467  	ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
  1468  	defer ts.Close()
  1469  
  1470  	// Connect an idle TCP connection to this server before we run
  1471  	// our real tests. This idle connection used to block forever
  1472  	// in the TLS handshake, preventing future connections from
  1473  	// being accepted. It may prevent future accidental blocking
  1474  	// in newConn.
  1475  	idleConn, err := net.Dial("tcp", ts.Listener.Addr().String())
  1476  	if err != nil {
  1477  		t.Fatalf("Dial: %v", err)
  1478  	}
  1479  	defer idleConn.Close()
  1480  	goTimeout(t, 10*time.Second, func() {
  1481  		if !strings.HasPrefix(ts.URL, "https://") {
  1482  			t.Errorf("expected test TLS server to start with https://, got %q", ts.URL)
  1483  			return
  1484  		}
  1485  		client := ts.Client()
  1486  		res, err := client.Get(ts.URL)
  1487  		if err != nil {
  1488  			t.Error(err)
  1489  			return
  1490  		}
  1491  		if res == nil {
  1492  			t.Errorf("got nil Response")
  1493  			return
  1494  		}
  1495  		defer res.Body.Close()
  1496  		if res.Header.Get("X-TLS-Set") != "true" {
  1497  			t.Errorf("expected X-TLS-Set response header")
  1498  			return
  1499  		}
  1500  		if res.Header.Get("X-TLS-HandshakeComplete") != "true" {
  1501  			t.Errorf("expected X-TLS-HandshakeComplete header")
  1502  		}
  1503  	})
  1504  }
  1505  
  1506  func TestServeTLS(t *testing.T) {
  1507  	// Not parallel: uses global test hooks.
  1508  	defer afterTest(t)
  1509  	defer SetTestHookServerServe(nil)
  1510  
  1511  	cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
  1512  	if err != nil {
  1513  		t.Fatal(err)
  1514  	}
  1515  	tlsConf := &tls.Config{
  1516  		Certificates: []tls.Certificate{cert},
  1517  	}
  1518  
  1519  	ln := newLocalListener(t)
  1520  	defer ln.Close()
  1521  	addr := ln.Addr().String()
  1522  
  1523  	serving := make(chan bool, 1)
  1524  	SetTestHookServerServe(func(s *Server, ln net.Listener) {
  1525  		serving <- true
  1526  	})
  1527  	handler := HandlerFunc(func(w ResponseWriter, r *Request) {})
  1528  	s := &Server{
  1529  		Addr:      addr,
  1530  		TLSConfig: tlsConf,
  1531  		Handler:   handler,
  1532  	}
  1533  	errc := make(chan error, 1)
  1534  	go func() { errc <- s.ServeTLS(ln, "", "") }()
  1535  	select {
  1536  	case err := <-errc:
  1537  		t.Fatalf("ServeTLS: %v", err)
  1538  	case <-serving:
  1539  	case <-time.After(5 * time.Second):
  1540  		t.Fatal("timeout")
  1541  	}
  1542  
  1543  	c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{
  1544  		InsecureSkipVerify: true,
  1545  		NextProtos:         []string{"h2", "http/1.1"},
  1546  	})
  1547  	if err != nil {
  1548  		t.Fatal(err)
  1549  	}
  1550  	defer c.Close()
  1551  	if got, want := c.ConnectionState().NegotiatedProtocol, "h2"; got != want {
  1552  		t.Errorf("NegotiatedProtocol = %q; want %q", got, want)
  1553  	}
  1554  	if got, want := c.ConnectionState().NegotiatedProtocolIsMutual, true; got != want {
  1555  		t.Errorf("NegotiatedProtocolIsMutual = %v; want %v", got, want)
  1556  	}
  1557  }
  1558  
  1559  // Issue 15908
  1560  func TestAutomaticHTTP2_Serve_NoTLSConfig(t *testing.T) {
  1561  	testAutomaticHTTP2_Serve(t, nil, true)
  1562  }
  1563  
  1564  func TestAutomaticHTTP2_Serve_NonH2TLSConfig(t *testing.T) {
  1565  	testAutomaticHTTP2_Serve(t, &tls.Config{}, false)
  1566  }
  1567  
  1568  func TestAutomaticHTTP2_Serve_H2TLSConfig(t *testing.T) {
  1569  	testAutomaticHTTP2_Serve(t, &tls.Config{NextProtos: []string{"h2"}}, true)
  1570  }
  1571  
  1572  func testAutomaticHTTP2_Serve(t *testing.T, tlsConf *tls.Config, wantH2 bool) {
  1573  	setParallel(t)
  1574  	defer afterTest(t)
  1575  	ln := newLocalListener(t)
  1576  	ln.Close() // immediately (not a defer!)
  1577  	var s Server
  1578  	s.TLSConfig = tlsConf
  1579  	if err := s.Serve(ln); err == nil {
  1580  		t.Fatal("expected an error")
  1581  	}
  1582  	gotH2 := s.TLSNextProto["h2"] != nil
  1583  	if gotH2 != wantH2 {
  1584  		t.Errorf("http2 configured = %v; want %v", gotH2, wantH2)
  1585  	}
  1586  }
  1587  
  1588  func TestAutomaticHTTP2_Serve_WithTLSConfig(t *testing.T) {
  1589  	setParallel(t)
  1590  	defer afterTest(t)
  1591  	ln := newLocalListener(t)
  1592  	ln.Close() // immediately (not a defer!)
  1593  	var s Server
  1594  	// Set the TLSConfig. In reality, this would be the
  1595  	// *tls.Config given to tls.NewListener.
  1596  	s.TLSConfig = &tls.Config{
  1597  		NextProtos: []string{"h2"},
  1598  	}
  1599  	if err := s.Serve(ln); err == nil {
  1600  		t.Fatal("expected an error")
  1601  	}
  1602  	on := s.TLSNextProto["h2"] != nil
  1603  	if !on {
  1604  		t.Errorf("http2 wasn't automatically enabled")
  1605  	}
  1606  }
  1607  
  1608  func TestAutomaticHTTP2_ListenAndServe(t *testing.T) {
  1609  	cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
  1610  	if err != nil {
  1611  		t.Fatal(err)
  1612  	}
  1613  	testAutomaticHTTP2_ListenAndServe(t, &tls.Config{
  1614  		Certificates: []tls.Certificate{cert},
  1615  	})
  1616  }
  1617  
  1618  func TestAutomaticHTTP2_ListenAndServe_GetCertificate(t *testing.T) {
  1619  	cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
  1620  	if err != nil {
  1621  		t.Fatal(err)
  1622  	}
  1623  	testAutomaticHTTP2_ListenAndServe(t, &tls.Config{
  1624  		GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  1625  			return &cert, nil
  1626  		},
  1627  	})
  1628  }
  1629  
  1630  func testAutomaticHTTP2_ListenAndServe(t *testing.T, tlsConf *tls.Config) {
  1631  	// Not parallel: uses global test hooks.
  1632  	defer afterTest(t)
  1633  	defer SetTestHookServerServe(nil)
  1634  	var ok bool
  1635  	var s *Server
  1636  	const maxTries = 5
  1637  	var ln net.Listener
  1638  Try:
  1639  	for try := 0; try < maxTries; try++ {
  1640  		ln = newLocalListener(t)
  1641  		addr := ln.Addr().String()
  1642  		ln.Close()
  1643  		t.Logf("Got %v", addr)
  1644  		lnc := make(chan net.Listener, 1)
  1645  		SetTestHookServerServe(func(s *Server, ln net.Listener) {
  1646  			lnc <- ln
  1647  		})
  1648  		s = &Server{
  1649  			Addr:      addr,
  1650  			TLSConfig: tlsConf,
  1651  		}
  1652  		errc := make(chan error, 1)
  1653  		go func() { errc <- s.ListenAndServeTLS("", "") }()
  1654  		select {
  1655  		case err := <-errc:
  1656  			t.Logf("On try #%v: %v", try+1, err)
  1657  			continue
  1658  		case ln = <-lnc:
  1659  			ok = true
  1660  			t.Logf("Listening on %v", ln.Addr().String())
  1661  			break Try
  1662  		}
  1663  	}
  1664  	if !ok {
  1665  		t.Fatalf("Failed to start up after %d tries", maxTries)
  1666  	}
  1667  	defer ln.Close()
  1668  	c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{
  1669  		InsecureSkipVerify: true,
  1670  		NextProtos:         []string{"h2", "http/1.1"},
  1671  	})
  1672  	if err != nil {
  1673  		t.Fatal(err)
  1674  	}
  1675  	defer c.Close()
  1676  	if got, want := c.ConnectionState().NegotiatedProtocol, "h2"; got != want {
  1677  		t.Errorf("NegotiatedProtocol = %q; want %q", got, want)
  1678  	}
  1679  	if got, want := c.ConnectionState().NegotiatedProtocolIsMutual, true; got != want {
  1680  		t.Errorf("NegotiatedProtocolIsMutual = %v; want %v", got, want)
  1681  	}
  1682  }
  1683  
  1684  type serverExpectTest struct {
  1685  	contentLength    int // of request body
  1686  	chunked          bool
  1687  	expectation      string // e.g. "100-continue"
  1688  	readBody         bool   // whether handler should read the body (if false, sends StatusUnauthorized)
  1689  	expectedResponse string // expected substring in first line of http response
  1690  }
  1691  
  1692  func expectTest(contentLength int, expectation string, readBody bool, expectedResponse string) serverExpectTest {
  1693  	return serverExpectTest{
  1694  		contentLength:    contentLength,
  1695  		expectation:      expectation,
  1696  		readBody:         readBody,
  1697  		expectedResponse: expectedResponse,
  1698  	}
  1699  }
  1700  
  1701  var serverExpectTests = []serverExpectTest{
  1702  	// Normal 100-continues, case-insensitive.
  1703  	expectTest(100, "100-continue", true, "100 Continue"),
  1704  	expectTest(100, "100-cOntInUE", true, "100 Continue"),
  1705  
  1706  	// No 100-continue.
  1707  	expectTest(100, "", true, "200 OK"),
  1708  
  1709  	// 100-continue but requesting client to deny us,
  1710  	// so it never reads the body.
  1711  	expectTest(100, "100-continue", false, "401 Unauthorized"),
  1712  	// Likewise without 100-continue:
  1713  	expectTest(100, "", false, "401 Unauthorized"),
  1714  
  1715  	// Non-standard expectations are failures
  1716  	expectTest(0, "a-pony", false, "417 Expectation Failed"),
  1717  
  1718  	// Expect-100 requested but no body (is apparently okay: Issue 7625)
  1719  	expectTest(0, "100-continue", true, "200 OK"),
  1720  	// Expect-100 requested but handler doesn't read the body
  1721  	expectTest(0, "100-continue", false, "401 Unauthorized"),
  1722  	// Expect-100 continue with no body, but a chunked body.
  1723  	{
  1724  		expectation:      "100-continue",
  1725  		readBody:         true,
  1726  		chunked:          true,
  1727  		expectedResponse: "100 Continue",
  1728  	},
  1729  }
  1730  
  1731  // Tests that the server responds to the "Expect" request header
  1732  // correctly.
  1733  // http2 test: TestServer_Response_Automatic100Continue
  1734  func TestServerExpect(t *testing.T) {
  1735  	setParallel(t)
  1736  	defer afterTest(t)
  1737  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1738  		// Note using r.FormValue("readbody") because for POST
  1739  		// requests that would read from r.Body, which we only
  1740  		// conditionally want to do.
  1741  		if strings.Contains(r.URL.RawQuery, "readbody=true") {
  1742  			ioutil.ReadAll(r.Body)
  1743  			w.Write([]byte("Hi"))
  1744  		} else {
  1745  			w.WriteHeader(StatusUnauthorized)
  1746  		}
  1747  	}))
  1748  	defer ts.Close()
  1749  
  1750  	runTest := func(test serverExpectTest) {
  1751  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  1752  		if err != nil {
  1753  			t.Fatalf("Dial: %v", err)
  1754  		}
  1755  		defer conn.Close()
  1756  
  1757  		// Only send the body immediately if we're acting like an HTTP client
  1758  		// that doesn't send 100-continue expectations.
  1759  		writeBody := test.contentLength != 0 && strings.ToLower(test.expectation) != "100-continue"
  1760  
  1761  		go func() {
  1762  			contentLen := fmt.Sprintf("Content-Length: %d", test.contentLength)
  1763  			if test.chunked {
  1764  				contentLen = "Transfer-Encoding: chunked"
  1765  			}
  1766  			_, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+
  1767  				"Connection: close\r\n"+
  1768  				"%s\r\n"+
  1769  				"Expect: %s\r\nHost: foo\r\n\r\n",
  1770  				test.readBody, contentLen, test.expectation)
  1771  			if err != nil {
  1772  				t.Errorf("On test %#v, error writing request headers: %v", test, err)
  1773  				return
  1774  			}
  1775  			if writeBody {
  1776  				var targ io.WriteCloser = struct {
  1777  					io.Writer
  1778  					io.Closer
  1779  				}{
  1780  					conn,
  1781  					ioutil.NopCloser(nil),
  1782  				}
  1783  				if test.chunked {
  1784  					targ = httputil.NewChunkedWriter(conn)
  1785  				}
  1786  				body := strings.Repeat("A", test.contentLength)
  1787  				_, err = fmt.Fprint(targ, body)
  1788  				if err == nil {
  1789  					err = targ.Close()
  1790  				}
  1791  				if err != nil {
  1792  					if !test.readBody {
  1793  						// Server likely already hung up on us.
  1794  						// See larger comment below.
  1795  						t.Logf("On test %#v, acceptable error writing request body: %v", test, err)
  1796  						return
  1797  					}
  1798  					t.Errorf("On test %#v, error writing request body: %v", test, err)
  1799  				}
  1800  			}
  1801  		}()
  1802  		bufr := bufio.NewReader(conn)
  1803  		line, err := bufr.ReadString('\n')
  1804  		if err != nil {
  1805  			if writeBody && !test.readBody {
  1806  				// This is an acceptable failure due to a possible TCP race:
  1807  				// We were still writing data and the server hung up on us. A TCP
  1808  				// implementation may send a RST if our request body data was known
  1809  				// to be lost, which may trigger our reads to fail.
  1810  				// See RFC 1122 page 88.
  1811  				t.Logf("On test %#v, acceptable error from ReadString: %v", test, err)
  1812  				return
  1813  			}
  1814  			t.Fatalf("On test %#v, ReadString: %v", test, err)
  1815  		}
  1816  		if !strings.Contains(line, test.expectedResponse) {
  1817  			t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse)
  1818  		}
  1819  	}
  1820  
  1821  	for _, test := range serverExpectTests {
  1822  		runTest(test)
  1823  	}
  1824  }
  1825  
  1826  // Under a ~256KB (maxPostHandlerReadBytes) threshold, the server
  1827  // should consume client request bodies that a handler didn't read.
  1828  func TestServerUnreadRequestBodyLittle(t *testing.T) {
  1829  	setParallel(t)
  1830  	defer afterTest(t)
  1831  	conn := new(testConn)
  1832  	body := strings.Repeat("x", 100<<10)
  1833  	conn.readBuf.Write([]byte(fmt.Sprintf(
  1834  		"POST / HTTP/1.1\r\n"+
  1835  			"Host: test\r\n"+
  1836  			"Content-Length: %d\r\n"+
  1837  			"\r\n", len(body))))
  1838  	conn.readBuf.Write([]byte(body))
  1839  
  1840  	done := make(chan bool)
  1841  
  1842  	readBufLen := func() int {
  1843  		conn.readMu.Lock()
  1844  		defer conn.readMu.Unlock()
  1845  		return conn.readBuf.Len()
  1846  	}
  1847  
  1848  	ls := &oneConnListener{conn}
  1849  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  1850  		defer close(done)
  1851  		if bufLen := readBufLen(); bufLen < len(body)/2 {
  1852  			t.Errorf("on request, read buffer length is %d; expected about 100 KB", bufLen)
  1853  		}
  1854  		rw.WriteHeader(200)
  1855  		rw.(Flusher).Flush()
  1856  		if g, e := readBufLen(), 0; g != e {
  1857  			t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e)
  1858  		}
  1859  		if c := rw.Header().Get("Connection"); c != "" {
  1860  			t.Errorf(`Connection header = %q; want ""`, c)
  1861  		}
  1862  	}))
  1863  	<-done
  1864  }
  1865  
  1866  // Over a ~256KB (maxPostHandlerReadBytes) threshold, the server
  1867  // should ignore client request bodies that a handler didn't read
  1868  // and close the connection.
  1869  func TestServerUnreadRequestBodyLarge(t *testing.T) {
  1870  	setParallel(t)
  1871  	if testing.Short() && testenv.Builder() == "" {
  1872  		t.Log("skipping in short mode")
  1873  	}
  1874  	conn := new(testConn)
  1875  	body := strings.Repeat("x", 1<<20)
  1876  	conn.readBuf.Write([]byte(fmt.Sprintf(
  1877  		"POST / HTTP/1.1\r\n"+
  1878  			"Host: test\r\n"+
  1879  			"Content-Length: %d\r\n"+
  1880  			"\r\n", len(body))))
  1881  	conn.readBuf.Write([]byte(body))
  1882  	conn.closec = make(chan bool, 1)
  1883  
  1884  	ls := &oneConnListener{conn}
  1885  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  1886  		if conn.readBuf.Len() < len(body)/2 {
  1887  			t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
  1888  		}
  1889  		rw.WriteHeader(200)
  1890  		rw.(Flusher).Flush()
  1891  		if conn.readBuf.Len() < len(body)/2 {
  1892  			t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
  1893  		}
  1894  	}))
  1895  	<-conn.closec
  1896  
  1897  	if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") {
  1898  		t.Errorf("Expected a Connection: close header; got response: %s", res)
  1899  	}
  1900  }
  1901  
  1902  type handlerBodyCloseTest struct {
  1903  	bodySize     int
  1904  	bodyChunked  bool
  1905  	reqConnClose bool
  1906  
  1907  	wantEOFSearch bool // should Handler's Body.Close do Reads, looking for EOF?
  1908  	wantNextReq   bool // should it find the next request on the same conn?
  1909  }
  1910  
  1911  func (t handlerBodyCloseTest) connectionHeader() string {
  1912  	if t.reqConnClose {
  1913  		return "Connection: close\r\n"
  1914  	}
  1915  	return ""
  1916  }
  1917  
  1918  var handlerBodyCloseTests = [...]handlerBodyCloseTest{
  1919  	// Small enough to slurp past to the next request +
  1920  	// has Content-Length.
  1921  	0: {
  1922  		bodySize:      20 << 10,
  1923  		bodyChunked:   false,
  1924  		reqConnClose:  false,
  1925  		wantEOFSearch: true,
  1926  		wantNextReq:   true,
  1927  	},
  1928  
  1929  	// Small enough to slurp past to the next request +
  1930  	// is chunked.
  1931  	1: {
  1932  		bodySize:      20 << 10,
  1933  		bodyChunked:   true,
  1934  		reqConnClose:  false,
  1935  		wantEOFSearch: true,
  1936  		wantNextReq:   true,
  1937  	},
  1938  
  1939  	// Small enough to slurp past to the next request +
  1940  	// has Content-Length +
  1941  	// declares Connection: close (so pointless to read more).
  1942  	2: {
  1943  		bodySize:      20 << 10,
  1944  		bodyChunked:   false,
  1945  		reqConnClose:  true,
  1946  		wantEOFSearch: false,
  1947  		wantNextReq:   false,
  1948  	},
  1949  
  1950  	// Small enough to slurp past to the next request +
  1951  	// declares Connection: close,
  1952  	// but chunked, so it might have trailers.
  1953  	// TODO: maybe skip this search if no trailers were declared
  1954  	// in the headers.
  1955  	3: {
  1956  		bodySize:      20 << 10,
  1957  		bodyChunked:   true,
  1958  		reqConnClose:  true,
  1959  		wantEOFSearch: true,
  1960  		wantNextReq:   false,
  1961  	},
  1962  
  1963  	// Big with Content-Length, so give up immediately if we know it's too big.
  1964  	4: {
  1965  		bodySize:      1 << 20,
  1966  		bodyChunked:   false, // has a Content-Length
  1967  		reqConnClose:  false,
  1968  		wantEOFSearch: false,
  1969  		wantNextReq:   false,
  1970  	},
  1971  
  1972  	// Big chunked, so read a bit before giving up.
  1973  	5: {
  1974  		bodySize:      1 << 20,
  1975  		bodyChunked:   true,
  1976  		reqConnClose:  false,
  1977  		wantEOFSearch: true,
  1978  		wantNextReq:   false,
  1979  	},
  1980  
  1981  	// Big with Connection: close, but chunked, so search for trailers.
  1982  	// TODO: maybe skip this search if no trailers were declared
  1983  	// in the headers.
  1984  	6: {
  1985  		bodySize:      1 << 20,
  1986  		bodyChunked:   true,
  1987  		reqConnClose:  true,
  1988  		wantEOFSearch: true,
  1989  		wantNextReq:   false,
  1990  	},
  1991  
  1992  	// Big with Connection: close, so don't do any reads on Close.
  1993  	// With Content-Length.
  1994  	7: {
  1995  		bodySize:      1 << 20,
  1996  		bodyChunked:   false,
  1997  		reqConnClose:  true,
  1998  		wantEOFSearch: false,
  1999  		wantNextReq:   false,
  2000  	},
  2001  }
  2002  
  2003  func TestHandlerBodyClose(t *testing.T) {
  2004  	setParallel(t)
  2005  	if testing.Short() && testenv.Builder() == "" {
  2006  		t.Skip("skipping in -short mode")
  2007  	}
  2008  	for i, tt := range handlerBodyCloseTests {
  2009  		testHandlerBodyClose(t, i, tt)
  2010  	}
  2011  }
  2012  
  2013  func testHandlerBodyClose(t *testing.T, i int, tt handlerBodyCloseTest) {
  2014  	conn := new(testConn)
  2015  	body := strings.Repeat("x", tt.bodySize)
  2016  	if tt.bodyChunked {
  2017  		conn.readBuf.WriteString("POST / HTTP/1.1\r\n" +
  2018  			"Host: test\r\n" +
  2019  			tt.connectionHeader() +
  2020  			"Transfer-Encoding: chunked\r\n" +
  2021  			"\r\n")
  2022  		cw := internal.NewChunkedWriter(&conn.readBuf)
  2023  		io.WriteString(cw, body)
  2024  		cw.Close()
  2025  		conn.readBuf.WriteString("\r\n")
  2026  	} else {
  2027  		conn.readBuf.Write([]byte(fmt.Sprintf(
  2028  			"POST / HTTP/1.1\r\n"+
  2029  				"Host: test\r\n"+
  2030  				tt.connectionHeader()+
  2031  				"Content-Length: %d\r\n"+
  2032  				"\r\n", len(body))))
  2033  		conn.readBuf.Write([]byte(body))
  2034  	}
  2035  	if !tt.reqConnClose {
  2036  		conn.readBuf.WriteString("GET / HTTP/1.1\r\nHost: test\r\n\r\n")
  2037  	}
  2038  	conn.closec = make(chan bool, 1)
  2039  
  2040  	readBufLen := func() int {
  2041  		conn.readMu.Lock()
  2042  		defer conn.readMu.Unlock()
  2043  		return conn.readBuf.Len()
  2044  	}
  2045  
  2046  	ls := &oneConnListener{conn}
  2047  	var numReqs int
  2048  	var size0, size1 int
  2049  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  2050  		numReqs++
  2051  		if numReqs == 1 {
  2052  			size0 = readBufLen()
  2053  			req.Body.Close()
  2054  			size1 = readBufLen()
  2055  		}
  2056  	}))
  2057  	<-conn.closec
  2058  	if numReqs < 1 || numReqs > 2 {
  2059  		t.Fatalf("%d. bug in test. unexpected number of requests = %d", i, numReqs)
  2060  	}
  2061  	didSearch := size0 != size1
  2062  	if didSearch != tt.wantEOFSearch {
  2063  		t.Errorf("%d. did EOF search = %v; want %v (size went from %d to %d)", i, didSearch, !didSearch, size0, size1)
  2064  	}
  2065  	if tt.wantNextReq && numReqs != 2 {
  2066  		t.Errorf("%d. numReq = %d; want 2", i, numReqs)
  2067  	}
  2068  }
  2069  
  2070  // testHandlerBodyConsumer represents a function injected into a test handler to
  2071  // vary work done on a request Body.
  2072  type testHandlerBodyConsumer struct {
  2073  	name string
  2074  	f    func(io.ReadCloser)
  2075  }
  2076  
  2077  var testHandlerBodyConsumers = []testHandlerBodyConsumer{
  2078  	{"nil", func(io.ReadCloser) {}},
  2079  	{"close", func(r io.ReadCloser) { r.Close() }},
  2080  	{"discard", func(r io.ReadCloser) { io.Copy(ioutil.Discard, r) }},
  2081  }
  2082  
  2083  func TestRequestBodyReadErrorClosesConnection(t *testing.T) {
  2084  	setParallel(t)
  2085  	defer afterTest(t)
  2086  	for _, handler := range testHandlerBodyConsumers {
  2087  		conn := new(testConn)
  2088  		conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
  2089  			"Host: test\r\n" +
  2090  			"Transfer-Encoding: chunked\r\n" +
  2091  			"\r\n" +
  2092  			"hax\r\n" + // Invalid chunked encoding
  2093  			"GET /secret HTTP/1.1\r\n" +
  2094  			"Host: test\r\n" +
  2095  			"\r\n")
  2096  
  2097  		conn.closec = make(chan bool, 1)
  2098  		ls := &oneConnListener{conn}
  2099  		var numReqs int
  2100  		go Serve(ls, HandlerFunc(func(_ ResponseWriter, req *Request) {
  2101  			numReqs++
  2102  			if strings.Contains(req.URL.Path, "secret") {
  2103  				t.Error("Request for /secret encountered, should not have happened.")
  2104  			}
  2105  			handler.f(req.Body)
  2106  		}))
  2107  		<-conn.closec
  2108  		if numReqs != 1 {
  2109  			t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
  2110  		}
  2111  	}
  2112  }
  2113  
  2114  func TestInvalidTrailerClosesConnection(t *testing.T) {
  2115  	setParallel(t)
  2116  	defer afterTest(t)
  2117  	for _, handler := range testHandlerBodyConsumers {
  2118  		conn := new(testConn)
  2119  		conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
  2120  			"Host: test\r\n" +
  2121  			"Trailer: hack\r\n" +
  2122  			"Transfer-Encoding: chunked\r\n" +
  2123  			"\r\n" +
  2124  			"3\r\n" +
  2125  			"hax\r\n" +
  2126  			"0\r\n" +
  2127  			"I'm not a valid trailer\r\n" +
  2128  			"GET /secret HTTP/1.1\r\n" +
  2129  			"Host: test\r\n" +
  2130  			"\r\n")
  2131  
  2132  		conn.closec = make(chan bool, 1)
  2133  		ln := &oneConnListener{conn}
  2134  		var numReqs int
  2135  		go Serve(ln, HandlerFunc(func(_ ResponseWriter, req *Request) {
  2136  			numReqs++
  2137  			if strings.Contains(req.URL.Path, "secret") {
  2138  				t.Errorf("Handler %s, Request for /secret encountered, should not have happened.", handler.name)
  2139  			}
  2140  			handler.f(req.Body)
  2141  		}))
  2142  		<-conn.closec
  2143  		if numReqs != 1 {
  2144  			t.Errorf("Handler %s: got %d reqs; want 1", handler.name, numReqs)
  2145  		}
  2146  	}
  2147  }
  2148  
  2149  // slowTestConn is a net.Conn that provides a means to simulate parts of a
  2150  // request being received piecemeal. Deadlines can be set and enforced in both
  2151  // Read and Write.
  2152  type slowTestConn struct {
  2153  	// over multiple calls to Read, time.Durations are slept, strings are read.
  2154  	script []interface{}
  2155  	closec chan bool
  2156  
  2157  	mu     sync.Mutex // guards rd/wd
  2158  	rd, wd time.Time  // read, write deadline
  2159  	noopConn
  2160  }
  2161  
  2162  func (c *slowTestConn) SetDeadline(t time.Time) error {
  2163  	c.SetReadDeadline(t)
  2164  	c.SetWriteDeadline(t)
  2165  	return nil
  2166  }
  2167  
  2168  func (c *slowTestConn) SetReadDeadline(t time.Time) error {
  2169  	c.mu.Lock()
  2170  	defer c.mu.Unlock()
  2171  	c.rd = t
  2172  	return nil
  2173  }
  2174  
  2175  func (c *slowTestConn) SetWriteDeadline(t time.Time) error {
  2176  	c.mu.Lock()
  2177  	defer c.mu.Unlock()
  2178  	c.wd = t
  2179  	return nil
  2180  }
  2181  
  2182  func (c *slowTestConn) Read(b []byte) (n int, err error) {
  2183  	c.mu.Lock()
  2184  	defer c.mu.Unlock()
  2185  restart:
  2186  	if !c.rd.IsZero() && time.Now().After(c.rd) {
  2187  		return 0, syscall.ETIMEDOUT
  2188  	}
  2189  	if len(c.script) == 0 {
  2190  		return 0, io.EOF
  2191  	}
  2192  
  2193  	switch cue := c.script[0].(type) {
  2194  	case time.Duration:
  2195  		if !c.rd.IsZero() {
  2196  			// If the deadline falls in the middle of our sleep window, deduct
  2197  			// part of the sleep, then return a timeout.
  2198  			if remaining := time.Until(c.rd); remaining < cue {
  2199  				c.script[0] = cue - remaining
  2200  				time.Sleep(remaining)
  2201  				return 0, syscall.ETIMEDOUT
  2202  			}
  2203  		}
  2204  		c.script = c.script[1:]
  2205  		time.Sleep(cue)
  2206  		goto restart
  2207  
  2208  	case string:
  2209  		n = copy(b, cue)
  2210  		// If cue is too big for the buffer, leave the end for the next Read.
  2211  		if len(cue) > n {
  2212  			c.script[0] = cue[n:]
  2213  		} else {
  2214  			c.script = c.script[1:]
  2215  		}
  2216  
  2217  	default:
  2218  		panic("unknown cue in slowTestConn script")
  2219  	}
  2220  
  2221  	return
  2222  }
  2223  
  2224  func (c *slowTestConn) Close() error {
  2225  	select {
  2226  	case c.closec <- true:
  2227  	default:
  2228  	}
  2229  	return nil
  2230  }
  2231  
  2232  func (c *slowTestConn) Write(b []byte) (int, error) {
  2233  	if !c.wd.IsZero() && time.Now().After(c.wd) {
  2234  		return 0, syscall.ETIMEDOUT
  2235  	}
  2236  	return len(b), nil
  2237  }
  2238  
  2239  func TestRequestBodyTimeoutClosesConnection(t *testing.T) {
  2240  	if testing.Short() {
  2241  		t.Skip("skipping in -short mode")
  2242  	}
  2243  	defer afterTest(t)
  2244  	for _, handler := range testHandlerBodyConsumers {
  2245  		conn := &slowTestConn{
  2246  			script: []interface{}{
  2247  				"POST /public HTTP/1.1\r\n" +
  2248  					"Host: test\r\n" +
  2249  					"Content-Length: 10000\r\n" +
  2250  					"\r\n",
  2251  				"foo bar baz",
  2252  				600 * time.Millisecond, // Request deadline should hit here
  2253  				"GET /secret HTTP/1.1\r\n" +
  2254  					"Host: test\r\n" +
  2255  					"\r\n",
  2256  			},
  2257  			closec: make(chan bool, 1),
  2258  		}
  2259  		ls := &oneConnListener{conn}
  2260  
  2261  		var numReqs int
  2262  		s := Server{
  2263  			Handler: HandlerFunc(func(_ ResponseWriter, req *Request) {
  2264  				numReqs++
  2265  				if strings.Contains(req.URL.Path, "secret") {
  2266  					t.Error("Request for /secret encountered, should not have happened.")
  2267  				}
  2268  				handler.f(req.Body)
  2269  			}),
  2270  			ReadTimeout: 400 * time.Millisecond,
  2271  		}
  2272  		go s.Serve(ls)
  2273  		<-conn.closec
  2274  
  2275  		if numReqs != 1 {
  2276  			t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
  2277  		}
  2278  	}
  2279  }
  2280  
  2281  func TestTimeoutHandler_h1(t *testing.T) { testTimeoutHandler(t, h1Mode) }
  2282  func TestTimeoutHandler_h2(t *testing.T) { testTimeoutHandler(t, h2Mode) }
  2283  func testTimeoutHandler(t *testing.T, h2 bool) {
  2284  	setParallel(t)
  2285  	defer afterTest(t)
  2286  	sendHi := make(chan bool, 1)
  2287  	writeErrors := make(chan error, 1)
  2288  	sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2289  		<-sendHi
  2290  		_, werr := w.Write([]byte("hi"))
  2291  		writeErrors <- werr
  2292  	})
  2293  	timeout := make(chan time.Time, 1) // write to this to force timeouts
  2294  	cst := newClientServerTest(t, h2, NewTestTimeoutHandler(sayHi, timeout))
  2295  	defer cst.close()
  2296  
  2297  	// Succeed without timing out:
  2298  	sendHi <- true
  2299  	res, err := cst.c.Get(cst.ts.URL)
  2300  	if err != nil {
  2301  		t.Error(err)
  2302  	}
  2303  	if g, e := res.StatusCode, StatusOK; g != e {
  2304  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2305  	}
  2306  	body, _ := ioutil.ReadAll(res.Body)
  2307  	if g, e := string(body), "hi"; g != e {
  2308  		t.Errorf("got body %q; expected %q", g, e)
  2309  	}
  2310  	if g := <-writeErrors; g != nil {
  2311  		t.Errorf("got unexpected Write error on first request: %v", g)
  2312  	}
  2313  
  2314  	// Times out:
  2315  	timeout <- time.Time{}
  2316  	res, err = cst.c.Get(cst.ts.URL)
  2317  	if err != nil {
  2318  		t.Error(err)
  2319  	}
  2320  	if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  2321  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2322  	}
  2323  	body, _ = ioutil.ReadAll(res.Body)
  2324  	if !strings.Contains(string(body), "<title>Timeout</title>") {
  2325  		t.Errorf("expected timeout body; got %q", string(body))
  2326  	}
  2327  	if g, w := res.Header.Get("Content-Type"), "text/html; charset=utf-8"; g != w {
  2328  		t.Errorf("response content-type = %q; want %q", g, w)
  2329  	}
  2330  
  2331  	// Now make the previously-timed out handler speak again,
  2332  	// which verifies the panic is handled:
  2333  	sendHi <- true
  2334  	if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
  2335  		t.Errorf("expected Write error of %v; got %v", e, g)
  2336  	}
  2337  }
  2338  
  2339  // See issues 8209 and 8414.
  2340  func TestTimeoutHandlerRace(t *testing.T) {
  2341  	setParallel(t)
  2342  	defer afterTest(t)
  2343  
  2344  	delayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2345  		ms, _ := strconv.Atoi(r.URL.Path[1:])
  2346  		if ms == 0 {
  2347  			ms = 1
  2348  		}
  2349  		for i := 0; i < ms; i++ {
  2350  			w.Write([]byte("hi"))
  2351  			time.Sleep(time.Millisecond)
  2352  		}
  2353  	})
  2354  
  2355  	ts := httptest.NewServer(TimeoutHandler(delayHi, 20*time.Millisecond, ""))
  2356  	defer ts.Close()
  2357  
  2358  	c := ts.Client()
  2359  
  2360  	var wg sync.WaitGroup
  2361  	gate := make(chan bool, 10)
  2362  	n := 50
  2363  	if testing.Short() {
  2364  		n = 10
  2365  		gate = make(chan bool, 3)
  2366  	}
  2367  	for i := 0; i < n; i++ {
  2368  		gate <- true
  2369  		wg.Add(1)
  2370  		go func() {
  2371  			defer wg.Done()
  2372  			defer func() { <-gate }()
  2373  			res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50)))
  2374  			if err == nil {
  2375  				io.Copy(ioutil.Discard, res.Body)
  2376  				res.Body.Close()
  2377  			}
  2378  		}()
  2379  	}
  2380  	wg.Wait()
  2381  }
  2382  
  2383  // See issues 8209 and 8414.
  2384  func TestTimeoutHandlerRaceHeader(t *testing.T) {
  2385  	setParallel(t)
  2386  	defer afterTest(t)
  2387  
  2388  	delay204 := HandlerFunc(func(w ResponseWriter, r *Request) {
  2389  		w.WriteHeader(204)
  2390  	})
  2391  
  2392  	ts := httptest.NewServer(TimeoutHandler(delay204, time.Nanosecond, ""))
  2393  	defer ts.Close()
  2394  
  2395  	var wg sync.WaitGroup
  2396  	gate := make(chan bool, 50)
  2397  	n := 500
  2398  	if testing.Short() {
  2399  		n = 10
  2400  	}
  2401  
  2402  	c := ts.Client()
  2403  	for i := 0; i < n; i++ {
  2404  		gate <- true
  2405  		wg.Add(1)
  2406  		go func() {
  2407  			defer wg.Done()
  2408  			defer func() { <-gate }()
  2409  			res, err := c.Get(ts.URL)
  2410  			if err != nil {
  2411  				t.Error(err)
  2412  				return
  2413  			}
  2414  			defer res.Body.Close()
  2415  			io.Copy(ioutil.Discard, res.Body)
  2416  		}()
  2417  	}
  2418  	wg.Wait()
  2419  }
  2420  
  2421  // Issue 9162
  2422  func TestTimeoutHandlerRaceHeaderTimeout(t *testing.T) {
  2423  	setParallel(t)
  2424  	defer afterTest(t)
  2425  	sendHi := make(chan bool, 1)
  2426  	writeErrors := make(chan error, 1)
  2427  	sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2428  		w.Header().Set("Content-Type", "text/plain")
  2429  		<-sendHi
  2430  		_, werr := w.Write([]byte("hi"))
  2431  		writeErrors <- werr
  2432  	})
  2433  	timeout := make(chan time.Time, 1) // write to this to force timeouts
  2434  	cst := newClientServerTest(t, h1Mode, NewTestTimeoutHandler(sayHi, timeout))
  2435  	defer cst.close()
  2436  
  2437  	// Succeed without timing out:
  2438  	sendHi <- true
  2439  	res, err := cst.c.Get(cst.ts.URL)
  2440  	if err != nil {
  2441  		t.Error(err)
  2442  	}
  2443  	if g, e := res.StatusCode, StatusOK; g != e {
  2444  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2445  	}
  2446  	body, _ := ioutil.ReadAll(res.Body)
  2447  	if g, e := string(body), "hi"; g != e {
  2448  		t.Errorf("got body %q; expected %q", g, e)
  2449  	}
  2450  	if g := <-writeErrors; g != nil {
  2451  		t.Errorf("got unexpected Write error on first request: %v", g)
  2452  	}
  2453  
  2454  	// Times out:
  2455  	timeout <- time.Time{}
  2456  	res, err = cst.c.Get(cst.ts.URL)
  2457  	if err != nil {
  2458  		t.Error(err)
  2459  	}
  2460  	if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  2461  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2462  	}
  2463  	body, _ = ioutil.ReadAll(res.Body)
  2464  	if !strings.Contains(string(body), "<title>Timeout</title>") {
  2465  		t.Errorf("expected timeout body; got %q", string(body))
  2466  	}
  2467  
  2468  	// Now make the previously-timed out handler speak again,
  2469  	// which verifies the panic is handled:
  2470  	sendHi <- true
  2471  	if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
  2472  		t.Errorf("expected Write error of %v; got %v", e, g)
  2473  	}
  2474  }
  2475  
  2476  // Issue 14568.
  2477  func TestTimeoutHandlerStartTimerWhenServing(t *testing.T) {
  2478  	if testing.Short() {
  2479  		t.Skip("skipping sleeping test in -short mode")
  2480  	}
  2481  	defer afterTest(t)
  2482  	var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
  2483  		w.WriteHeader(StatusNoContent)
  2484  	}
  2485  	timeout := 300 * time.Millisecond
  2486  	ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
  2487  	defer ts.Close()
  2488  
  2489  	c := ts.Client()
  2490  
  2491  	// Issue was caused by the timeout handler starting the timer when
  2492  	// was created, not when the request. So wait for more than the timeout
  2493  	// to ensure that's not the case.
  2494  	time.Sleep(2 * timeout)
  2495  	res, err := c.Get(ts.URL)
  2496  	if err != nil {
  2497  		t.Fatal(err)
  2498  	}
  2499  	defer res.Body.Close()
  2500  	if res.StatusCode != StatusNoContent {
  2501  		t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusNoContent)
  2502  	}
  2503  }
  2504  
  2505  // https://golang.org/issue/15948
  2506  func TestTimeoutHandlerEmptyResponse(t *testing.T) {
  2507  	setParallel(t)
  2508  	defer afterTest(t)
  2509  	var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
  2510  		// No response.
  2511  	}
  2512  	timeout := 300 * time.Millisecond
  2513  	ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
  2514  	defer ts.Close()
  2515  
  2516  	c := ts.Client()
  2517  
  2518  	res, err := c.Get(ts.URL)
  2519  	if err != nil {
  2520  		t.Fatal(err)
  2521  	}
  2522  	defer res.Body.Close()
  2523  	if res.StatusCode != StatusOK {
  2524  		t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusOK)
  2525  	}
  2526  }
  2527  
  2528  // https://golang.org/issues/22084
  2529  func TestTimeoutHandlerPanicRecovery(t *testing.T) {
  2530  	wrapper := func(h Handler) Handler {
  2531  		return TimeoutHandler(h, time.Second, "")
  2532  	}
  2533  	testHandlerPanic(t, false, false, wrapper, "intentional death for testing")
  2534  }
  2535  
  2536  func TestRedirectBadPath(t *testing.T) {
  2537  	// This used to crash. It's not valid input (bad path), but it
  2538  	// shouldn't crash.
  2539  	rr := httptest.NewRecorder()
  2540  	req := &Request{
  2541  		Method: "GET",
  2542  		URL: &url.URL{
  2543  			Scheme: "http",
  2544  			Path:   "not-empty-but-no-leading-slash", // bogus
  2545  		},
  2546  	}
  2547  	Redirect(rr, req, "", 304)
  2548  	if rr.Code != 304 {
  2549  		t.Errorf("Code = %d; want 304", rr.Code)
  2550  	}
  2551  }
  2552  
  2553  // Test different URL formats and schemes
  2554  func TestRedirect(t *testing.T) {
  2555  	req, _ := NewRequest("GET", "http://example.com/qux/", nil)
  2556  
  2557  	var tests = []struct {
  2558  		in   string
  2559  		want string
  2560  	}{
  2561  		// normal http
  2562  		{"http://foobar.com/baz", "http://foobar.com/baz"},
  2563  		// normal https
  2564  		{"https://foobar.com/baz", "https://foobar.com/baz"},
  2565  		// custom scheme
  2566  		{"test://foobar.com/baz", "test://foobar.com/baz"},
  2567  		// schemeless
  2568  		{"//foobar.com/baz", "//foobar.com/baz"},
  2569  		// relative to the root
  2570  		{"/foobar.com/baz", "/foobar.com/baz"},
  2571  		// relative to the current path
  2572  		{"foobar.com/baz", "/qux/foobar.com/baz"},
  2573  		// relative to the current path (+ going upwards)
  2574  		{"../quux/foobar.com/baz", "/quux/foobar.com/baz"},
  2575  		// incorrect number of slashes
  2576  		{"///foobar.com/baz", "/foobar.com/baz"},
  2577  
  2578  		// Verifies we don't path.Clean() on the wrong parts in redirects:
  2579  		{"/foo?next=http://bar.com/", "/foo?next=http://bar.com/"},
  2580  		{"http://localhost:8080/_ah/login?continue=http://localhost:8080/",
  2581  			"http://localhost:8080/_ah/login?continue=http://localhost:8080/"},
  2582  
  2583  		{"/фубар", "/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
  2584  		{"http://foo.com/фубар", "http://foo.com/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
  2585  	}
  2586  
  2587  	for _, tt := range tests {
  2588  		rec := httptest.NewRecorder()
  2589  		Redirect(rec, req, tt.in, 302)
  2590  		if got, want := rec.Code, 302; got != want {
  2591  			t.Errorf("Redirect(%q) generated status code %v; want %v", tt.in, got, want)
  2592  		}
  2593  		if got := rec.Header().Get("Location"); got != tt.want {
  2594  			t.Errorf("Redirect(%q) generated Location header %q; want %q", tt.in, got, tt.want)
  2595  		}
  2596  	}
  2597  }
  2598  
  2599  // Test that Redirect sets Content-Type header for GET and HEAD requests
  2600  // and writes a short HTML body, unless the request already has a Content-Type header.
  2601  func TestRedirect_contentTypeAndBody(t *testing.T) {
  2602  	type ctHeader struct {
  2603  		Values []string
  2604  	}
  2605  
  2606  	var tests = []struct {
  2607  		method   string
  2608  		ct       *ctHeader // Optional Content-Type header to set.
  2609  		wantCT   string
  2610  		wantBody string
  2611  	}{
  2612  		{MethodGet, nil, "text/html; charset=utf-8", "<a href=\"/foo\">Found</a>.\n\n"},
  2613  		{MethodHead, nil, "text/html; charset=utf-8", ""},
  2614  		{MethodPost, nil, "", ""},
  2615  		{MethodDelete, nil, "", ""},
  2616  		{"foo", nil, "", ""},
  2617  		{MethodGet, &ctHeader{[]string{"application/test"}}, "application/test", ""},
  2618  		{MethodGet, &ctHeader{[]string{}}, "", ""},
  2619  		{MethodGet, &ctHeader{nil}, "", ""},
  2620  	}
  2621  	for _, tt := range tests {
  2622  		req := httptest.NewRequest(tt.method, "http://example.com/qux/", nil)
  2623  		rec := httptest.NewRecorder()
  2624  		if tt.ct != nil {
  2625  			rec.Header()["Content-Type"] = tt.ct.Values
  2626  		}
  2627  		Redirect(rec, req, "/foo", 302)
  2628  		if got, want := rec.Code, 302; got != want {
  2629  			t.Errorf("Redirect(%q, %#v) generated status code %v; want %v", tt.method, tt.ct, got, want)
  2630  		}
  2631  		if got, want := rec.Header().Get("Content-Type"), tt.wantCT; got != want {
  2632  			t.Errorf("Redirect(%q, %#v) generated Content-Type header %q; want %q", tt.method, tt.ct, got, want)
  2633  		}
  2634  		resp := rec.Result()
  2635  		body, err := ioutil.ReadAll(resp.Body)
  2636  		if err != nil {
  2637  			t.Fatal(err)
  2638  		}
  2639  		if got, want := string(body), tt.wantBody; got != want {
  2640  			t.Errorf("Redirect(%q, %#v) generated Body %q; want %q", tt.method, tt.ct, got, want)
  2641  		}
  2642  	}
  2643  }
  2644  
  2645  // TestZeroLengthPostAndResponse exercises an optimization done by the Transport:
  2646  // when there is no body (either because the method doesn't permit a body, or an
  2647  // explicit Content-Length of zero is present), then the transport can re-use the
  2648  // connection immediately. But when it re-uses the connection, it typically closes
  2649  // the previous request's body, which is not optimal for zero-lengthed bodies,
  2650  // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF.
  2651  func TestZeroLengthPostAndResponse_h1(t *testing.T) {
  2652  	testZeroLengthPostAndResponse(t, h1Mode)
  2653  }
  2654  func TestZeroLengthPostAndResponse_h2(t *testing.T) {
  2655  	testZeroLengthPostAndResponse(t, h2Mode)
  2656  }
  2657  
  2658  func testZeroLengthPostAndResponse(t *testing.T, h2 bool) {
  2659  	setParallel(t)
  2660  	defer afterTest(t)
  2661  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, r *Request) {
  2662  		all, err := ioutil.ReadAll(r.Body)
  2663  		if err != nil {
  2664  			t.Fatalf("handler ReadAll: %v", err)
  2665  		}
  2666  		if len(all) != 0 {
  2667  			t.Errorf("handler got %d bytes; expected 0", len(all))
  2668  		}
  2669  		rw.Header().Set("Content-Length", "0")
  2670  	}))
  2671  	defer cst.close()
  2672  
  2673  	req, err := NewRequest("POST", cst.ts.URL, strings.NewReader(""))
  2674  	if err != nil {
  2675  		t.Fatal(err)
  2676  	}
  2677  	req.ContentLength = 0
  2678  
  2679  	var resp [5]*Response
  2680  	for i := range resp {
  2681  		resp[i], err = cst.c.Do(req)
  2682  		if err != nil {
  2683  			t.Fatalf("client post #%d: %v", i, err)
  2684  		}
  2685  	}
  2686  
  2687  	for i := range resp {
  2688  		all, err := ioutil.ReadAll(resp[i].Body)
  2689  		if err != nil {
  2690  			t.Fatalf("req #%d: client ReadAll: %v", i, err)
  2691  		}
  2692  		if len(all) != 0 {
  2693  			t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all))
  2694  		}
  2695  	}
  2696  }
  2697  
  2698  func TestHandlerPanicNil_h1(t *testing.T) { testHandlerPanic(t, false, h1Mode, nil, nil) }
  2699  func TestHandlerPanicNil_h2(t *testing.T) { testHandlerPanic(t, false, h2Mode, nil, nil) }
  2700  
  2701  func TestHandlerPanic_h1(t *testing.T) {
  2702  	testHandlerPanic(t, false, h1Mode, nil, "intentional death for testing")
  2703  }
  2704  func TestHandlerPanic_h2(t *testing.T) {
  2705  	testHandlerPanic(t, false, h2Mode, nil, "intentional death for testing")
  2706  }
  2707  
  2708  func TestHandlerPanicWithHijack(t *testing.T) {
  2709  	// Only testing HTTP/1, and our http2 server doesn't support hijacking.
  2710  	testHandlerPanic(t, true, h1Mode, nil, "intentional death for testing")
  2711  }
  2712  
  2713  func testHandlerPanic(t *testing.T, withHijack, h2 bool, wrapper func(Handler) Handler, panicValue interface{}) {
  2714  	defer afterTest(t)
  2715  	// Unlike the other tests that set the log output to ioutil.Discard
  2716  	// to quiet the output, this test uses a pipe. The pipe serves three
  2717  	// purposes:
  2718  	//
  2719  	//   1) The log.Print from the http server (generated by the caught
  2720  	//      panic) will go to the pipe instead of stderr, making the
  2721  	//      output quiet.
  2722  	//
  2723  	//   2) We read from the pipe to verify that the handler
  2724  	//      actually caught the panic and logged something.
  2725  	//
  2726  	//   3) The blocking Read call prevents this TestHandlerPanic
  2727  	//      function from exiting before the HTTP server handler
  2728  	//      finishes crashing. If this text function exited too
  2729  	//      early (and its defer log.SetOutput(os.Stderr) ran),
  2730  	//      then the crash output could spill into the next test.
  2731  	pr, pw := io.Pipe()
  2732  	log.SetOutput(pw)
  2733  	defer log.SetOutput(os.Stderr)
  2734  	defer pw.Close()
  2735  
  2736  	var handler Handler = HandlerFunc(func(w ResponseWriter, r *Request) {
  2737  		if withHijack {
  2738  			rwc, _, err := w.(Hijacker).Hijack()
  2739  			if err != nil {
  2740  				t.Logf("unexpected error: %v", err)
  2741  			}
  2742  			defer rwc.Close()
  2743  		}
  2744  		panic(panicValue)
  2745  	})
  2746  	if wrapper != nil {
  2747  		handler = wrapper(handler)
  2748  	}
  2749  	cst := newClientServerTest(t, h2, handler)
  2750  	defer cst.close()
  2751  
  2752  	// Do a blocking read on the log output pipe so its logging
  2753  	// doesn't bleed into the next test. But wait only 5 seconds
  2754  	// for it.
  2755  	done := make(chan bool, 1)
  2756  	go func() {
  2757  		buf := make([]byte, 4<<10)
  2758  		_, err := pr.Read(buf)
  2759  		pr.Close()
  2760  		if err != nil && err != io.EOF {
  2761  			t.Error(err)
  2762  		}
  2763  		done <- true
  2764  	}()
  2765  
  2766  	_, err := cst.c.Get(cst.ts.URL)
  2767  	if err == nil {
  2768  		t.Logf("expected an error")
  2769  	}
  2770  
  2771  	if panicValue == nil {
  2772  		return
  2773  	}
  2774  
  2775  	select {
  2776  	case <-done:
  2777  		return
  2778  	case <-time.After(5 * time.Second):
  2779  		t.Fatal("expected server handler to log an error")
  2780  	}
  2781  }
  2782  
  2783  type terrorWriter struct{ t *testing.T }
  2784  
  2785  func (w terrorWriter) Write(p []byte) (int, error) {
  2786  	w.t.Errorf("%s", p)
  2787  	return len(p), nil
  2788  }
  2789  
  2790  // Issue 16456: allow writing 0 bytes on hijacked conn to test hijack
  2791  // without any log spam.
  2792  func TestServerWriteHijackZeroBytes(t *testing.T) {
  2793  	defer afterTest(t)
  2794  	done := make(chan struct{})
  2795  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  2796  		defer close(done)
  2797  		w.(Flusher).Flush()
  2798  		conn, _, err := w.(Hijacker).Hijack()
  2799  		if err != nil {
  2800  			t.Errorf("Hijack: %v", err)
  2801  			return
  2802  		}
  2803  		defer conn.Close()
  2804  		_, err = w.Write(nil)
  2805  		if err != ErrHijacked {
  2806  			t.Errorf("Write error = %v; want ErrHijacked", err)
  2807  		}
  2808  	}))
  2809  	ts.Config.ErrorLog = log.New(terrorWriter{t}, "Unexpected write: ", 0)
  2810  	ts.Start()
  2811  	defer ts.Close()
  2812  
  2813  	c := ts.Client()
  2814  	res, err := c.Get(ts.URL)
  2815  	if err != nil {
  2816  		t.Fatal(err)
  2817  	}
  2818  	res.Body.Close()
  2819  	select {
  2820  	case <-done:
  2821  	case <-time.After(5 * time.Second):
  2822  		t.Fatal("timeout")
  2823  	}
  2824  }
  2825  
  2826  func TestServerNoDate_h1(t *testing.T)        { testServerNoHeader(t, h1Mode, "Date") }
  2827  func TestServerNoDate_h2(t *testing.T)        { testServerNoHeader(t, h2Mode, "Date") }
  2828  func TestServerNoContentType_h1(t *testing.T) { testServerNoHeader(t, h1Mode, "Content-Type") }
  2829  func TestServerNoContentType_h2(t *testing.T) { testServerNoHeader(t, h2Mode, "Content-Type") }
  2830  
  2831  func testServerNoHeader(t *testing.T, h2 bool, header string) {
  2832  	setParallel(t)
  2833  	defer afterTest(t)
  2834  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2835  		w.Header()[header] = nil
  2836  		io.WriteString(w, "<html>foo</html>") // non-empty
  2837  	}))
  2838  	defer cst.close()
  2839  	res, err := cst.c.Get(cst.ts.URL)
  2840  	if err != nil {
  2841  		t.Fatal(err)
  2842  	}
  2843  	res.Body.Close()
  2844  	if got, ok := res.Header[header]; ok {
  2845  		t.Fatalf("Expected no %s header; got %q", header, got)
  2846  	}
  2847  }
  2848  
  2849  func TestStripPrefix(t *testing.T) {
  2850  	setParallel(t)
  2851  	defer afterTest(t)
  2852  	h := HandlerFunc(func(w ResponseWriter, r *Request) {
  2853  		w.Header().Set("X-Path", r.URL.Path)
  2854  	})
  2855  	ts := httptest.NewServer(StripPrefix("/foo", h))
  2856  	defer ts.Close()
  2857  
  2858  	c := ts.Client()
  2859  
  2860  	res, err := c.Get(ts.URL + "/foo/bar")
  2861  	if err != nil {
  2862  		t.Fatal(err)
  2863  	}
  2864  	if g, e := res.Header.Get("X-Path"), "/bar"; g != e {
  2865  		t.Errorf("test 1: got %s, want %s", g, e)
  2866  	}
  2867  	res.Body.Close()
  2868  
  2869  	res, err = Get(ts.URL + "/bar")
  2870  	if err != nil {
  2871  		t.Fatal(err)
  2872  	}
  2873  	if g, e := res.StatusCode, 404; g != e {
  2874  		t.Errorf("test 2: got status %v, want %v", g, e)
  2875  	}
  2876  	res.Body.Close()
  2877  }
  2878  
  2879  // https://golang.org/issue/18952.
  2880  func TestStripPrefix_notModifyRequest(t *testing.T) {
  2881  	h := StripPrefix("/foo", NotFoundHandler())
  2882  	req := httptest.NewRequest("GET", "/foo/bar", nil)
  2883  	h.ServeHTTP(httptest.NewRecorder(), req)
  2884  	if req.URL.Path != "/foo/bar" {
  2885  		t.Errorf("StripPrefix should not modify the provided Request, but it did")
  2886  	}
  2887  }
  2888  
  2889  func TestRequestLimit_h1(t *testing.T) { testRequestLimit(t, h1Mode) }
  2890  func TestRequestLimit_h2(t *testing.T) { testRequestLimit(t, h2Mode) }
  2891  func testRequestLimit(t *testing.T, h2 bool) {
  2892  	setParallel(t)
  2893  	defer afterTest(t)
  2894  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2895  		t.Fatalf("didn't expect to get request in Handler")
  2896  	}), optQuietLog)
  2897  	defer cst.close()
  2898  	req, _ := NewRequest("GET", cst.ts.URL, nil)
  2899  	var bytesPerHeader = len("header12345: val12345\r\n")
  2900  	for i := 0; i < ((DefaultMaxHeaderBytes+4096)/bytesPerHeader)+1; i++ {
  2901  		req.Header.Set(fmt.Sprintf("header%05d", i), fmt.Sprintf("val%05d", i))
  2902  	}
  2903  	res, err := cst.c.Do(req)
  2904  	if res != nil {
  2905  		defer res.Body.Close()
  2906  	}
  2907  	if h2 {
  2908  		// In HTTP/2, the result depends on a race. If the client has received the
  2909  		// server's SETTINGS before RoundTrip starts sending the request, then RoundTrip
  2910  		// will fail with an error. Otherwise, the client should receive a 431 from the
  2911  		// server.
  2912  		if err == nil && res.StatusCode != 431 {
  2913  			t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
  2914  		}
  2915  	} else {
  2916  		// In HTTP/1, we expect a 431 from the server.
  2917  		// Some HTTP clients may fail on this undefined behavior (server replying and
  2918  		// closing the connection while the request is still being written), but
  2919  		// we do support it (at least currently), so we expect a response below.
  2920  		if err != nil {
  2921  			t.Fatalf("Do: %v", err)
  2922  		}
  2923  		if res.StatusCode != 431 {
  2924  			t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
  2925  		}
  2926  	}
  2927  }
  2928  
  2929  type neverEnding byte
  2930  
  2931  func (b neverEnding) Read(p []byte) (n int, err error) {
  2932  	for i := range p {
  2933  		p[i] = byte(b)
  2934  	}
  2935  	return len(p), nil
  2936  }
  2937  
  2938  type countReader struct {
  2939  	r io.Reader
  2940  	n *int64
  2941  }
  2942  
  2943  func (cr countReader) Read(p []byte) (n int, err error) {
  2944  	n, err = cr.r.Read(p)
  2945  	atomic.AddInt64(cr.n, int64(n))
  2946  	return
  2947  }
  2948  
  2949  func TestRequestBodyLimit_h1(t *testing.T) { testRequestBodyLimit(t, h1Mode) }
  2950  func TestRequestBodyLimit_h2(t *testing.T) { testRequestBodyLimit(t, h2Mode) }
  2951  func testRequestBodyLimit(t *testing.T, h2 bool) {
  2952  	setParallel(t)
  2953  	defer afterTest(t)
  2954  	const limit = 1 << 20
  2955  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2956  		r.Body = MaxBytesReader(w, r.Body, limit)
  2957  		n, err := io.Copy(ioutil.Discard, r.Body)
  2958  		if err == nil {
  2959  			t.Errorf("expected error from io.Copy")
  2960  		}
  2961  		if n != limit {
  2962  			t.Errorf("io.Copy = %d, want %d", n, limit)
  2963  		}
  2964  	}))
  2965  	defer cst.close()
  2966  
  2967  	nWritten := new(int64)
  2968  	req, _ := NewRequest("POST", cst.ts.URL, io.LimitReader(countReader{neverEnding('a'), nWritten}, limit*200))
  2969  
  2970  	// Send the POST, but don't care it succeeds or not. The
  2971  	// remote side is going to reply and then close the TCP
  2972  	// connection, and HTTP doesn't really define if that's
  2973  	// allowed or not. Some HTTP clients will get the response
  2974  	// and some (like ours, currently) will complain that the
  2975  	// request write failed, without reading the response.
  2976  	//
  2977  	// But that's okay, since what we're really testing is that
  2978  	// the remote side hung up on us before we wrote too much.
  2979  	_, _ = cst.c.Do(req)
  2980  
  2981  	if atomic.LoadInt64(nWritten) > limit*100 {
  2982  		t.Errorf("handler restricted the request body to %d bytes, but client managed to write %d",
  2983  			limit, nWritten)
  2984  	}
  2985  }
  2986  
  2987  // TestClientWriteShutdown tests that if the client shuts down the write
  2988  // side of their TCP connection, the server doesn't send a 400 Bad Request.
  2989  func TestClientWriteShutdown(t *testing.T) {
  2990  	if runtime.GOOS == "plan9" {
  2991  		t.Skip("skipping test; see https://golang.org/issue/7237")
  2992  	}
  2993  	defer afterTest(t)
  2994  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  2995  	defer ts.Close()
  2996  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  2997  	if err != nil {
  2998  		t.Fatalf("Dial: %v", err)
  2999  	}
  3000  	err = conn.(*net.TCPConn).CloseWrite()
  3001  	if err != nil {
  3002  		t.Fatalf("CloseWrite: %v", err)
  3003  	}
  3004  	donec := make(chan bool)
  3005  	go func() {
  3006  		defer close(donec)
  3007  		bs, err := ioutil.ReadAll(conn)
  3008  		if err != nil {
  3009  			t.Errorf("ReadAll: %v", err)
  3010  		}
  3011  		got := string(bs)
  3012  		if got != "" {
  3013  			t.Errorf("read %q from server; want nothing", got)
  3014  		}
  3015  	}()
  3016  	select {
  3017  	case <-donec:
  3018  	case <-time.After(10 * time.Second):
  3019  		t.Fatalf("timeout")
  3020  	}
  3021  }
  3022  
  3023  // Tests that chunked server responses that write 1 byte at a time are
  3024  // buffered before chunk headers are added, not after chunk headers.
  3025  func TestServerBufferedChunking(t *testing.T) {
  3026  	conn := new(testConn)
  3027  	conn.readBuf.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
  3028  	conn.closec = make(chan bool, 1)
  3029  	ls := &oneConnListener{conn}
  3030  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3031  		rw.(Flusher).Flush() // force the Header to be sent, in chunking mode, not counting the length
  3032  		rw.Write([]byte{'x'})
  3033  		rw.Write([]byte{'y'})
  3034  		rw.Write([]byte{'z'})
  3035  	}))
  3036  	<-conn.closec
  3037  	if !bytes.HasSuffix(conn.writeBuf.Bytes(), []byte("\r\n\r\n3\r\nxyz\r\n0\r\n\r\n")) {
  3038  		t.Errorf("response didn't end with a single 3 byte 'xyz' chunk; got:\n%q",
  3039  			conn.writeBuf.Bytes())
  3040  	}
  3041  }
  3042  
  3043  // Tests that the server flushes its response headers out when it's
  3044  // ignoring the response body and waits a bit before forcefully
  3045  // closing the TCP connection, causing the client to get a RST.
  3046  // See https://golang.org/issue/3595
  3047  func TestServerGracefulClose(t *testing.T) {
  3048  	setParallel(t)
  3049  	defer afterTest(t)
  3050  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3051  		Error(w, "bye", StatusUnauthorized)
  3052  	}))
  3053  	defer ts.Close()
  3054  
  3055  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3056  	if err != nil {
  3057  		t.Fatal(err)
  3058  	}
  3059  	defer conn.Close()
  3060  	const bodySize = 5 << 20
  3061  	req := []byte(fmt.Sprintf("POST / HTTP/1.1\r\nHost: foo.com\r\nContent-Length: %d\r\n\r\n", bodySize))
  3062  	for i := 0; i < bodySize; i++ {
  3063  		req = append(req, 'x')
  3064  	}
  3065  	writeErr := make(chan error)
  3066  	go func() {
  3067  		_, err := conn.Write(req)
  3068  		writeErr <- err
  3069  	}()
  3070  	br := bufio.NewReader(conn)
  3071  	lineNum := 0
  3072  	for {
  3073  		line, err := br.ReadString('\n')
  3074  		if err == io.EOF {
  3075  			break
  3076  		}
  3077  		if err != nil {
  3078  			t.Fatalf("ReadLine: %v", err)
  3079  		}
  3080  		lineNum++
  3081  		if lineNum == 1 && !strings.Contains(line, "401 Unauthorized") {
  3082  			t.Errorf("Response line = %q; want a 401", line)
  3083  		}
  3084  	}
  3085  	// Wait for write to finish. This is a broken pipe on both
  3086  	// Darwin and Linux, but checking this isn't the point of
  3087  	// the test.
  3088  	<-writeErr
  3089  }
  3090  
  3091  func TestCaseSensitiveMethod_h1(t *testing.T) { testCaseSensitiveMethod(t, h1Mode) }
  3092  func TestCaseSensitiveMethod_h2(t *testing.T) { testCaseSensitiveMethod(t, h2Mode) }
  3093  func testCaseSensitiveMethod(t *testing.T, h2 bool) {
  3094  	defer afterTest(t)
  3095  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  3096  		if r.Method != "get" {
  3097  			t.Errorf(`Got method %q; want "get"`, r.Method)
  3098  		}
  3099  	}))
  3100  	defer cst.close()
  3101  	req, _ := NewRequest("get", cst.ts.URL, nil)
  3102  	res, err := cst.c.Do(req)
  3103  	if err != nil {
  3104  		t.Error(err)
  3105  		return
  3106  	}
  3107  
  3108  	res.Body.Close()
  3109  }
  3110  
  3111  // TestContentLengthZero tests that for both an HTTP/1.0 and HTTP/1.1
  3112  // request (both keep-alive), when a Handler never writes any
  3113  // response, the net/http package adds a "Content-Length: 0" response
  3114  // header.
  3115  func TestContentLengthZero(t *testing.T) {
  3116  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {}))
  3117  	defer ts.Close()
  3118  
  3119  	for _, version := range []string{"HTTP/1.0", "HTTP/1.1"} {
  3120  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3121  		if err != nil {
  3122  			t.Fatalf("error dialing: %v", err)
  3123  		}
  3124  		_, err = fmt.Fprintf(conn, "GET / %v\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n", version)
  3125  		if err != nil {
  3126  			t.Fatalf("error writing: %v", err)
  3127  		}
  3128  		req, _ := NewRequest("GET", "/", nil)
  3129  		res, err := ReadResponse(bufio.NewReader(conn), req)
  3130  		if err != nil {
  3131  			t.Fatalf("error reading response: %v", err)
  3132  		}
  3133  		if te := res.TransferEncoding; len(te) > 0 {
  3134  			t.Errorf("For version %q, Transfer-Encoding = %q; want none", version, te)
  3135  		}
  3136  		if cl := res.ContentLength; cl != 0 {
  3137  			t.Errorf("For version %q, Content-Length = %v; want 0", version, cl)
  3138  		}
  3139  		conn.Close()
  3140  	}
  3141  }
  3142  
  3143  func TestCloseNotifier(t *testing.T) {
  3144  	defer afterTest(t)
  3145  	gotReq := make(chan bool, 1)
  3146  	sawClose := make(chan bool, 1)
  3147  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  3148  		gotReq <- true
  3149  		cc := rw.(CloseNotifier).CloseNotify()
  3150  		<-cc
  3151  		sawClose <- true
  3152  	}))
  3153  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3154  	if err != nil {
  3155  		t.Fatalf("error dialing: %v", err)
  3156  	}
  3157  	diec := make(chan bool)
  3158  	go func() {
  3159  		_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
  3160  		if err != nil {
  3161  			t.Error(err)
  3162  			return
  3163  		}
  3164  		<-diec
  3165  		conn.Close()
  3166  	}()
  3167  For:
  3168  	for {
  3169  		select {
  3170  		case <-gotReq:
  3171  			diec <- true
  3172  		case <-sawClose:
  3173  			break For
  3174  		case <-time.After(5 * time.Second):
  3175  			t.Fatal("timeout")
  3176  		}
  3177  	}
  3178  	ts.Close()
  3179  }
  3180  
  3181  // Tests that a pipelined request does not cause the first request's
  3182  // Handler's CloseNotify channel to fire.
  3183  //
  3184  // Issue 13165 (where it used to deadlock), but behavior changed in Issue 23921.
  3185  func TestCloseNotifierPipelined(t *testing.T) {
  3186  	setParallel(t)
  3187  	defer afterTest(t)
  3188  	gotReq := make(chan bool, 2)
  3189  	sawClose := make(chan bool, 2)
  3190  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  3191  		gotReq <- true
  3192  		cc := rw.(CloseNotifier).CloseNotify()
  3193  		select {
  3194  		case <-cc:
  3195  			t.Error("unexpected CloseNotify")
  3196  		case <-time.After(100 * time.Millisecond):
  3197  		}
  3198  		sawClose <- true
  3199  	}))
  3200  	defer ts.Close()
  3201  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3202  	if err != nil {
  3203  		t.Fatalf("error dialing: %v", err)
  3204  	}
  3205  	diec := make(chan bool, 1)
  3206  	defer close(diec)
  3207  	go func() {
  3208  		const req = "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n"
  3209  		_, err = io.WriteString(conn, req+req) // two requests
  3210  		if err != nil {
  3211  			t.Error(err)
  3212  			return
  3213  		}
  3214  		<-diec
  3215  		conn.Close()
  3216  	}()
  3217  	reqs := 0
  3218  	closes := 0
  3219  	for {
  3220  		select {
  3221  		case <-gotReq:
  3222  			reqs++
  3223  			if reqs > 2 {
  3224  				t.Fatal("too many requests")
  3225  			}
  3226  		case <-sawClose:
  3227  			closes++
  3228  			if closes > 1 {
  3229  				return
  3230  			}
  3231  		case <-time.After(5 * time.Second):
  3232  			ts.CloseClientConnections()
  3233  			t.Fatal("timeout")
  3234  		}
  3235  	}
  3236  }
  3237  
  3238  func TestCloseNotifierChanLeak(t *testing.T) {
  3239  	defer afterTest(t)
  3240  	req := reqBytes("GET / HTTP/1.0\nHost: golang.org")
  3241  	for i := 0; i < 20; i++ {
  3242  		var output bytes.Buffer
  3243  		conn := &rwTestConn{
  3244  			Reader: bytes.NewReader(req),
  3245  			Writer: &output,
  3246  			closec: make(chan bool, 1),
  3247  		}
  3248  		ln := &oneConnListener{conn: conn}
  3249  		handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3250  			// Ignore the return value and never read from
  3251  			// it, testing that we don't leak goroutines
  3252  			// on the sending side:
  3253  			_ = rw.(CloseNotifier).CloseNotify()
  3254  		})
  3255  		go Serve(ln, handler)
  3256  		<-conn.closec
  3257  	}
  3258  }
  3259  
  3260  // Tests that we can use CloseNotifier in one request, and later call Hijack
  3261  // on a second request on the same connection.
  3262  //
  3263  // It also tests that the connReader stitches together its background
  3264  // 1-byte read for CloseNotifier when CloseNotifier doesn't fire with
  3265  // the rest of the second HTTP later.
  3266  //
  3267  // Issue 9763.
  3268  // HTTP/1-only test. (http2 doesn't have Hijack)
  3269  func TestHijackAfterCloseNotifier(t *testing.T) {
  3270  	defer afterTest(t)
  3271  	script := make(chan string, 2)
  3272  	script <- "closenotify"
  3273  	script <- "hijack"
  3274  	close(script)
  3275  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3276  		plan := <-script
  3277  		switch plan {
  3278  		default:
  3279  			panic("bogus plan; too many requests")
  3280  		case "closenotify":
  3281  			w.(CloseNotifier).CloseNotify() // discard result
  3282  			w.Header().Set("X-Addr", r.RemoteAddr)
  3283  		case "hijack":
  3284  			c, _, err := w.(Hijacker).Hijack()
  3285  			if err != nil {
  3286  				t.Errorf("Hijack in Handler: %v", err)
  3287  				return
  3288  			}
  3289  			if _, ok := c.(*net.TCPConn); !ok {
  3290  				// Verify it's not wrapped in some type.
  3291  				// Not strictly a go1 compat issue, but in practice it probably is.
  3292  				t.Errorf("type of hijacked conn is %T; want *net.TCPConn", c)
  3293  			}
  3294  			fmt.Fprintf(c, "HTTP/1.0 200 OK\r\nX-Addr: %v\r\nContent-Length: 0\r\n\r\n", r.RemoteAddr)
  3295  			c.Close()
  3296  			return
  3297  		}
  3298  	}))
  3299  	defer ts.Close()
  3300  	res1, err := Get(ts.URL)
  3301  	if err != nil {
  3302  		log.Fatal(err)
  3303  	}
  3304  	res2, err := Get(ts.URL)
  3305  	if err != nil {
  3306  		log.Fatal(err)
  3307  	}
  3308  	addr1 := res1.Header.Get("X-Addr")
  3309  	addr2 := res2.Header.Get("X-Addr")
  3310  	if addr1 == "" || addr1 != addr2 {
  3311  		t.Errorf("addr1, addr2 = %q, %q; want same", addr1, addr2)
  3312  	}
  3313  }
  3314  
  3315  func TestHijackBeforeRequestBodyRead(t *testing.T) {
  3316  	setParallel(t)
  3317  	defer afterTest(t)
  3318  	var requestBody = bytes.Repeat([]byte("a"), 1<<20)
  3319  	bodyOkay := make(chan bool, 1)
  3320  	gotCloseNotify := make(chan bool, 1)
  3321  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3322  		defer close(bodyOkay) // caller will read false if nothing else
  3323  
  3324  		reqBody := r.Body
  3325  		r.Body = nil // to test that server.go doesn't use this value.
  3326  
  3327  		gone := w.(CloseNotifier).CloseNotify()
  3328  		slurp, err := ioutil.ReadAll(reqBody)
  3329  		if err != nil {
  3330  			t.Errorf("Body read: %v", err)
  3331  			return
  3332  		}
  3333  		if len(slurp) != len(requestBody) {
  3334  			t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody))
  3335  			return
  3336  		}
  3337  		if !bytes.Equal(slurp, requestBody) {
  3338  			t.Error("Backend read wrong request body.") // 1MB; omitting details
  3339  			return
  3340  		}
  3341  		bodyOkay <- true
  3342  		select {
  3343  		case <-gone:
  3344  			gotCloseNotify <- true
  3345  		case <-time.After(5 * time.Second):
  3346  			gotCloseNotify <- false
  3347  		}
  3348  	}))
  3349  	defer ts.Close()
  3350  
  3351  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3352  	if err != nil {
  3353  		t.Fatal(err)
  3354  	}
  3355  	defer conn.Close()
  3356  
  3357  	fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: foo\r\nContent-Length: %d\r\n\r\n%s",
  3358  		len(requestBody), requestBody)
  3359  	if !<-bodyOkay {
  3360  		// already failed.
  3361  		return
  3362  	}
  3363  	conn.Close()
  3364  	if !<-gotCloseNotify {
  3365  		t.Error("timeout waiting for CloseNotify")
  3366  	}
  3367  }
  3368  
  3369  func TestOptions(t *testing.T) {
  3370  	uric := make(chan string, 2) // only expect 1, but leave space for 2
  3371  	mux := NewServeMux()
  3372  	mux.HandleFunc("/", func(w ResponseWriter, r *Request) {
  3373  		uric <- r.RequestURI
  3374  	})
  3375  	ts := httptest.NewServer(mux)
  3376  	defer ts.Close()
  3377  
  3378  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3379  	if err != nil {
  3380  		t.Fatal(err)
  3381  	}
  3382  	defer conn.Close()
  3383  
  3384  	// An OPTIONS * request should succeed.
  3385  	_, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
  3386  	if err != nil {
  3387  		t.Fatal(err)
  3388  	}
  3389  	br := bufio.NewReader(conn)
  3390  	res, err := ReadResponse(br, &Request{Method: "OPTIONS"})
  3391  	if err != nil {
  3392  		t.Fatal(err)
  3393  	}
  3394  	if res.StatusCode != 200 {
  3395  		t.Errorf("Got non-200 response to OPTIONS *: %#v", res)
  3396  	}
  3397  
  3398  	// A GET * request on a ServeMux should fail.
  3399  	_, err = conn.Write([]byte("GET * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
  3400  	if err != nil {
  3401  		t.Fatal(err)
  3402  	}
  3403  	res, err = ReadResponse(br, &Request{Method: "GET"})
  3404  	if err != nil {
  3405  		t.Fatal(err)
  3406  	}
  3407  	if res.StatusCode != 400 {
  3408  		t.Errorf("Got non-400 response to GET *: %#v", res)
  3409  	}
  3410  
  3411  	res, err = Get(ts.URL + "/second")
  3412  	if err != nil {
  3413  		t.Fatal(err)
  3414  	}
  3415  	res.Body.Close()
  3416  	if got := <-uric; got != "/second" {
  3417  		t.Errorf("Handler saw request for %q; want /second", got)
  3418  	}
  3419  }
  3420  
  3421  // Tests regarding the ordering of Write, WriteHeader, Header, and
  3422  // Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the
  3423  // (*response).header to the wire. In Go 1.1, the actual wire flush is
  3424  // delayed, so we could maybe tack on a Content-Length and better
  3425  // Content-Type after we see more (or all) of the output. To preserve
  3426  // compatibility with Go 1, we need to be careful to track which
  3427  // headers were live at the time of WriteHeader, so we write the same
  3428  // ones, even if the handler modifies them (~erroneously) after the
  3429  // first Write.
  3430  func TestHeaderToWire(t *testing.T) {
  3431  	tests := []struct {
  3432  		name    string
  3433  		handler func(ResponseWriter, *Request)
  3434  		check   func(got, logs string) error
  3435  	}{
  3436  		{
  3437  			name: "write without Header",
  3438  			handler: func(rw ResponseWriter, r *Request) {
  3439  				rw.Write([]byte("hello world"))
  3440  			},
  3441  			check: func(got, logs string) error {
  3442  				if !strings.Contains(got, "Content-Length:") {
  3443  					return errors.New("no content-length")
  3444  				}
  3445  				if !strings.Contains(got, "Content-Type: text/plain") {
  3446  					return errors.New("no content-type")
  3447  				}
  3448  				return nil
  3449  			},
  3450  		},
  3451  		{
  3452  			name: "Header mutation before write",
  3453  			handler: func(rw ResponseWriter, r *Request) {
  3454  				h := rw.Header()
  3455  				h.Set("Content-Type", "some/type")
  3456  				rw.Write([]byte("hello world"))
  3457  				h.Set("Too-Late", "bogus")
  3458  			},
  3459  			check: func(got, logs string) error {
  3460  				if !strings.Contains(got, "Content-Length:") {
  3461  					return errors.New("no content-length")
  3462  				}
  3463  				if !strings.Contains(got, "Content-Type: some/type") {
  3464  					return errors.New("wrong content-type")
  3465  				}
  3466  				if strings.Contains(got, "Too-Late") {
  3467  					return errors.New("don't want too-late header")
  3468  				}
  3469  				return nil
  3470  			},
  3471  		},
  3472  		{
  3473  			name: "write then useless Header mutation",
  3474  			handler: func(rw ResponseWriter, r *Request) {
  3475  				rw.Write([]byte("hello world"))
  3476  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3477  			},
  3478  			check: func(got, logs string) error {
  3479  				if strings.Contains(got, "Too-Late") {
  3480  					return errors.New("header appeared from after WriteHeader")
  3481  				}
  3482  				return nil
  3483  			},
  3484  		},
  3485  		{
  3486  			name: "flush then write",
  3487  			handler: func(rw ResponseWriter, r *Request) {
  3488  				rw.(Flusher).Flush()
  3489  				rw.Write([]byte("post-flush"))
  3490  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3491  			},
  3492  			check: func(got, logs string) error {
  3493  				if !strings.Contains(got, "Transfer-Encoding: chunked") {
  3494  					return errors.New("not chunked")
  3495  				}
  3496  				if strings.Contains(got, "Too-Late") {
  3497  					return errors.New("header appeared from after WriteHeader")
  3498  				}
  3499  				return nil
  3500  			},
  3501  		},
  3502  		{
  3503  			name: "header then flush",
  3504  			handler: func(rw ResponseWriter, r *Request) {
  3505  				rw.Header().Set("Content-Type", "some/type")
  3506  				rw.(Flusher).Flush()
  3507  				rw.Write([]byte("post-flush"))
  3508  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3509  			},
  3510  			check: func(got, logs string) error {
  3511  				if !strings.Contains(got, "Transfer-Encoding: chunked") {
  3512  					return errors.New("not chunked")
  3513  				}
  3514  				if strings.Contains(got, "Too-Late") {
  3515  					return errors.New("header appeared from after WriteHeader")
  3516  				}
  3517  				if !strings.Contains(got, "Content-Type: some/type") {
  3518  					return errors.New("wrong content-type")
  3519  				}
  3520  				return nil
  3521  			},
  3522  		},
  3523  		{
  3524  			name: "sniff-on-first-write content-type",
  3525  			handler: func(rw ResponseWriter, r *Request) {
  3526  				rw.Write([]byte("<html><head></head><body>some html</body></html>"))
  3527  				rw.Header().Set("Content-Type", "x/wrong")
  3528  			},
  3529  			check: func(got, logs string) error {
  3530  				if !strings.Contains(got, "Content-Type: text/html") {
  3531  					return errors.New("wrong content-type; want html")
  3532  				}
  3533  				return nil
  3534  			},
  3535  		},
  3536  		{
  3537  			name: "explicit content-type wins",
  3538  			handler: func(rw ResponseWriter, r *Request) {
  3539  				rw.Header().Set("Content-Type", "some/type")
  3540  				rw.Write([]byte("<html><head></head><body>some html</body></html>"))
  3541  			},
  3542  			check: func(got, logs string) error {
  3543  				if !strings.Contains(got, "Content-Type: some/type") {
  3544  					return errors.New("wrong content-type; want html")
  3545  				}
  3546  				return nil
  3547  			},
  3548  		},
  3549  		{
  3550  			name: "empty handler",
  3551  			handler: func(rw ResponseWriter, r *Request) {
  3552  			},
  3553  			check: func(got, logs string) error {
  3554  				if !strings.Contains(got, "Content-Length: 0") {
  3555  					return errors.New("want 0 content-length")
  3556  				}
  3557  				return nil
  3558  			},
  3559  		},
  3560  		{
  3561  			name: "only Header, no write",
  3562  			handler: func(rw ResponseWriter, r *Request) {
  3563  				rw.Header().Set("Some-Header", "some-value")
  3564  			},
  3565  			check: func(got, logs string) error {
  3566  				if !strings.Contains(got, "Some-Header") {
  3567  					return errors.New("didn't get header")
  3568  				}
  3569  				return nil
  3570  			},
  3571  		},
  3572  		{
  3573  			name: "WriteHeader call",
  3574  			handler: func(rw ResponseWriter, r *Request) {
  3575  				rw.WriteHeader(404)
  3576  				rw.Header().Set("Too-Late", "some-value")
  3577  			},
  3578  			check: func(got, logs string) error {
  3579  				if !strings.Contains(got, "404") {
  3580  					return errors.New("wrong status")
  3581  				}
  3582  				if strings.Contains(got, "Too-Late") {
  3583  					return errors.New("shouldn't have seen Too-Late")
  3584  				}
  3585  				return nil
  3586  			},
  3587  		},
  3588  	}
  3589  	for _, tc := range tests {
  3590  		ht := newHandlerTest(HandlerFunc(tc.handler))
  3591  		got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org")
  3592  		logs := ht.logbuf.String()
  3593  		if err := tc.check(got, logs); err != nil {
  3594  			t.Errorf("%s: %v\nGot response:\n%s\n\n%s", tc.name, err, got, logs)
  3595  		}
  3596  	}
  3597  }
  3598  
  3599  // goTimeout runs f, failing t if f takes more than ns to complete.
  3600  func goTimeout(t *testing.T, d time.Duration, f func()) {
  3601  	ch := make(chan bool, 2)
  3602  	timer := time.AfterFunc(d, func() {
  3603  		t.Errorf("Timeout expired after %v", d)
  3604  		ch <- true
  3605  	})
  3606  	defer timer.Stop()
  3607  	go func() {
  3608  		defer func() { ch <- true }()
  3609  		f()
  3610  	}()
  3611  	<-ch
  3612  }
  3613  
  3614  type errorListener struct {
  3615  	errs []error
  3616  }
  3617  
  3618  func (l *errorListener) Accept() (c net.Conn, err error) {
  3619  	if len(l.errs) == 0 {
  3620  		return nil, io.EOF
  3621  	}
  3622  	err = l.errs[0]
  3623  	l.errs = l.errs[1:]
  3624  	return
  3625  }
  3626  
  3627  func (l *errorListener) Close() error {
  3628  	return nil
  3629  }
  3630  
  3631  func (l *errorListener) Addr() net.Addr {
  3632  	return dummyAddr("test-address")
  3633  }
  3634  
  3635  func TestAcceptMaxFds(t *testing.T) {
  3636  	setParallel(t)
  3637  
  3638  	ln := &errorListener{[]error{
  3639  		&net.OpError{
  3640  			Op:  "accept",
  3641  			Err: syscall.EMFILE,
  3642  		}}}
  3643  	server := &Server{
  3644  		Handler:  HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {})),
  3645  		ErrorLog: log.New(ioutil.Discard, "", 0), // noisy otherwise
  3646  	}
  3647  	err := server.Serve(ln)
  3648  	if err != io.EOF {
  3649  		t.Errorf("got error %v, want EOF", err)
  3650  	}
  3651  }
  3652  
  3653  func TestWriteAfterHijack(t *testing.T) {
  3654  	req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
  3655  	var buf bytes.Buffer
  3656  	wrotec := make(chan bool, 1)
  3657  	conn := &rwTestConn{
  3658  		Reader: bytes.NewReader(req),
  3659  		Writer: &buf,
  3660  		closec: make(chan bool, 1),
  3661  	}
  3662  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3663  		conn, bufrw, err := rw.(Hijacker).Hijack()
  3664  		if err != nil {
  3665  			t.Error(err)
  3666  			return
  3667  		}
  3668  		go func() {
  3669  			bufrw.Write([]byte("[hijack-to-bufw]"))
  3670  			bufrw.Flush()
  3671  			conn.Write([]byte("[hijack-to-conn]"))
  3672  			conn.Close()
  3673  			wrotec <- true
  3674  		}()
  3675  	})
  3676  	ln := &oneConnListener{conn: conn}
  3677  	go Serve(ln, handler)
  3678  	<-conn.closec
  3679  	<-wrotec
  3680  	if g, w := buf.String(), "[hijack-to-bufw][hijack-to-conn]"; g != w {
  3681  		t.Errorf("wrote %q; want %q", g, w)
  3682  	}
  3683  }
  3684  
  3685  func TestDoubleHijack(t *testing.T) {
  3686  	req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
  3687  	var buf bytes.Buffer
  3688  	conn := &rwTestConn{
  3689  		Reader: bytes.NewReader(req),
  3690  		Writer: &buf,
  3691  		closec: make(chan bool, 1),
  3692  	}
  3693  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3694  		conn, _, err := rw.(Hijacker).Hijack()
  3695  		if err != nil {
  3696  			t.Error(err)
  3697  			return
  3698  		}
  3699  		_, _, err = rw.(Hijacker).Hijack()
  3700  		if err == nil {
  3701  			t.Errorf("got err = nil;  want err != nil")
  3702  		}
  3703  		conn.Close()
  3704  	})
  3705  	ln := &oneConnListener{conn: conn}
  3706  	go Serve(ln, handler)
  3707  	<-conn.closec
  3708  }
  3709  
  3710  // https://golang.org/issue/5955
  3711  // Note that this does not test the "request too large"
  3712  // exit path from the http server. This is intentional;
  3713  // not sending Connection: close is just a minor wire
  3714  // optimization and is pointless if dealing with a
  3715  // badly behaved client.
  3716  func TestHTTP10ConnectionHeader(t *testing.T) {
  3717  	defer afterTest(t)
  3718  
  3719  	mux := NewServeMux()
  3720  	mux.Handle("/", HandlerFunc(func(ResponseWriter, *Request) {}))
  3721  	ts := httptest.NewServer(mux)
  3722  	defer ts.Close()
  3723  
  3724  	// net/http uses HTTP/1.1 for requests, so write requests manually
  3725  	tests := []struct {
  3726  		req    string   // raw http request
  3727  		expect []string // expected Connection header(s)
  3728  	}{
  3729  		{
  3730  			req:    "GET / HTTP/1.0\r\n\r\n",
  3731  			expect: nil,
  3732  		},
  3733  		{
  3734  			req:    "OPTIONS * HTTP/1.0\r\n\r\n",
  3735  			expect: nil,
  3736  		},
  3737  		{
  3738  			req:    "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n",
  3739  			expect: []string{"keep-alive"},
  3740  		},
  3741  	}
  3742  
  3743  	for _, tt := range tests {
  3744  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3745  		if err != nil {
  3746  			t.Fatal("dial err:", err)
  3747  		}
  3748  
  3749  		_, err = fmt.Fprint(conn, tt.req)
  3750  		if err != nil {
  3751  			t.Fatal("conn write err:", err)
  3752  		}
  3753  
  3754  		resp, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "GET"})
  3755  		if err != nil {
  3756  			t.Fatal("ReadResponse err:", err)
  3757  		}
  3758  		conn.Close()
  3759  		resp.Body.Close()
  3760  
  3761  		got := resp.Header["Connection"]
  3762  		if !reflect.DeepEqual(got, tt.expect) {
  3763  			t.Errorf("wrong Connection headers for request %q. Got %q expect %q", tt.req, got, tt.expect)
  3764  		}
  3765  	}
  3766  }
  3767  
  3768  // See golang.org/issue/5660
  3769  func TestServerReaderFromOrder_h1(t *testing.T) { testServerReaderFromOrder(t, h1Mode) }
  3770  func TestServerReaderFromOrder_h2(t *testing.T) { testServerReaderFromOrder(t, h2Mode) }
  3771  func testServerReaderFromOrder(t *testing.T, h2 bool) {
  3772  	setParallel(t)
  3773  	defer afterTest(t)
  3774  	pr, pw := io.Pipe()
  3775  	const size = 3 << 20
  3776  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3777  		rw.Header().Set("Content-Type", "text/plain") // prevent sniffing path
  3778  		done := make(chan bool)
  3779  		go func() {
  3780  			io.Copy(rw, pr)
  3781  			close(done)
  3782  		}()
  3783  		time.Sleep(25 * time.Millisecond) // give Copy a chance to break things
  3784  		n, err := io.Copy(ioutil.Discard, req.Body)
  3785  		if err != nil {
  3786  			t.Errorf("handler Copy: %v", err)
  3787  			return
  3788  		}
  3789  		if n != size {
  3790  			t.Errorf("handler Copy = %d; want %d", n, size)
  3791  		}
  3792  		pw.Write([]byte("hi"))
  3793  		pw.Close()
  3794  		<-done
  3795  	}))
  3796  	defer cst.close()
  3797  
  3798  	req, err := NewRequest("POST", cst.ts.URL, io.LimitReader(neverEnding('a'), size))
  3799  	if err != nil {
  3800  		t.Fatal(err)
  3801  	}
  3802  	res, err := cst.c.Do(req)
  3803  	if err != nil {
  3804  		t.Fatal(err)
  3805  	}
  3806  	all, err := ioutil.ReadAll(res.Body)
  3807  	if err != nil {
  3808  		t.Fatal(err)
  3809  	}
  3810  	res.Body.Close()
  3811  	if string(all) != "hi" {
  3812  		t.Errorf("Body = %q; want hi", all)
  3813  	}
  3814  }
  3815  
  3816  // Issue 6157, Issue 6685
  3817  func TestCodesPreventingContentTypeAndBody(t *testing.T) {
  3818  	for _, code := range []int{StatusNotModified, StatusNoContent, StatusContinue} {
  3819  		ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  3820  			if r.URL.Path == "/header" {
  3821  				w.Header().Set("Content-Length", "123")
  3822  			}
  3823  			w.WriteHeader(code)
  3824  			if r.URL.Path == "/more" {
  3825  				w.Write([]byte("stuff"))
  3826  			}
  3827  		}))
  3828  		for _, req := range []string{
  3829  			"GET / HTTP/1.0",
  3830  			"GET /header HTTP/1.0",
  3831  			"GET /more HTTP/1.0",
  3832  			"GET / HTTP/1.1\nHost: foo",
  3833  			"GET /header HTTP/1.1\nHost: foo",
  3834  			"GET /more HTTP/1.1\nHost: foo",
  3835  		} {
  3836  			got := ht.rawResponse(req)
  3837  			wantStatus := fmt.Sprintf("%d %s", code, StatusText(code))
  3838  			if !strings.Contains(got, wantStatus) {
  3839  				t.Errorf("Code %d: Wanted %q Modified for %q: %s", code, wantStatus, req, got)
  3840  			} else if strings.Contains(got, "Content-Length") {
  3841  				t.Errorf("Code %d: Got a Content-Length from %q: %s", code, req, got)
  3842  			} else if strings.Contains(got, "stuff") {
  3843  				t.Errorf("Code %d: Response contains a body from %q: %s", code, req, got)
  3844  			}
  3845  		}
  3846  	}
  3847  }
  3848  
  3849  func TestContentTypeOkayOn204(t *testing.T) {
  3850  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  3851  		w.Header().Set("Content-Length", "123") // suppressed
  3852  		w.Header().Set("Content-Type", "foo/bar")
  3853  		w.WriteHeader(204)
  3854  	}))
  3855  	got := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  3856  	if !strings.Contains(got, "Content-Type: foo/bar") {
  3857  		t.Errorf("Response = %q; want Content-Type: foo/bar", got)
  3858  	}
  3859  	if strings.Contains(got, "Content-Length: 123") {
  3860  		t.Errorf("Response = %q; don't want a Content-Length", got)
  3861  	}
  3862  }
  3863  
  3864  // Issue 6995
  3865  // A server Handler can receive a Request, and then turn around and
  3866  // give a copy of that Request.Body out to the Transport (e.g. any
  3867  // proxy).  So then two people own that Request.Body (both the server
  3868  // and the http client), and both think they can close it on failure.
  3869  // Therefore, all incoming server requests Bodies need to be thread-safe.
  3870  func TestTransportAndServerSharedBodyRace_h1(t *testing.T) {
  3871  	testTransportAndServerSharedBodyRace(t, h1Mode)
  3872  }
  3873  func TestTransportAndServerSharedBodyRace_h2(t *testing.T) {
  3874  	testTransportAndServerSharedBodyRace(t, h2Mode)
  3875  }
  3876  func testTransportAndServerSharedBodyRace(t *testing.T, h2 bool) {
  3877  	setParallel(t)
  3878  	defer afterTest(t)
  3879  
  3880  	const bodySize = 1 << 20
  3881  
  3882  	// errorf is like t.Errorf, but also writes to println. When
  3883  	// this test fails, it hangs. This helps debugging and I've
  3884  	// added this enough times "temporarily".  It now gets added
  3885  	// full time.
  3886  	errorf := func(format string, args ...interface{}) {
  3887  		v := fmt.Sprintf(format, args...)
  3888  		println(v)
  3889  		t.Error(v)
  3890  	}
  3891  
  3892  	unblockBackend := make(chan bool)
  3893  	backend := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3894  		gone := rw.(CloseNotifier).CloseNotify()
  3895  		didCopy := make(chan interface{})
  3896  		go func() {
  3897  			n, err := io.CopyN(rw, req.Body, bodySize)
  3898  			didCopy <- []interface{}{n, err}
  3899  		}()
  3900  		isGone := false
  3901  	Loop:
  3902  		for {
  3903  			select {
  3904  			case <-didCopy:
  3905  				break Loop
  3906  			case <-gone:
  3907  				isGone = true
  3908  			case <-time.After(time.Second):
  3909  				println("1 second passes in backend, proxygone=", isGone)
  3910  			}
  3911  		}
  3912  		<-unblockBackend
  3913  	}))
  3914  	var quitTimer *time.Timer
  3915  	defer func() { quitTimer.Stop() }()
  3916  	defer backend.close()
  3917  
  3918  	backendRespc := make(chan *Response, 1)
  3919  	var proxy *clientServerTest
  3920  	proxy = newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3921  		req2, _ := NewRequest("POST", backend.ts.URL, req.Body)
  3922  		req2.ContentLength = bodySize
  3923  		cancel := make(chan struct{})
  3924  		req2.Cancel = cancel
  3925  
  3926  		bresp, err := proxy.c.Do(req2)
  3927  		if err != nil {
  3928  			errorf("Proxy outbound request: %v", err)
  3929  			return
  3930  		}
  3931  		_, err = io.CopyN(ioutil.Discard, bresp.Body, bodySize/2)
  3932  		if err != nil {
  3933  			errorf("Proxy copy error: %v", err)
  3934  			return
  3935  		}
  3936  		backendRespc <- bresp // to close later
  3937  
  3938  		// Try to cause a race: Both the Transport and the proxy handler's Server
  3939  		// will try to read/close req.Body (aka req2.Body)
  3940  		if h2 {
  3941  			close(cancel)
  3942  		} else {
  3943  			proxy.c.Transport.(*Transport).CancelRequest(req2)
  3944  		}
  3945  		rw.Write([]byte("OK"))
  3946  	}))
  3947  	defer proxy.close()
  3948  	defer func() {
  3949  		// Before we shut down our two httptest.Servers, start a timer.
  3950  		// We choose 7 seconds because httptest.Server starts logging
  3951  		// warnings to stderr at 5 seconds. If we don't disarm this bomb
  3952  		// in 7 seconds (after the two httptest.Server.Close calls above),
  3953  		// then we explode with stacks.
  3954  		quitTimer = time.AfterFunc(7*time.Second, func() {
  3955  			debug.SetTraceback("ALL")
  3956  			stacks := make([]byte, 1<<20)
  3957  			stacks = stacks[:runtime.Stack(stacks, true)]
  3958  			fmt.Fprintf(os.Stderr, "%s", stacks)
  3959  			log.Fatalf("Timeout.")
  3960  		})
  3961  	}()
  3962  
  3963  	defer close(unblockBackend)
  3964  	req, _ := NewRequest("POST", proxy.ts.URL, io.LimitReader(neverEnding('a'), bodySize))
  3965  	res, err := proxy.c.Do(req)
  3966  	if err != nil {
  3967  		t.Fatalf("Original request: %v", err)
  3968  	}
  3969  
  3970  	// Cleanup, so we don't leak goroutines.
  3971  	res.Body.Close()
  3972  	select {
  3973  	case res := <-backendRespc:
  3974  		res.Body.Close()
  3975  	default:
  3976  		// We failed earlier. (e.g. on proxy.c.Do(req2))
  3977  	}
  3978  }
  3979  
  3980  // Test that a hanging Request.Body.Read from another goroutine can't
  3981  // cause the Handler goroutine's Request.Body.Close to block.
  3982  // See issue 7121.
  3983  func TestRequestBodyCloseDoesntBlock(t *testing.T) {
  3984  	if testing.Short() {
  3985  		t.Skip("skipping in -short mode")
  3986  	}
  3987  	defer afterTest(t)
  3988  
  3989  	readErrCh := make(chan error, 1)
  3990  	errCh := make(chan error, 2)
  3991  
  3992  	server := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  3993  		go func(body io.Reader) {
  3994  			_, err := body.Read(make([]byte, 100))
  3995  			readErrCh <- err
  3996  		}(req.Body)
  3997  		time.Sleep(500 * time.Millisecond)
  3998  	}))
  3999  	defer server.Close()
  4000  
  4001  	closeConn := make(chan bool)
  4002  	defer close(closeConn)
  4003  	go func() {
  4004  		conn, err := net.Dial("tcp", server.Listener.Addr().String())
  4005  		if err != nil {
  4006  			errCh <- err
  4007  			return
  4008  		}
  4009  		defer conn.Close()
  4010  		_, err = conn.Write([]byte("POST / HTTP/1.1\r\nConnection: close\r\nHost: foo\r\nContent-Length: 100000\r\n\r\n"))
  4011  		if err != nil {
  4012  			errCh <- err
  4013  			return
  4014  		}
  4015  		// And now just block, making the server block on our
  4016  		// 100000 bytes of body that will never arrive.
  4017  		<-closeConn
  4018  	}()
  4019  	select {
  4020  	case err := <-readErrCh:
  4021  		if err == nil {
  4022  			t.Error("Read was nil. Expected error.")
  4023  		}
  4024  	case err := <-errCh:
  4025  		t.Error(err)
  4026  	case <-time.After(5 * time.Second):
  4027  		t.Error("timeout")
  4028  	}
  4029  }
  4030  
  4031  // test that ResponseWriter implements io.stringWriter.
  4032  func TestResponseWriterWriteString(t *testing.T) {
  4033  	okc := make(chan bool, 1)
  4034  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4035  		type stringWriter interface {
  4036  			WriteString(s string) (n int, err error)
  4037  		}
  4038  		_, ok := w.(stringWriter)
  4039  		okc <- ok
  4040  	}))
  4041  	ht.rawResponse("GET / HTTP/1.0")
  4042  	select {
  4043  	case ok := <-okc:
  4044  		if !ok {
  4045  			t.Error("ResponseWriter did not implement io.stringWriter")
  4046  		}
  4047  	default:
  4048  		t.Error("handler was never called")
  4049  	}
  4050  }
  4051  
  4052  func TestAppendTime(t *testing.T) {
  4053  	var b [len(TimeFormat)]byte
  4054  	t1 := time.Date(2013, 9, 21, 15, 41, 0, 0, time.FixedZone("CEST", 2*60*60))
  4055  	res := ExportAppendTime(b[:0], t1)
  4056  	t2, err := ParseTime(string(res))
  4057  	if err != nil {
  4058  		t.Fatalf("Error parsing time: %s", err)
  4059  	}
  4060  	if !t1.Equal(t2) {
  4061  		t.Fatalf("Times differ; expected: %v, got %v (%s)", t1, t2, string(res))
  4062  	}
  4063  }
  4064  
  4065  func TestServerConnState(t *testing.T) {
  4066  	setParallel(t)
  4067  	defer afterTest(t)
  4068  	handler := map[string]func(w ResponseWriter, r *Request){
  4069  		"/": func(w ResponseWriter, r *Request) {
  4070  			fmt.Fprintf(w, "Hello.")
  4071  		},
  4072  		"/close": func(w ResponseWriter, r *Request) {
  4073  			w.Header().Set("Connection", "close")
  4074  			fmt.Fprintf(w, "Hello.")
  4075  		},
  4076  		"/hijack": func(w ResponseWriter, r *Request) {
  4077  			c, _, _ := w.(Hijacker).Hijack()
  4078  			c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
  4079  			c.Close()
  4080  		},
  4081  		"/hijack-panic": func(w ResponseWriter, r *Request) {
  4082  			c, _, _ := w.(Hijacker).Hijack()
  4083  			c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
  4084  			c.Close()
  4085  			panic("intentional panic")
  4086  		},
  4087  	}
  4088  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4089  		handler[r.URL.Path](w, r)
  4090  	}))
  4091  	defer ts.Close()
  4092  
  4093  	var mu sync.Mutex // guard stateLog and connID
  4094  	var stateLog = map[int][]ConnState{}
  4095  	var connID = map[net.Conn]int{}
  4096  
  4097  	ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
  4098  	ts.Config.ConnState = func(c net.Conn, state ConnState) {
  4099  		if c == nil {
  4100  			t.Errorf("nil conn seen in state %s", state)
  4101  			return
  4102  		}
  4103  		mu.Lock()
  4104  		defer mu.Unlock()
  4105  		id, ok := connID[c]
  4106  		if !ok {
  4107  			id = len(connID) + 1
  4108  			connID[c] = id
  4109  		}
  4110  		stateLog[id] = append(stateLog[id], state)
  4111  	}
  4112  	ts.Start()
  4113  
  4114  	c := ts.Client()
  4115  
  4116  	mustGet := func(url string, headers ...string) {
  4117  		req, err := NewRequest("GET", url, nil)
  4118  		if err != nil {
  4119  			t.Fatal(err)
  4120  		}
  4121  		for len(headers) > 0 {
  4122  			req.Header.Add(headers[0], headers[1])
  4123  			headers = headers[2:]
  4124  		}
  4125  		res, err := c.Do(req)
  4126  		if err != nil {
  4127  			t.Errorf("Error fetching %s: %v", url, err)
  4128  			return
  4129  		}
  4130  		_, err = ioutil.ReadAll(res.Body)
  4131  		defer res.Body.Close()
  4132  		if err != nil {
  4133  			t.Errorf("Error reading %s: %v", url, err)
  4134  		}
  4135  	}
  4136  
  4137  	mustGet(ts.URL + "/")
  4138  	mustGet(ts.URL + "/close")
  4139  
  4140  	mustGet(ts.URL + "/")
  4141  	mustGet(ts.URL+"/", "Connection", "close")
  4142  
  4143  	mustGet(ts.URL + "/hijack")
  4144  	mustGet(ts.URL + "/hijack-panic")
  4145  
  4146  	// New->Closed
  4147  	{
  4148  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4149  		if err != nil {
  4150  			t.Fatal(err)
  4151  		}
  4152  		c.Close()
  4153  	}
  4154  
  4155  	// New->Active->Closed
  4156  	{
  4157  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4158  		if err != nil {
  4159  			t.Fatal(err)
  4160  		}
  4161  		if _, err := io.WriteString(c, "BOGUS REQUEST\r\n\r\n"); err != nil {
  4162  			t.Fatal(err)
  4163  		}
  4164  		c.Read(make([]byte, 1)) // block until server hangs up on us
  4165  		c.Close()
  4166  	}
  4167  
  4168  	// New->Idle->Closed
  4169  	{
  4170  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4171  		if err != nil {
  4172  			t.Fatal(err)
  4173  		}
  4174  		if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
  4175  			t.Fatal(err)
  4176  		}
  4177  		res, err := ReadResponse(bufio.NewReader(c), nil)
  4178  		if err != nil {
  4179  			t.Fatal(err)
  4180  		}
  4181  		if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
  4182  			t.Fatal(err)
  4183  		}
  4184  		c.Close()
  4185  	}
  4186  
  4187  	want := map[int][]ConnState{
  4188  		1: {StateNew, StateActive, StateIdle, StateActive, StateClosed},
  4189  		2: {StateNew, StateActive, StateIdle, StateActive, StateClosed},
  4190  		3: {StateNew, StateActive, StateHijacked},
  4191  		4: {StateNew, StateActive, StateHijacked},
  4192  		5: {StateNew, StateClosed},
  4193  		6: {StateNew, StateActive, StateClosed},
  4194  		7: {StateNew, StateActive, StateIdle, StateClosed},
  4195  	}
  4196  	logString := func(m map[int][]ConnState) string {
  4197  		var b bytes.Buffer
  4198  		var keys []int
  4199  		for id := range m {
  4200  			keys = append(keys, id)
  4201  		}
  4202  		sort.Ints(keys)
  4203  		for _, id := range keys {
  4204  			fmt.Fprintf(&b, "Conn %d: ", id)
  4205  			for _, s := range m[id] {
  4206  				fmt.Fprintf(&b, "%s ", s)
  4207  			}
  4208  			b.WriteString("\n")
  4209  		}
  4210  		return b.String()
  4211  	}
  4212  
  4213  	for i := 0; i < 5; i++ {
  4214  		time.Sleep(time.Duration(i) * 50 * time.Millisecond)
  4215  		mu.Lock()
  4216  		match := reflect.DeepEqual(stateLog, want)
  4217  		mu.Unlock()
  4218  		if match {
  4219  			return
  4220  		}
  4221  	}
  4222  
  4223  	mu.Lock()
  4224  	t.Errorf("Unexpected events.\nGot log:\n%s\n   Want:\n%s\n", logString(stateLog), logString(want))
  4225  	mu.Unlock()
  4226  }
  4227  
  4228  func TestServerKeepAlivesEnabled(t *testing.T) {
  4229  	defer afterTest(t)
  4230  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  4231  	ts.Config.SetKeepAlivesEnabled(false)
  4232  	ts.Start()
  4233  	defer ts.Close()
  4234  	res, err := Get(ts.URL)
  4235  	if err != nil {
  4236  		t.Fatal(err)
  4237  	}
  4238  	defer res.Body.Close()
  4239  	if !res.Close {
  4240  		t.Errorf("Body.Close == false; want true")
  4241  	}
  4242  }
  4243  
  4244  // golang.org/issue/7856
  4245  func TestServerEmptyBodyRace_h1(t *testing.T) { testServerEmptyBodyRace(t, h1Mode) }
  4246  func TestServerEmptyBodyRace_h2(t *testing.T) { testServerEmptyBodyRace(t, h2Mode) }
  4247  func testServerEmptyBodyRace(t *testing.T, h2 bool) {
  4248  	setParallel(t)
  4249  	defer afterTest(t)
  4250  	var n int32
  4251  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  4252  		atomic.AddInt32(&n, 1)
  4253  	}))
  4254  	defer cst.close()
  4255  	var wg sync.WaitGroup
  4256  	const reqs = 20
  4257  	for i := 0; i < reqs; i++ {
  4258  		wg.Add(1)
  4259  		go func() {
  4260  			defer wg.Done()
  4261  			res, err := cst.c.Get(cst.ts.URL)
  4262  			if err != nil {
  4263  				t.Error(err)
  4264  				return
  4265  			}
  4266  			defer res.Body.Close()
  4267  			_, err = io.Copy(ioutil.Discard, res.Body)
  4268  			if err != nil {
  4269  				t.Error(err)
  4270  				return
  4271  			}
  4272  		}()
  4273  	}
  4274  	wg.Wait()
  4275  	if got := atomic.LoadInt32(&n); got != reqs {
  4276  		t.Errorf("handler ran %d times; want %d", got, reqs)
  4277  	}
  4278  }
  4279  
  4280  func TestServerConnStateNew(t *testing.T) {
  4281  	sawNew := false // if the test is buggy, we'll race on this variable.
  4282  	srv := &Server{
  4283  		ConnState: func(c net.Conn, state ConnState) {
  4284  			if state == StateNew {
  4285  				sawNew = true // testing that this write isn't racy
  4286  			}
  4287  		},
  4288  		Handler: HandlerFunc(func(w ResponseWriter, r *Request) {}), // irrelevant
  4289  	}
  4290  	srv.Serve(&oneConnListener{
  4291  		conn: &rwTestConn{
  4292  			Reader: strings.NewReader("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"),
  4293  			Writer: ioutil.Discard,
  4294  		},
  4295  	})
  4296  	if !sawNew { // testing that this read isn't racy
  4297  		t.Error("StateNew not seen")
  4298  	}
  4299  }
  4300  
  4301  type closeWriteTestConn struct {
  4302  	rwTestConn
  4303  	didCloseWrite bool
  4304  }
  4305  
  4306  func (c *closeWriteTestConn) CloseWrite() error {
  4307  	c.didCloseWrite = true
  4308  	return nil
  4309  }
  4310  
  4311  func TestCloseWrite(t *testing.T) {
  4312  	setParallel(t)
  4313  	var srv Server
  4314  	var testConn closeWriteTestConn
  4315  	c := ExportServerNewConn(&srv, &testConn)
  4316  	ExportCloseWriteAndWait(c)
  4317  	if !testConn.didCloseWrite {
  4318  		t.Error("didn't see CloseWrite call")
  4319  	}
  4320  }
  4321  
  4322  // This verifies that a handler can Flush and then Hijack.
  4323  //
  4324  // An similar test crashed once during development, but it was only
  4325  // testing this tangentially and temporarily until another TODO was
  4326  // fixed.
  4327  //
  4328  // So add an explicit test for this.
  4329  func TestServerFlushAndHijack(t *testing.T) {
  4330  	defer afterTest(t)
  4331  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4332  		io.WriteString(w, "Hello, ")
  4333  		w.(Flusher).Flush()
  4334  		conn, buf, _ := w.(Hijacker).Hijack()
  4335  		buf.WriteString("6\r\nworld!\r\n0\r\n\r\n")
  4336  		if err := buf.Flush(); err != nil {
  4337  			t.Error(err)
  4338  		}
  4339  		if err := conn.Close(); err != nil {
  4340  			t.Error(err)
  4341  		}
  4342  	}))
  4343  	defer ts.Close()
  4344  	res, err := Get(ts.URL)
  4345  	if err != nil {
  4346  		t.Fatal(err)
  4347  	}
  4348  	defer res.Body.Close()
  4349  	all, err := ioutil.ReadAll(res.Body)
  4350  	if err != nil {
  4351  		t.Fatal(err)
  4352  	}
  4353  	if want := "Hello, world!"; string(all) != want {
  4354  		t.Errorf("Got %q; want %q", all, want)
  4355  	}
  4356  }
  4357  
  4358  // golang.org/issue/8534 -- the Server shouldn't reuse a connection
  4359  // for keep-alive after it's seen any Write error (e.g. a timeout) on
  4360  // that net.Conn.
  4361  //
  4362  // To test, verify we don't timeout or see fewer unique client
  4363  // addresses (== unique connections) than requests.
  4364  func TestServerKeepAliveAfterWriteError(t *testing.T) {
  4365  	if testing.Short() {
  4366  		t.Skip("skipping in -short mode")
  4367  	}
  4368  	defer afterTest(t)
  4369  	const numReq = 3
  4370  	addrc := make(chan string, numReq)
  4371  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4372  		addrc <- r.RemoteAddr
  4373  		time.Sleep(500 * time.Millisecond)
  4374  		w.(Flusher).Flush()
  4375  	}))
  4376  	ts.Config.WriteTimeout = 250 * time.Millisecond
  4377  	ts.Start()
  4378  	defer ts.Close()
  4379  
  4380  	errc := make(chan error, numReq)
  4381  	go func() {
  4382  		defer close(errc)
  4383  		for i := 0; i < numReq; i++ {
  4384  			res, err := Get(ts.URL)
  4385  			if res != nil {
  4386  				res.Body.Close()
  4387  			}
  4388  			errc <- err
  4389  		}
  4390  	}()
  4391  
  4392  	timeout := time.NewTimer(numReq * 2 * time.Second) // 4x overkill
  4393  	defer timeout.Stop()
  4394  	addrSeen := map[string]bool{}
  4395  	numOkay := 0
  4396  	for {
  4397  		select {
  4398  		case v := <-addrc:
  4399  			addrSeen[v] = true
  4400  		case err, ok := <-errc:
  4401  			if !ok {
  4402  				if len(addrSeen) != numReq {
  4403  					t.Errorf("saw %d unique client addresses; want %d", len(addrSeen), numReq)
  4404  				}
  4405  				if numOkay != 0 {
  4406  					t.Errorf("got %d successful client requests; want 0", numOkay)
  4407  				}
  4408  				return
  4409  			}
  4410  			if err == nil {
  4411  				numOkay++
  4412  			}
  4413  		case <-timeout.C:
  4414  			t.Fatal("timeout waiting for requests to complete")
  4415  		}
  4416  	}
  4417  }
  4418  
  4419  // Issue 9987: shouldn't add automatic Content-Length (or
  4420  // Content-Type) if a Transfer-Encoding was set by the handler.
  4421  func TestNoContentLengthIfTransferEncoding(t *testing.T) {
  4422  	defer afterTest(t)
  4423  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4424  		w.Header().Set("Transfer-Encoding", "foo")
  4425  		io.WriteString(w, "<html>")
  4426  	}))
  4427  	defer ts.Close()
  4428  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4429  	if err != nil {
  4430  		t.Fatalf("Dial: %v", err)
  4431  	}
  4432  	defer c.Close()
  4433  	if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
  4434  		t.Fatal(err)
  4435  	}
  4436  	bs := bufio.NewScanner(c)
  4437  	var got bytes.Buffer
  4438  	for bs.Scan() {
  4439  		if strings.TrimSpace(bs.Text()) == "" {
  4440  			break
  4441  		}
  4442  		got.WriteString(bs.Text())
  4443  		got.WriteByte('\n')
  4444  	}
  4445  	if err := bs.Err(); err != nil {
  4446  		t.Fatal(err)
  4447  	}
  4448  	if strings.Contains(got.String(), "Content-Length") {
  4449  		t.Errorf("Unexpected Content-Length in response headers: %s", got.String())
  4450  	}
  4451  	if strings.Contains(got.String(), "Content-Type") {
  4452  		t.Errorf("Unexpected Content-Type in response headers: %s", got.String())
  4453  	}
  4454  }
  4455  
  4456  // tolerate extra CRLF(s) before Request-Line on subsequent requests on a conn
  4457  // Issue 10876.
  4458  func TestTolerateCRLFBeforeRequestLine(t *testing.T) {
  4459  	req := []byte("POST / HTTP/1.1\r\nHost: golang.org\r\nContent-Length: 3\r\n\r\nABC" +
  4460  		"\r\n\r\n" + // <-- this stuff is bogus, but we'll ignore it
  4461  		"GET / HTTP/1.1\r\nHost: golang.org\r\n\r\n")
  4462  	var buf bytes.Buffer
  4463  	conn := &rwTestConn{
  4464  		Reader: bytes.NewReader(req),
  4465  		Writer: &buf,
  4466  		closec: make(chan bool, 1),
  4467  	}
  4468  	ln := &oneConnListener{conn: conn}
  4469  	numReq := 0
  4470  	go Serve(ln, HandlerFunc(func(rw ResponseWriter, r *Request) {
  4471  		numReq++
  4472  	}))
  4473  	<-conn.closec
  4474  	if numReq != 2 {
  4475  		t.Errorf("num requests = %d; want 2", numReq)
  4476  		t.Logf("Res: %s", buf.Bytes())
  4477  	}
  4478  }
  4479  
  4480  func TestIssue13893_Expect100(t *testing.T) {
  4481  	// test that the Server doesn't filter out Expect headers.
  4482  	req := reqBytes(`PUT /readbody HTTP/1.1
  4483  User-Agent: PycURL/7.22.0
  4484  Host: 127.0.0.1:9000
  4485  Accept: */*
  4486  Expect: 100-continue
  4487  Content-Length: 10
  4488  
  4489  HelloWorld
  4490  
  4491  `)
  4492  	var buf bytes.Buffer
  4493  	conn := &rwTestConn{
  4494  		Reader: bytes.NewReader(req),
  4495  		Writer: &buf,
  4496  		closec: make(chan bool, 1),
  4497  	}
  4498  	ln := &oneConnListener{conn: conn}
  4499  	go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
  4500  		if _, ok := r.Header["Expect"]; !ok {
  4501  			t.Error("Expect header should not be filtered out")
  4502  		}
  4503  	}))
  4504  	<-conn.closec
  4505  }
  4506  
  4507  func TestIssue11549_Expect100(t *testing.T) {
  4508  	req := reqBytes(`PUT /readbody HTTP/1.1
  4509  User-Agent: PycURL/7.22.0
  4510  Host: 127.0.0.1:9000
  4511  Accept: */*
  4512  Expect: 100-continue
  4513  Content-Length: 10
  4514  
  4515  HelloWorldPUT /noreadbody HTTP/1.1
  4516  User-Agent: PycURL/7.22.0
  4517  Host: 127.0.0.1:9000
  4518  Accept: */*
  4519  Expect: 100-continue
  4520  Content-Length: 10
  4521  
  4522  GET /should-be-ignored HTTP/1.1
  4523  Host: foo
  4524  
  4525  `)
  4526  	var buf bytes.Buffer
  4527  	conn := &rwTestConn{
  4528  		Reader: bytes.NewReader(req),
  4529  		Writer: &buf,
  4530  		closec: make(chan bool, 1),
  4531  	}
  4532  	ln := &oneConnListener{conn: conn}
  4533  	numReq := 0
  4534  	go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
  4535  		numReq++
  4536  		if r.URL.Path == "/readbody" {
  4537  			ioutil.ReadAll(r.Body)
  4538  		}
  4539  		io.WriteString(w, "Hello world!")
  4540  	}))
  4541  	<-conn.closec
  4542  	if numReq != 2 {
  4543  		t.Errorf("num requests = %d; want 2", numReq)
  4544  	}
  4545  	if !strings.Contains(buf.String(), "Connection: close\r\n") {
  4546  		t.Errorf("expected 'Connection: close' in response; got: %s", buf.String())
  4547  	}
  4548  }
  4549  
  4550  // If a Handler finishes and there's an unread request body,
  4551  // verify the server try to do implicit read on it before replying.
  4552  func TestHandlerFinishSkipBigContentLengthRead(t *testing.T) {
  4553  	setParallel(t)
  4554  	conn := &testConn{closec: make(chan bool)}
  4555  	conn.readBuf.Write([]byte(fmt.Sprintf(
  4556  		"POST / HTTP/1.1\r\n" +
  4557  			"Host: test\r\n" +
  4558  			"Content-Length: 9999999999\r\n" +
  4559  			"\r\n" + strings.Repeat("a", 1<<20))))
  4560  
  4561  	ls := &oneConnListener{conn}
  4562  	var inHandlerLen int
  4563  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  4564  		inHandlerLen = conn.readBuf.Len()
  4565  		rw.WriteHeader(404)
  4566  	}))
  4567  	<-conn.closec
  4568  	afterHandlerLen := conn.readBuf.Len()
  4569  
  4570  	if afterHandlerLen != inHandlerLen {
  4571  		t.Errorf("unexpected implicit read. Read buffer went from %d -> %d", inHandlerLen, afterHandlerLen)
  4572  	}
  4573  }
  4574  
  4575  func TestHandlerSetsBodyNil_h1(t *testing.T) { testHandlerSetsBodyNil(t, h1Mode) }
  4576  func TestHandlerSetsBodyNil_h2(t *testing.T) { testHandlerSetsBodyNil(t, h2Mode) }
  4577  func testHandlerSetsBodyNil(t *testing.T, h2 bool) {
  4578  	defer afterTest(t)
  4579  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4580  		r.Body = nil
  4581  		fmt.Fprintf(w, "%v", r.RemoteAddr)
  4582  	}))
  4583  	defer cst.close()
  4584  	get := func() string {
  4585  		res, err := cst.c.Get(cst.ts.URL)
  4586  		if err != nil {
  4587  			t.Fatal(err)
  4588  		}
  4589  		defer res.Body.Close()
  4590  		slurp, err := ioutil.ReadAll(res.Body)
  4591  		if err != nil {
  4592  			t.Fatal(err)
  4593  		}
  4594  		return string(slurp)
  4595  	}
  4596  	a, b := get(), get()
  4597  	if a != b {
  4598  		t.Errorf("Failed to reuse connections between requests: %v vs %v", a, b)
  4599  	}
  4600  }
  4601  
  4602  // Test that we validate the Host header.
  4603  // Issue 11206 (invalid bytes in Host) and 13624 (Host present in HTTP/1.1)
  4604  func TestServerValidatesHostHeader(t *testing.T) {
  4605  	tests := []struct {
  4606  		proto string
  4607  		host  string
  4608  		want  int
  4609  	}{
  4610  		{"HTTP/0.9", "", 400},
  4611  
  4612  		{"HTTP/1.1", "", 400},
  4613  		{"HTTP/1.1", "Host: \r\n", 200},
  4614  		{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
  4615  		{"HTTP/1.1", "Host: foo.com\r\n", 200},
  4616  		{"HTTP/1.1", "Host: foo-bar_baz.com\r\n", 200},
  4617  		{"HTTP/1.1", "Host: foo.com:80\r\n", 200},
  4618  		{"HTTP/1.1", "Host: ::1\r\n", 200},
  4619  		{"HTTP/1.1", "Host: [::1]\r\n", 200}, // questionable without port, but accept it
  4620  		{"HTTP/1.1", "Host: [::1]:80\r\n", 200},
  4621  		{"HTTP/1.1", "Host: [::1%25en0]:80\r\n", 200},
  4622  		{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
  4623  		{"HTTP/1.1", "Host: \x06\r\n", 400},
  4624  		{"HTTP/1.1", "Host: \xff\r\n", 400},
  4625  		{"HTTP/1.1", "Host: {\r\n", 400},
  4626  		{"HTTP/1.1", "Host: }\r\n", 400},
  4627  		{"HTTP/1.1", "Host: first\r\nHost: second\r\n", 400},
  4628  
  4629  		// HTTP/1.0 can lack a host header, but if present
  4630  		// must play by the rules too:
  4631  		{"HTTP/1.0", "", 200},
  4632  		{"HTTP/1.0", "Host: first\r\nHost: second\r\n", 400},
  4633  		{"HTTP/1.0", "Host: \xff\r\n", 400},
  4634  
  4635  		// Make an exception for HTTP upgrade requests:
  4636  		{"PRI * HTTP/2.0", "", 200},
  4637  
  4638  		// Also an exception for CONNECT requests: (Issue 18215)
  4639  		{"CONNECT golang.org:443 HTTP/1.1", "", 200},
  4640  
  4641  		// But not other HTTP/2 stuff:
  4642  		{"PRI / HTTP/2.0", "", 400},
  4643  		{"GET / HTTP/2.0", "", 400},
  4644  		{"GET / HTTP/3.0", "", 400},
  4645  	}
  4646  	for _, tt := range tests {
  4647  		conn := &testConn{closec: make(chan bool, 1)}
  4648  		methodTarget := "GET / "
  4649  		if !strings.HasPrefix(tt.proto, "HTTP/") {
  4650  			methodTarget = ""
  4651  		}
  4652  		io.WriteString(&conn.readBuf, methodTarget+tt.proto+"\r\n"+tt.host+"\r\n")
  4653  
  4654  		ln := &oneConnListener{conn}
  4655  		srv := Server{
  4656  			ErrorLog: quietLog,
  4657  			Handler:  HandlerFunc(func(ResponseWriter, *Request) {}),
  4658  		}
  4659  		go srv.Serve(ln)
  4660  		<-conn.closec
  4661  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  4662  		if err != nil {
  4663  			t.Errorf("For %s %q, ReadResponse: %v", tt.proto, tt.host, res)
  4664  			continue
  4665  		}
  4666  		if res.StatusCode != tt.want {
  4667  			t.Errorf("For %s %q, Status = %d; want %d", tt.proto, tt.host, res.StatusCode, tt.want)
  4668  		}
  4669  	}
  4670  }
  4671  
  4672  func TestServerHandlersCanHandleH2PRI(t *testing.T) {
  4673  	const upgradeResponse = "upgrade here"
  4674  	defer afterTest(t)
  4675  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4676  		conn, br, err := w.(Hijacker).Hijack()
  4677  		defer conn.Close()
  4678  		if r.Method != "PRI" || r.RequestURI != "*" {
  4679  			t.Errorf("Got method/target %q %q; want PRI *", r.Method, r.RequestURI)
  4680  			return
  4681  		}
  4682  		if !r.Close {
  4683  			t.Errorf("Request.Close = true; want false")
  4684  		}
  4685  		const want = "SM\r\n\r\n"
  4686  		buf := make([]byte, len(want))
  4687  		n, err := io.ReadFull(br, buf)
  4688  		if err != nil || string(buf[:n]) != want {
  4689  			t.Errorf("Read = %v, %v (%q), want %q", n, err, buf[:n], want)
  4690  			return
  4691  		}
  4692  		io.WriteString(conn, upgradeResponse)
  4693  	}))
  4694  	defer ts.Close()
  4695  
  4696  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4697  	if err != nil {
  4698  		t.Fatalf("Dial: %v", err)
  4699  	}
  4700  	defer c.Close()
  4701  	io.WriteString(c, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
  4702  	slurp, err := ioutil.ReadAll(c)
  4703  	if err != nil {
  4704  		t.Fatal(err)
  4705  	}
  4706  	if string(slurp) != upgradeResponse {
  4707  		t.Errorf("Handler response = %q; want %q", slurp, upgradeResponse)
  4708  	}
  4709  }
  4710  
  4711  // Test that we validate the valid bytes in HTTP/1 headers.
  4712  // Issue 11207.
  4713  func TestServerValidatesHeaders(t *testing.T) {
  4714  	setParallel(t)
  4715  	tests := []struct {
  4716  		header string
  4717  		want   int
  4718  	}{
  4719  		{"", 200},
  4720  		{"Foo: bar\r\n", 200},
  4721  		{"X-Foo: bar\r\n", 200},
  4722  		{"Foo: a space\r\n", 200},
  4723  
  4724  		{"A space: foo\r\n", 400},                            // space in header
  4725  		{"foo\xffbar: foo\r\n", 400},                         // binary in header
  4726  		{"foo\x00bar: foo\r\n", 400},                         // binary in header
  4727  		{"Foo: " + strings.Repeat("x", 1<<21) + "\r\n", 431}, // header too large
  4728  
  4729  		{"foo: foo foo\r\n", 200},    // LWS space is okay
  4730  		{"foo: foo\tfoo\r\n", 200},   // LWS tab is okay
  4731  		{"foo: foo\x00foo\r\n", 400}, // CTL 0x00 in value is bad
  4732  		{"foo: foo\x7ffoo\r\n", 400}, // CTL 0x7f in value is bad
  4733  		{"foo: foo\xfffoo\r\n", 200}, // non-ASCII high octets in value are fine
  4734  	}
  4735  	for _, tt := range tests {
  4736  		conn := &testConn{closec: make(chan bool, 1)}
  4737  		io.WriteString(&conn.readBuf, "GET / HTTP/1.1\r\nHost: foo\r\n"+tt.header+"\r\n")
  4738  
  4739  		ln := &oneConnListener{conn}
  4740  		srv := Server{
  4741  			ErrorLog: quietLog,
  4742  			Handler:  HandlerFunc(func(ResponseWriter, *Request) {}),
  4743  		}
  4744  		go srv.Serve(ln)
  4745  		<-conn.closec
  4746  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  4747  		if err != nil {
  4748  			t.Errorf("For %q, ReadResponse: %v", tt.header, res)
  4749  			continue
  4750  		}
  4751  		if res.StatusCode != tt.want {
  4752  			t.Errorf("For %q, Status = %d; want %d", tt.header, res.StatusCode, tt.want)
  4753  		}
  4754  	}
  4755  }
  4756  
  4757  func TestServerRequestContextCancel_ServeHTTPDone_h1(t *testing.T) {
  4758  	testServerRequestContextCancel_ServeHTTPDone(t, h1Mode)
  4759  }
  4760  func TestServerRequestContextCancel_ServeHTTPDone_h2(t *testing.T) {
  4761  	testServerRequestContextCancel_ServeHTTPDone(t, h2Mode)
  4762  }
  4763  func testServerRequestContextCancel_ServeHTTPDone(t *testing.T, h2 bool) {
  4764  	setParallel(t)
  4765  	defer afterTest(t)
  4766  	ctxc := make(chan context.Context, 1)
  4767  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4768  		ctx := r.Context()
  4769  		select {
  4770  		case <-ctx.Done():
  4771  			t.Error("should not be Done in ServeHTTP")
  4772  		default:
  4773  		}
  4774  		ctxc <- ctx
  4775  	}))
  4776  	defer cst.close()
  4777  	res, err := cst.c.Get(cst.ts.URL)
  4778  	if err != nil {
  4779  		t.Fatal(err)
  4780  	}
  4781  	res.Body.Close()
  4782  	ctx := <-ctxc
  4783  	select {
  4784  	case <-ctx.Done():
  4785  	default:
  4786  		t.Error("context should be done after ServeHTTP completes")
  4787  	}
  4788  }
  4789  
  4790  // Tests that the Request.Context available to the Handler is canceled
  4791  // if the peer closes their TCP connection. This requires that the server
  4792  // is always blocked in a Read call so it notices the EOF from the client.
  4793  // See issues 15927 and 15224.
  4794  func TestServerRequestContextCancel_ConnClose(t *testing.T) {
  4795  	setParallel(t)
  4796  	defer afterTest(t)
  4797  	inHandler := make(chan struct{})
  4798  	handlerDone := make(chan struct{})
  4799  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4800  		close(inHandler)
  4801  		select {
  4802  		case <-r.Context().Done():
  4803  		case <-time.After(3 * time.Second):
  4804  			t.Errorf("timeout waiting for context to be done")
  4805  		}
  4806  		close(handlerDone)
  4807  	}))
  4808  	defer ts.Close()
  4809  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4810  	if err != nil {
  4811  		t.Fatal(err)
  4812  	}
  4813  	defer c.Close()
  4814  	io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n")
  4815  	select {
  4816  	case <-inHandler:
  4817  	case <-time.After(3 * time.Second):
  4818  		t.Fatalf("timeout waiting to see ServeHTTP get called")
  4819  	}
  4820  	c.Close() // this should trigger the context being done
  4821  
  4822  	select {
  4823  	case <-handlerDone:
  4824  	case <-time.After(4 * time.Second):
  4825  		t.Fatalf("timeout waiting to see ServeHTTP exit")
  4826  	}
  4827  }
  4828  
  4829  func TestServerContext_ServerContextKey_h1(t *testing.T) {
  4830  	testServerContext_ServerContextKey(t, h1Mode)
  4831  }
  4832  func TestServerContext_ServerContextKey_h2(t *testing.T) {
  4833  	testServerContext_ServerContextKey(t, h2Mode)
  4834  }
  4835  func testServerContext_ServerContextKey(t *testing.T, h2 bool) {
  4836  	setParallel(t)
  4837  	defer afterTest(t)
  4838  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4839  		ctx := r.Context()
  4840  		got := ctx.Value(ServerContextKey)
  4841  		if _, ok := got.(*Server); !ok {
  4842  			t.Errorf("context value = %T; want *http.Server", got)
  4843  		}
  4844  	}))
  4845  	defer cst.close()
  4846  	res, err := cst.c.Get(cst.ts.URL)
  4847  	if err != nil {
  4848  		t.Fatal(err)
  4849  	}
  4850  	res.Body.Close()
  4851  }
  4852  
  4853  func TestServerContext_LocalAddrContextKey_h1(t *testing.T) {
  4854  	testServerContext_LocalAddrContextKey(t, h1Mode)
  4855  }
  4856  func TestServerContext_LocalAddrContextKey_h2(t *testing.T) {
  4857  	testServerContext_LocalAddrContextKey(t, h2Mode)
  4858  }
  4859  func testServerContext_LocalAddrContextKey(t *testing.T, h2 bool) {
  4860  	setParallel(t)
  4861  	defer afterTest(t)
  4862  	ch := make(chan interface{}, 1)
  4863  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4864  		ch <- r.Context().Value(LocalAddrContextKey)
  4865  	}))
  4866  	defer cst.close()
  4867  	if _, err := cst.c.Head(cst.ts.URL); err != nil {
  4868  		t.Fatal(err)
  4869  	}
  4870  
  4871  	host := cst.ts.Listener.Addr().String()
  4872  	select {
  4873  	case got := <-ch:
  4874  		if addr, ok := got.(net.Addr); !ok {
  4875  			t.Errorf("local addr value = %T; want net.Addr", got)
  4876  		} else if fmt.Sprint(addr) != host {
  4877  			t.Errorf("local addr = %v; want %v", addr, host)
  4878  		}
  4879  	case <-time.After(5 * time.Second):
  4880  		t.Error("timed out")
  4881  	}
  4882  }
  4883  
  4884  // https://golang.org/issue/15960
  4885  func TestHandlerSetTransferEncodingChunked(t *testing.T) {
  4886  	setParallel(t)
  4887  	defer afterTest(t)
  4888  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4889  		w.Header().Set("Transfer-Encoding", "chunked")
  4890  		w.Write([]byte("hello"))
  4891  	}))
  4892  	resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  4893  	const hdr = "Transfer-Encoding: chunked"
  4894  	if n := strings.Count(resp, hdr); n != 1 {
  4895  		t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
  4896  	}
  4897  }
  4898  
  4899  // https://golang.org/issue/16063
  4900  func TestHandlerSetTransferEncodingGzip(t *testing.T) {
  4901  	setParallel(t)
  4902  	defer afterTest(t)
  4903  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4904  		w.Header().Set("Transfer-Encoding", "gzip")
  4905  		gz := gzip.NewWriter(w)
  4906  		gz.Write([]byte("hello"))
  4907  		gz.Close()
  4908  	}))
  4909  	resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  4910  	for _, v := range []string{"gzip", "chunked"} {
  4911  		hdr := "Transfer-Encoding: " + v
  4912  		if n := strings.Count(resp, hdr); n != 1 {
  4913  			t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
  4914  		}
  4915  	}
  4916  }
  4917  
  4918  func BenchmarkClientServer(b *testing.B) {
  4919  	b.ReportAllocs()
  4920  	b.StopTimer()
  4921  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  4922  		fmt.Fprintf(rw, "Hello world.\n")
  4923  	}))
  4924  	defer ts.Close()
  4925  	b.StartTimer()
  4926  
  4927  	for i := 0; i < b.N; i++ {
  4928  		res, err := Get(ts.URL)
  4929  		if err != nil {
  4930  			b.Fatal("Get:", err)
  4931  		}
  4932  		all, err := ioutil.ReadAll(res.Body)
  4933  		res.Body.Close()
  4934  		if err != nil {
  4935  			b.Fatal("ReadAll:", err)
  4936  		}
  4937  		body := string(all)
  4938  		if body != "Hello world.\n" {
  4939  			b.Fatal("Got body:", body)
  4940  		}
  4941  	}
  4942  
  4943  	b.StopTimer()
  4944  }
  4945  
  4946  func BenchmarkClientServerParallel4(b *testing.B) {
  4947  	benchmarkClientServerParallel(b, 4, false)
  4948  }
  4949  
  4950  func BenchmarkClientServerParallel64(b *testing.B) {
  4951  	benchmarkClientServerParallel(b, 64, false)
  4952  }
  4953  
  4954  func BenchmarkClientServerParallelTLS4(b *testing.B) {
  4955  	benchmarkClientServerParallel(b, 4, true)
  4956  }
  4957  
  4958  func BenchmarkClientServerParallelTLS64(b *testing.B) {
  4959  	benchmarkClientServerParallel(b, 64, true)
  4960  }
  4961  
  4962  func benchmarkClientServerParallel(b *testing.B, parallelism int, useTLS bool) {
  4963  	b.ReportAllocs()
  4964  	ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  4965  		fmt.Fprintf(rw, "Hello world.\n")
  4966  	}))
  4967  	if useTLS {
  4968  		ts.StartTLS()
  4969  	} else {
  4970  		ts.Start()
  4971  	}
  4972  	defer ts.Close()
  4973  	b.ResetTimer()
  4974  	b.SetParallelism(parallelism)
  4975  	b.RunParallel(func(pb *testing.PB) {
  4976  		c := ts.Client()
  4977  		for pb.Next() {
  4978  			res, err := c.Get(ts.URL)
  4979  			if err != nil {
  4980  				b.Logf("Get: %v", err)
  4981  				continue
  4982  			}
  4983  			all, err := ioutil.ReadAll(res.Body)
  4984  			res.Body.Close()
  4985  			if err != nil {
  4986  				b.Logf("ReadAll: %v", err)
  4987  				continue
  4988  			}
  4989  			body := string(all)
  4990  			if body != "Hello world.\n" {
  4991  				panic("Got body: " + body)
  4992  			}
  4993  		}
  4994  	})
  4995  }
  4996  
  4997  // A benchmark for profiling the server without the HTTP client code.
  4998  // The client code runs in a subprocess.
  4999  //
  5000  // For use like:
  5001  //   $ go test -c
  5002  //   $ ./http.test -test.run=XX -test.bench=BenchmarkServer -test.benchtime=15s -test.cpuprofile=http.prof
  5003  //   $ go tool pprof http.test http.prof
  5004  //   (pprof) web
  5005  func BenchmarkServer(b *testing.B) {
  5006  	b.ReportAllocs()
  5007  	// Child process mode;
  5008  	if url := os.Getenv("TEST_BENCH_SERVER_URL"); url != "" {
  5009  		n, err := strconv.Atoi(os.Getenv("TEST_BENCH_CLIENT_N"))
  5010  		if err != nil {
  5011  			panic(err)
  5012  		}
  5013  		for i := 0; i < n; i++ {
  5014  			res, err := Get(url)
  5015  			if err != nil {
  5016  				log.Panicf("Get: %v", err)
  5017  			}
  5018  			all, err := ioutil.ReadAll(res.Body)
  5019  			res.Body.Close()
  5020  			if err != nil {
  5021  				log.Panicf("ReadAll: %v", err)
  5022  			}
  5023  			body := string(all)
  5024  			if body != "Hello world.\n" {
  5025  				log.Panicf("Got body: %q", body)
  5026  			}
  5027  		}
  5028  		os.Exit(0)
  5029  		return
  5030  	}
  5031  
  5032  	var res = []byte("Hello world.\n")
  5033  	b.StopTimer()
  5034  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  5035  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5036  		rw.Write(res)
  5037  	}))
  5038  	defer ts.Close()
  5039  	b.StartTimer()
  5040  
  5041  	cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkServer$")
  5042  	cmd.Env = append([]string{
  5043  		fmt.Sprintf("TEST_BENCH_CLIENT_N=%d", b.N),
  5044  		fmt.Sprintf("TEST_BENCH_SERVER_URL=%s", ts.URL),
  5045  	}, os.Environ()...)
  5046  	out, err := cmd.CombinedOutput()
  5047  	if err != nil {
  5048  		b.Errorf("Test failure: %v, with output: %s", err, out)
  5049  	}
  5050  }
  5051  
  5052  // getNoBody wraps Get but closes any Response.Body before returning the response.
  5053  func getNoBody(urlStr string) (*Response, error) {
  5054  	res, err := Get(urlStr)
  5055  	if err != nil {
  5056  		return nil, err
  5057  	}
  5058  	res.Body.Close()
  5059  	return res, nil
  5060  }
  5061  
  5062  // A benchmark for profiling the client without the HTTP server code.
  5063  // The server code runs in a subprocess.
  5064  func BenchmarkClient(b *testing.B) {
  5065  	b.ReportAllocs()
  5066  	b.StopTimer()
  5067  	defer afterTest(b)
  5068  
  5069  	var data = []byte("Hello world.\n")
  5070  	if server := os.Getenv("TEST_BENCH_SERVER"); server != "" {
  5071  		// Server process mode.
  5072  		port := os.Getenv("TEST_BENCH_SERVER_PORT") // can be set by user
  5073  		if port == "" {
  5074  			port = "0"
  5075  		}
  5076  		ln, err := net.Listen("tcp", "localhost:"+port)
  5077  		if err != nil {
  5078  			fmt.Fprintln(os.Stderr, err.Error())
  5079  			os.Exit(1)
  5080  		}
  5081  		fmt.Println(ln.Addr().String())
  5082  		HandleFunc("/", func(w ResponseWriter, r *Request) {
  5083  			r.ParseForm()
  5084  			if r.Form.Get("stop") != "" {
  5085  				os.Exit(0)
  5086  			}
  5087  			w.Header().Set("Content-Type", "text/html; charset=utf-8")
  5088  			w.Write(data)
  5089  		})
  5090  		var srv Server
  5091  		log.Fatal(srv.Serve(ln))
  5092  	}
  5093  
  5094  	// Start server process.
  5095  	cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkClient$")
  5096  	cmd.Env = append(os.Environ(), "TEST_BENCH_SERVER=yes")
  5097  	cmd.Stderr = os.Stderr
  5098  	stdout, err := cmd.StdoutPipe()
  5099  	if err != nil {
  5100  		b.Fatal(err)
  5101  	}
  5102  	if err := cmd.Start(); err != nil {
  5103  		b.Fatalf("subprocess failed to start: %v", err)
  5104  	}
  5105  	defer cmd.Process.Kill()
  5106  
  5107  	// Wait for the server in the child process to respond and tell us
  5108  	// its listening address, once it's started listening:
  5109  	timer := time.AfterFunc(10*time.Second, func() {
  5110  		cmd.Process.Kill()
  5111  	})
  5112  	defer timer.Stop()
  5113  	bs := bufio.NewScanner(stdout)
  5114  	if !bs.Scan() {
  5115  		b.Fatalf("failed to read listening URL from child: %v", bs.Err())
  5116  	}
  5117  	url := "http://" + strings.TrimSpace(bs.Text()) + "/"
  5118  	timer.Stop()
  5119  	if _, err := getNoBody(url); err != nil {
  5120  		b.Fatalf("initial probe of child process failed: %v", err)
  5121  	}
  5122  
  5123  	done := make(chan error)
  5124  	go func() {
  5125  		done <- cmd.Wait()
  5126  	}()
  5127  
  5128  	// Do b.N requests to the server.
  5129  	b.StartTimer()
  5130  	for i := 0; i < b.N; i++ {
  5131  		res, err := Get(url)
  5132  		if err != nil {
  5133  			b.Fatalf("Get: %v", err)
  5134  		}
  5135  		body, err := ioutil.ReadAll(res.Body)
  5136  		res.Body.Close()
  5137  		if err != nil {
  5138  			b.Fatalf("ReadAll: %v", err)
  5139  		}
  5140  		if !bytes.Equal(body, data) {
  5141  			b.Fatalf("Got body: %q", body)
  5142  		}
  5143  	}
  5144  	b.StopTimer()
  5145  
  5146  	// Instruct server process to stop.
  5147  	getNoBody(url + "?stop=yes")
  5148  	select {
  5149  	case err := <-done:
  5150  		if err != nil {
  5151  			b.Fatalf("subprocess failed: %v", err)
  5152  		}
  5153  	case <-time.After(5 * time.Second):
  5154  		b.Fatalf("subprocess did not stop")
  5155  	}
  5156  }
  5157  
  5158  func BenchmarkServerFakeConnNoKeepAlive(b *testing.B) {
  5159  	b.ReportAllocs()
  5160  	req := reqBytes(`GET / HTTP/1.0
  5161  Host: golang.org
  5162  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5163  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
  5164  Accept-Encoding: gzip,deflate,sdch
  5165  Accept-Language: en-US,en;q=0.8
  5166  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  5167  `)
  5168  	res := []byte("Hello world!\n")
  5169  
  5170  	conn := &testConn{
  5171  		// testConn.Close will not push into the channel
  5172  		// if it's full.
  5173  		closec: make(chan bool, 1),
  5174  	}
  5175  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5176  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5177  		rw.Write(res)
  5178  	})
  5179  	ln := new(oneConnListener)
  5180  	for i := 0; i < b.N; i++ {
  5181  		conn.readBuf.Reset()
  5182  		conn.writeBuf.Reset()
  5183  		conn.readBuf.Write(req)
  5184  		ln.conn = conn
  5185  		Serve(ln, handler)
  5186  		<-conn.closec
  5187  	}
  5188  }
  5189  
  5190  // repeatReader reads content count times, then EOFs.
  5191  type repeatReader struct {
  5192  	content []byte
  5193  	count   int
  5194  	off     int
  5195  }
  5196  
  5197  func (r *repeatReader) Read(p []byte) (n int, err error) {
  5198  	if r.count <= 0 {
  5199  		return 0, io.EOF
  5200  	}
  5201  	n = copy(p, r.content[r.off:])
  5202  	r.off += n
  5203  	if r.off == len(r.content) {
  5204  		r.count--
  5205  		r.off = 0
  5206  	}
  5207  	return
  5208  }
  5209  
  5210  func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) {
  5211  	b.ReportAllocs()
  5212  
  5213  	req := reqBytes(`GET / HTTP/1.1
  5214  Host: golang.org
  5215  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5216  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
  5217  Accept-Encoding: gzip,deflate,sdch
  5218  Accept-Language: en-US,en;q=0.8
  5219  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  5220  `)
  5221  	res := []byte("Hello world!\n")
  5222  
  5223  	conn := &rwTestConn{
  5224  		Reader: &repeatReader{content: req, count: b.N},
  5225  		Writer: ioutil.Discard,
  5226  		closec: make(chan bool, 1),
  5227  	}
  5228  	handled := 0
  5229  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5230  		handled++
  5231  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5232  		rw.Write(res)
  5233  	})
  5234  	ln := &oneConnListener{conn: conn}
  5235  	go Serve(ln, handler)
  5236  	<-conn.closec
  5237  	if b.N != handled {
  5238  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5239  	}
  5240  }
  5241  
  5242  // same as above, but representing the most simple possible request
  5243  // and handler. Notably: the handler does not call rw.Header().
  5244  func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) {
  5245  	b.ReportAllocs()
  5246  
  5247  	req := reqBytes(`GET / HTTP/1.1
  5248  Host: golang.org
  5249  `)
  5250  	res := []byte("Hello world!\n")
  5251  
  5252  	conn := &rwTestConn{
  5253  		Reader: &repeatReader{content: req, count: b.N},
  5254  		Writer: ioutil.Discard,
  5255  		closec: make(chan bool, 1),
  5256  	}
  5257  	handled := 0
  5258  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5259  		handled++
  5260  		rw.Write(res)
  5261  	})
  5262  	ln := &oneConnListener{conn: conn}
  5263  	go Serve(ln, handler)
  5264  	<-conn.closec
  5265  	if b.N != handled {
  5266  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5267  	}
  5268  }
  5269  
  5270  const someResponse = "<html>some response</html>"
  5271  
  5272  // A Response that's just no bigger than 2KB, the buffer-before-chunking threshold.
  5273  var response = bytes.Repeat([]byte(someResponse), 2<<10/len(someResponse))
  5274  
  5275  // Both Content-Type and Content-Length set. Should be no buffering.
  5276  func BenchmarkServerHandlerTypeLen(b *testing.B) {
  5277  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5278  		w.Header().Set("Content-Type", "text/html")
  5279  		w.Header().Set("Content-Length", strconv.Itoa(len(response)))
  5280  		w.Write(response)
  5281  	}))
  5282  }
  5283  
  5284  // A Content-Type is set, but no length. No sniffing, but will count the Content-Length.
  5285  func BenchmarkServerHandlerNoLen(b *testing.B) {
  5286  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5287  		w.Header().Set("Content-Type", "text/html")
  5288  		w.Write(response)
  5289  	}))
  5290  }
  5291  
  5292  // A Content-Length is set, but the Content-Type will be sniffed.
  5293  func BenchmarkServerHandlerNoType(b *testing.B) {
  5294  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5295  		w.Header().Set("Content-Length", strconv.Itoa(len(response)))
  5296  		w.Write(response)
  5297  	}))
  5298  }
  5299  
  5300  // Neither a Content-Type or Content-Length, so sniffed and counted.
  5301  func BenchmarkServerHandlerNoHeader(b *testing.B) {
  5302  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5303  		w.Write(response)
  5304  	}))
  5305  }
  5306  
  5307  func benchmarkHandler(b *testing.B, h Handler) {
  5308  	b.ReportAllocs()
  5309  	req := reqBytes(`GET / HTTP/1.1
  5310  Host: golang.org
  5311  `)
  5312  	conn := &rwTestConn{
  5313  		Reader: &repeatReader{content: req, count: b.N},
  5314  		Writer: ioutil.Discard,
  5315  		closec: make(chan bool, 1),
  5316  	}
  5317  	handled := 0
  5318  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5319  		handled++
  5320  		h.ServeHTTP(rw, r)
  5321  	})
  5322  	ln := &oneConnListener{conn: conn}
  5323  	go Serve(ln, handler)
  5324  	<-conn.closec
  5325  	if b.N != handled {
  5326  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5327  	}
  5328  }
  5329  
  5330  func BenchmarkServerHijack(b *testing.B) {
  5331  	b.ReportAllocs()
  5332  	req := reqBytes(`GET / HTTP/1.1
  5333  Host: golang.org
  5334  `)
  5335  	h := HandlerFunc(func(w ResponseWriter, r *Request) {
  5336  		conn, _, err := w.(Hijacker).Hijack()
  5337  		if err != nil {
  5338  			panic(err)
  5339  		}
  5340  		conn.Close()
  5341  	})
  5342  	conn := &rwTestConn{
  5343  		Writer: ioutil.Discard,
  5344  		closec: make(chan bool, 1),
  5345  	}
  5346  	ln := &oneConnListener{conn: conn}
  5347  	for i := 0; i < b.N; i++ {
  5348  		conn.Reader = bytes.NewReader(req)
  5349  		ln.conn = conn
  5350  		Serve(ln, h)
  5351  		<-conn.closec
  5352  	}
  5353  }
  5354  
  5355  func BenchmarkCloseNotifier(b *testing.B) {
  5356  	b.ReportAllocs()
  5357  	b.StopTimer()
  5358  	sawClose := make(chan bool)
  5359  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  5360  		<-rw.(CloseNotifier).CloseNotify()
  5361  		sawClose <- true
  5362  	}))
  5363  	defer ts.Close()
  5364  	tot := time.NewTimer(5 * time.Second)
  5365  	defer tot.Stop()
  5366  	b.StartTimer()
  5367  	for i := 0; i < b.N; i++ {
  5368  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5369  		if err != nil {
  5370  			b.Fatalf("error dialing: %v", err)
  5371  		}
  5372  		_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
  5373  		if err != nil {
  5374  			b.Fatal(err)
  5375  		}
  5376  		conn.Close()
  5377  		tot.Reset(5 * time.Second)
  5378  		select {
  5379  		case <-sawClose:
  5380  		case <-tot.C:
  5381  			b.Fatal("timeout")
  5382  		}
  5383  	}
  5384  	b.StopTimer()
  5385  }
  5386  
  5387  // Verify this doesn't race (Issue 16505)
  5388  func TestConcurrentServerServe(t *testing.T) {
  5389  	setParallel(t)
  5390  	for i := 0; i < 100; i++ {
  5391  		ln1 := &oneConnListener{conn: nil}
  5392  		ln2 := &oneConnListener{conn: nil}
  5393  		srv := Server{}
  5394  		go func() { srv.Serve(ln1) }()
  5395  		go func() { srv.Serve(ln2) }()
  5396  	}
  5397  }
  5398  
  5399  func TestServerIdleTimeout(t *testing.T) {
  5400  	if testing.Short() {
  5401  		t.Skip("skipping in short mode")
  5402  	}
  5403  	setParallel(t)
  5404  	defer afterTest(t)
  5405  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5406  		io.Copy(ioutil.Discard, r.Body)
  5407  		io.WriteString(w, r.RemoteAddr)
  5408  	}))
  5409  	ts.Config.ReadHeaderTimeout = 1 * time.Second
  5410  	ts.Config.IdleTimeout = 2 * time.Second
  5411  	ts.Start()
  5412  	defer ts.Close()
  5413  	c := ts.Client()
  5414  
  5415  	get := func() string {
  5416  		res, err := c.Get(ts.URL)
  5417  		if err != nil {
  5418  			t.Fatal(err)
  5419  		}
  5420  		defer res.Body.Close()
  5421  		slurp, err := ioutil.ReadAll(res.Body)
  5422  		if err != nil {
  5423  			t.Fatal(err)
  5424  		}
  5425  		return string(slurp)
  5426  	}
  5427  
  5428  	a1, a2 := get(), get()
  5429  	if a1 != a2 {
  5430  		t.Fatalf("did requests on different connections")
  5431  	}
  5432  	time.Sleep(3 * time.Second)
  5433  	a3 := get()
  5434  	if a2 == a3 {
  5435  		t.Fatal("request three unexpectedly on same connection")
  5436  	}
  5437  
  5438  	// And test that ReadHeaderTimeout still works:
  5439  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5440  	if err != nil {
  5441  		t.Fatal(err)
  5442  	}
  5443  	defer conn.Close()
  5444  	conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo.com\r\n"))
  5445  	time.Sleep(2 * time.Second)
  5446  	if _, err := io.CopyN(ioutil.Discard, conn, 1); err == nil {
  5447  		t.Fatal("copy byte succeeded; want err")
  5448  	}
  5449  }
  5450  
  5451  func get(t *testing.T, c *Client, url string) string {
  5452  	res, err := c.Get(url)
  5453  	if err != nil {
  5454  		t.Fatal(err)
  5455  	}
  5456  	defer res.Body.Close()
  5457  	slurp, err := ioutil.ReadAll(res.Body)
  5458  	if err != nil {
  5459  		t.Fatal(err)
  5460  	}
  5461  	return string(slurp)
  5462  }
  5463  
  5464  // Tests that calls to Server.SetKeepAlivesEnabled(false) closes any
  5465  // currently-open connections.
  5466  func TestServerSetKeepAlivesEnabledClosesConns(t *testing.T) {
  5467  	setParallel(t)
  5468  	defer afterTest(t)
  5469  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5470  		io.WriteString(w, r.RemoteAddr)
  5471  	}))
  5472  	defer ts.Close()
  5473  
  5474  	c := ts.Client()
  5475  	tr := c.Transport.(*Transport)
  5476  
  5477  	get := func() string { return get(t, c, ts.URL) }
  5478  
  5479  	a1, a2 := get(), get()
  5480  	if a1 != a2 {
  5481  		t.Fatal("expected first two requests on same connection")
  5482  	}
  5483  	var idle0 int
  5484  	if !waitCondition(2*time.Second, 10*time.Millisecond, func() bool {
  5485  		idle0 = tr.IdleConnKeyCountForTesting()
  5486  		return idle0 == 1
  5487  	}) {
  5488  		t.Fatalf("idle count before SetKeepAlivesEnabled called = %v; want 1", idle0)
  5489  	}
  5490  
  5491  	ts.Config.SetKeepAlivesEnabled(false)
  5492  
  5493  	var idle1 int
  5494  	if !waitCondition(2*time.Second, 10*time.Millisecond, func() bool {
  5495  		idle1 = tr.IdleConnKeyCountForTesting()
  5496  		return idle1 == 0
  5497  	}) {
  5498  		t.Fatalf("idle count after SetKeepAlivesEnabled called = %v; want 0", idle1)
  5499  	}
  5500  
  5501  	a3 := get()
  5502  	if a3 == a2 {
  5503  		t.Fatal("expected third request on new connection")
  5504  	}
  5505  }
  5506  
  5507  func TestServerShutdown_h1(t *testing.T) { testServerShutdown(t, h1Mode) }
  5508  func TestServerShutdown_h2(t *testing.T) { testServerShutdown(t, h2Mode) }
  5509  
  5510  func testServerShutdown(t *testing.T, h2 bool) {
  5511  	setParallel(t)
  5512  	defer afterTest(t)
  5513  	var doShutdown func() // set later
  5514  	var shutdownRes = make(chan error, 1)
  5515  	var gotOnShutdown = make(chan struct{}, 1)
  5516  	handler := HandlerFunc(func(w ResponseWriter, r *Request) {
  5517  		go doShutdown()
  5518  		// Shutdown is graceful, so it should not interrupt
  5519  		// this in-flight response. Add a tiny sleep here to
  5520  		// increase the odds of a failure if shutdown has
  5521  		// bugs.
  5522  		time.Sleep(20 * time.Millisecond)
  5523  		io.WriteString(w, r.RemoteAddr)
  5524  	})
  5525  	cst := newClientServerTest(t, h2, handler, func(srv *httptest.Server) {
  5526  		srv.Config.RegisterOnShutdown(func() { gotOnShutdown <- struct{}{} })
  5527  	})
  5528  	defer cst.close()
  5529  
  5530  	doShutdown = func() {
  5531  		shutdownRes <- cst.ts.Config.Shutdown(context.Background())
  5532  	}
  5533  	get(t, cst.c, cst.ts.URL) // calls t.Fail on failure
  5534  
  5535  	if err := <-shutdownRes; err != nil {
  5536  		t.Fatalf("Shutdown: %v", err)
  5537  	}
  5538  	select {
  5539  	case <-gotOnShutdown:
  5540  	case <-time.After(5 * time.Second):
  5541  		t.Errorf("onShutdown callback not called, RegisterOnShutdown broken?")
  5542  	}
  5543  
  5544  	res, err := cst.c.Get(cst.ts.URL)
  5545  	if err == nil {
  5546  		res.Body.Close()
  5547  		t.Fatal("second request should fail. server should be shut down")
  5548  	}
  5549  }
  5550  
  5551  func TestServerShutdownStateNew(t *testing.T) {
  5552  	if testing.Short() {
  5553  		t.Skip("test takes 5-6 seconds; skipping in short mode")
  5554  	}
  5555  	setParallel(t)
  5556  	defer afterTest(t)
  5557  
  5558  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5559  		// nothing.
  5560  	}))
  5561  	var connAccepted sync.WaitGroup
  5562  	ts.Config.ConnState = func(conn net.Conn, state ConnState) {
  5563  		if state == StateNew {
  5564  			connAccepted.Done()
  5565  		}
  5566  	}
  5567  	ts.Start()
  5568  	defer ts.Close()
  5569  
  5570  	// Start a connection but never write to it.
  5571  	connAccepted.Add(1)
  5572  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  5573  	if err != nil {
  5574  		t.Fatal(err)
  5575  	}
  5576  	defer c.Close()
  5577  
  5578  	// Wait for the connection to be accepted by the server. Otherwise, if
  5579  	// Shutdown happens to run first, the server will be closed when
  5580  	// encountering the connection, in which case it will be rejected
  5581  	// immediately.
  5582  	connAccepted.Wait()
  5583  
  5584  	shutdownRes := make(chan error, 1)
  5585  	go func() {
  5586  		shutdownRes <- ts.Config.Shutdown(context.Background())
  5587  	}()
  5588  	readRes := make(chan error, 1)
  5589  	go func() {
  5590  		_, err := c.Read([]byte{0})
  5591  		readRes <- err
  5592  	}()
  5593  
  5594  	const expectTimeout = 5 * time.Second
  5595  	t0 := time.Now()
  5596  	select {
  5597  	case got := <-shutdownRes:
  5598  		d := time.Since(t0)
  5599  		if got != nil {
  5600  			t.Fatalf("shutdown error after %v: %v", d, err)
  5601  		}
  5602  		if d < expectTimeout/2 {
  5603  			t.Errorf("shutdown too soon after %v", d)
  5604  		}
  5605  	case <-time.After(expectTimeout * 3 / 2):
  5606  		t.Fatalf("timeout waiting for shutdown")
  5607  	}
  5608  
  5609  	// Wait for c.Read to unblock; should be already done at this point,
  5610  	// or within a few milliseconds.
  5611  	select {
  5612  	case err := <-readRes:
  5613  		if err == nil {
  5614  			t.Error("expected error from Read")
  5615  		}
  5616  	case <-time.After(2 * time.Second):
  5617  		t.Errorf("timeout waiting for Read to unblock")
  5618  	}
  5619  }
  5620  
  5621  // Issue 17878: tests that we can call Close twice.
  5622  func TestServerCloseDeadlock(t *testing.T) {
  5623  	var s Server
  5624  	s.Close()
  5625  	s.Close()
  5626  }
  5627  
  5628  // Issue 17717: tests that Server.SetKeepAlivesEnabled is respected by
  5629  // both HTTP/1 and HTTP/2.
  5630  func TestServerKeepAlivesEnabled_h1(t *testing.T) { testServerKeepAlivesEnabled(t, h1Mode) }
  5631  func TestServerKeepAlivesEnabled_h2(t *testing.T) { testServerKeepAlivesEnabled(t, h2Mode) }
  5632  func testServerKeepAlivesEnabled(t *testing.T, h2 bool) {
  5633  	if h2 {
  5634  		restore := ExportSetH2GoawayTimeout(10 * time.Millisecond)
  5635  		defer restore()
  5636  	}
  5637  	// Not parallel: messes with global variable. (http2goAwayTimeout)
  5638  	defer afterTest(t)
  5639  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  5640  		fmt.Fprintf(w, "%v", r.RemoteAddr)
  5641  	}))
  5642  	defer cst.close()
  5643  	srv := cst.ts.Config
  5644  	srv.SetKeepAlivesEnabled(false)
  5645  	a := cst.getURL(cst.ts.URL)
  5646  	if !waitCondition(2*time.Second, 10*time.Millisecond, srv.ExportAllConnsIdle) {
  5647  		t.Fatalf("test server has active conns")
  5648  	}
  5649  	b := cst.getURL(cst.ts.URL)
  5650  	if a == b {
  5651  		t.Errorf("got same connection between first and second requests")
  5652  	}
  5653  	if !waitCondition(2*time.Second, 10*time.Millisecond, srv.ExportAllConnsIdle) {
  5654  		t.Fatalf("test server has active conns")
  5655  	}
  5656  }
  5657  
  5658  // Issue 18447: test that the Server's ReadTimeout is stopped while
  5659  // the server's doing its 1-byte background read between requests,
  5660  // waiting for the connection to maybe close.
  5661  func TestServerCancelsReadTimeoutWhenIdle(t *testing.T) {
  5662  	setParallel(t)
  5663  	defer afterTest(t)
  5664  	runTimeSensitiveTest(t, []time.Duration{
  5665  		10 * time.Millisecond,
  5666  		50 * time.Millisecond,
  5667  		250 * time.Millisecond,
  5668  		time.Second,
  5669  		2 * time.Second,
  5670  	}, func(t *testing.T, timeout time.Duration) error {
  5671  		ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5672  			select {
  5673  			case <-time.After(2 * timeout):
  5674  				fmt.Fprint(w, "ok")
  5675  			case <-r.Context().Done():
  5676  				fmt.Fprint(w, r.Context().Err())
  5677  			}
  5678  		}))
  5679  		ts.Config.ReadTimeout = timeout
  5680  		ts.Start()
  5681  		defer ts.Close()
  5682  
  5683  		c := ts.Client()
  5684  
  5685  		res, err := c.Get(ts.URL)
  5686  		if err != nil {
  5687  			return fmt.Errorf("Get: %v", err)
  5688  		}
  5689  		slurp, err := ioutil.ReadAll(res.Body)
  5690  		res.Body.Close()
  5691  		if err != nil {
  5692  			return fmt.Errorf("Body ReadAll: %v", err)
  5693  		}
  5694  		if string(slurp) != "ok" {
  5695  			return fmt.Errorf("got: %q, want ok", slurp)
  5696  		}
  5697  		return nil
  5698  	})
  5699  }
  5700  
  5701  // runTimeSensitiveTest runs test with the provided durations until one passes.
  5702  // If they all fail, t.Fatal is called with the last one's duration and error value.
  5703  func runTimeSensitiveTest(t *testing.T, durations []time.Duration, test func(t *testing.T, d time.Duration) error) {
  5704  	for i, d := range durations {
  5705  		err := test(t, d)
  5706  		if err == nil {
  5707  			return
  5708  		}
  5709  		if i == len(durations)-1 {
  5710  			t.Fatalf("failed with duration %v: %v", d, err)
  5711  		}
  5712  	}
  5713  }
  5714  
  5715  // Issue 18535: test that the Server doesn't try to do a background
  5716  // read if it's already done one.
  5717  func TestServerDuplicateBackgroundRead(t *testing.T) {
  5718  	if runtime.GOOS == "netbsd" && runtime.GOARCH == "arm" {
  5719  		testenv.SkipFlaky(t, 24826)
  5720  	}
  5721  
  5722  	setParallel(t)
  5723  	defer afterTest(t)
  5724  
  5725  	const goroutines = 5
  5726  	const requests = 2000
  5727  
  5728  	hts := httptest.NewServer(HandlerFunc(NotFound))
  5729  	defer hts.Close()
  5730  
  5731  	reqBytes := []byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")
  5732  
  5733  	var wg sync.WaitGroup
  5734  	for i := 0; i < goroutines; i++ {
  5735  		wg.Add(1)
  5736  		go func() {
  5737  			defer wg.Done()
  5738  			cn, err := net.Dial("tcp", hts.Listener.Addr().String())
  5739  			if err != nil {
  5740  				t.Error(err)
  5741  				return
  5742  			}
  5743  			defer cn.Close()
  5744  
  5745  			wg.Add(1)
  5746  			go func() {
  5747  				defer wg.Done()
  5748  				io.Copy(ioutil.Discard, cn)
  5749  			}()
  5750  
  5751  			for j := 0; j < requests; j++ {
  5752  				if t.Failed() {
  5753  					return
  5754  				}
  5755  				_, err := cn.Write(reqBytes)
  5756  				if err != nil {
  5757  					t.Error(err)
  5758  					return
  5759  				}
  5760  			}
  5761  		}()
  5762  	}
  5763  	wg.Wait()
  5764  }
  5765  
  5766  // Test that the bufio.Reader returned by Hijack includes any buffered
  5767  // byte (from the Server's backgroundRead) in its buffer. We want the
  5768  // Handler code to be able to tell that a byte is available via
  5769  // bufio.Reader.Buffered(), without resorting to Reading it
  5770  // (potentially blocking) to get at it.
  5771  func TestServerHijackGetsBackgroundByte(t *testing.T) {
  5772  	if runtime.GOOS == "plan9" {
  5773  		t.Skip("skipping test; see https://golang.org/issue/18657")
  5774  	}
  5775  	setParallel(t)
  5776  	defer afterTest(t)
  5777  	done := make(chan struct{})
  5778  	inHandler := make(chan bool, 1)
  5779  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5780  		defer close(done)
  5781  
  5782  		// Tell the client to send more data after the GET request.
  5783  		inHandler <- true
  5784  
  5785  		conn, buf, err := w.(Hijacker).Hijack()
  5786  		if err != nil {
  5787  			t.Error(err)
  5788  			return
  5789  		}
  5790  		defer conn.Close()
  5791  
  5792  		peek, err := buf.Reader.Peek(3)
  5793  		if string(peek) != "foo" || err != nil {
  5794  			t.Errorf("Peek = %q, %v; want foo, nil", peek, err)
  5795  		}
  5796  
  5797  		select {
  5798  		case <-r.Context().Done():
  5799  			t.Error("context unexpectedly canceled")
  5800  		default:
  5801  		}
  5802  	}))
  5803  	defer ts.Close()
  5804  
  5805  	cn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5806  	if err != nil {
  5807  		t.Fatal(err)
  5808  	}
  5809  	defer cn.Close()
  5810  	if _, err := cn.Write([]byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")); err != nil {
  5811  		t.Fatal(err)
  5812  	}
  5813  	<-inHandler
  5814  	if _, err := cn.Write([]byte("foo")); err != nil {
  5815  		t.Fatal(err)
  5816  	}
  5817  
  5818  	if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
  5819  		t.Fatal(err)
  5820  	}
  5821  	select {
  5822  	case <-done:
  5823  	case <-time.After(2 * time.Second):
  5824  		t.Error("timeout")
  5825  	}
  5826  }
  5827  
  5828  // Like TestServerHijackGetsBackgroundByte above but sending a
  5829  // immediate 1MB of data to the server to fill up the server's 4KB
  5830  // buffer.
  5831  func TestServerHijackGetsBackgroundByte_big(t *testing.T) {
  5832  	if runtime.GOOS == "plan9" {
  5833  		t.Skip("skipping test; see https://golang.org/issue/18657")
  5834  	}
  5835  	setParallel(t)
  5836  	defer afterTest(t)
  5837  	done := make(chan struct{})
  5838  	const size = 8 << 10
  5839  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5840  		defer close(done)
  5841  
  5842  		conn, buf, err := w.(Hijacker).Hijack()
  5843  		if err != nil {
  5844  			t.Error(err)
  5845  			return
  5846  		}
  5847  		defer conn.Close()
  5848  		slurp, err := ioutil.ReadAll(buf.Reader)
  5849  		if err != nil {
  5850  			t.Errorf("Copy: %v", err)
  5851  		}
  5852  		allX := true
  5853  		for _, v := range slurp {
  5854  			if v != 'x' {
  5855  				allX = false
  5856  			}
  5857  		}
  5858  		if len(slurp) != size {
  5859  			t.Errorf("read %d; want %d", len(slurp), size)
  5860  		} else if !allX {
  5861  			t.Errorf("read %q; want %d 'x'", slurp, size)
  5862  		}
  5863  	}))
  5864  	defer ts.Close()
  5865  
  5866  	cn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5867  	if err != nil {
  5868  		t.Fatal(err)
  5869  	}
  5870  	defer cn.Close()
  5871  	if _, err := fmt.Fprintf(cn, "GET / HTTP/1.1\r\nHost: e.com\r\n\r\n%s",
  5872  		strings.Repeat("x", size)); err != nil {
  5873  		t.Fatal(err)
  5874  	}
  5875  	if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
  5876  		t.Fatal(err)
  5877  	}
  5878  
  5879  	select {
  5880  	case <-done:
  5881  	case <-time.After(2 * time.Second):
  5882  		t.Error("timeout")
  5883  	}
  5884  }
  5885  
  5886  // Issue 18319: test that the Server validates the request method.
  5887  func TestServerValidatesMethod(t *testing.T) {
  5888  	tests := []struct {
  5889  		method string
  5890  		want   int
  5891  	}{
  5892  		{"GET", 200},
  5893  		{"GE(T", 400},
  5894  	}
  5895  	for _, tt := range tests {
  5896  		conn := &testConn{closec: make(chan bool, 1)}
  5897  		io.WriteString(&conn.readBuf, tt.method+" / HTTP/1.1\r\nHost: foo.example\r\n\r\n")
  5898  
  5899  		ln := &oneConnListener{conn}
  5900  		go Serve(ln, serve(200))
  5901  		<-conn.closec
  5902  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  5903  		if err != nil {
  5904  			t.Errorf("For %s, ReadResponse: %v", tt.method, res)
  5905  			continue
  5906  		}
  5907  		if res.StatusCode != tt.want {
  5908  			t.Errorf("For %s, Status = %d; want %d", tt.method, res.StatusCode, tt.want)
  5909  		}
  5910  	}
  5911  }
  5912  
  5913  // Listener for TestServerListenNotComparableListener.
  5914  type eofListenerNotComparable []int
  5915  
  5916  func (eofListenerNotComparable) Accept() (net.Conn, error) { return nil, io.EOF }
  5917  func (eofListenerNotComparable) Addr() net.Addr            { return nil }
  5918  func (eofListenerNotComparable) Close() error              { return nil }
  5919  
  5920  // Issue 24812: don't crash on non-comparable Listener
  5921  func TestServerListenNotComparableListener(t *testing.T) {
  5922  	var s Server
  5923  	s.Serve(make(eofListenerNotComparable, 1)) // used to panic
  5924  }
  5925  
  5926  // countCloseListener is a Listener wrapper that counts the number of Close calls.
  5927  type countCloseListener struct {
  5928  	net.Listener
  5929  	closes int32 // atomic
  5930  }
  5931  
  5932  func (p *countCloseListener) Close() error {
  5933  	atomic.AddInt32(&p.closes, 1)
  5934  	return nil
  5935  }
  5936  
  5937  // Issue 24803: don't call Listener.Close on Server.Shutdown.
  5938  func TestServerCloseListenerOnce(t *testing.T) {
  5939  	setParallel(t)
  5940  	defer afterTest(t)
  5941  
  5942  	ln := newLocalListener(t)
  5943  	defer ln.Close()
  5944  
  5945  	cl := &countCloseListener{Listener: ln}
  5946  	server := &Server{}
  5947  	sdone := make(chan bool, 1)
  5948  
  5949  	go func() {
  5950  		server.Serve(cl)
  5951  		sdone <- true
  5952  	}()
  5953  	time.Sleep(10 * time.Millisecond)
  5954  	server.Shutdown(context.Background())
  5955  	ln.Close()
  5956  	<-sdone
  5957  
  5958  	nclose := atomic.LoadInt32(&cl.closes)
  5959  	if nclose != 1 {
  5960  		t.Errorf("Close calls = %v; want 1", nclose)
  5961  	}
  5962  }
  5963  
  5964  // Issue 20239: don't block in Serve if Shutdown is called first.
  5965  func TestServerShutdownThenServe(t *testing.T) {
  5966  	var srv Server
  5967  	cl := &countCloseListener{Listener: nil}
  5968  	srv.Shutdown(context.Background())
  5969  	got := srv.Serve(cl)
  5970  	if got != ErrServerClosed {
  5971  		t.Errorf("Serve err = %v; want ErrServerClosed", got)
  5972  	}
  5973  	nclose := atomic.LoadInt32(&cl.closes)
  5974  	if nclose != 1 {
  5975  		t.Errorf("Close calls = %v; want 1", nclose)
  5976  	}
  5977  }
  5978  
  5979  // Issue 23351: document and test behavior of ServeMux with ports
  5980  func TestStripPortFromHost(t *testing.T) {
  5981  	mux := NewServeMux()
  5982  
  5983  	mux.HandleFunc("example.com/", func(w ResponseWriter, r *Request) {
  5984  		fmt.Fprintf(w, "OK")
  5985  	})
  5986  	mux.HandleFunc("example.com:9000/", func(w ResponseWriter, r *Request) {
  5987  		fmt.Fprintf(w, "uh-oh!")
  5988  	})
  5989  
  5990  	req := httptest.NewRequest("GET", "http://example.com:9000/", nil)
  5991  	rw := httptest.NewRecorder()
  5992  
  5993  	mux.ServeHTTP(rw, req)
  5994  
  5995  	response := rw.Body.String()
  5996  	if response != "OK" {
  5997  		t.Errorf("Response gotten was %q", response)
  5998  	}
  5999  }
  6000  
  6001  func BenchmarkResponseStatusLine(b *testing.B) {
  6002  	b.ReportAllocs()
  6003  	b.RunParallel(func(pb *testing.PB) {
  6004  		bw := bufio.NewWriter(ioutil.Discard)
  6005  		var buf3 [3]byte
  6006  		for pb.Next() {
  6007  			Export_writeStatusLine(bw, true, 200, buf3[:])
  6008  		}
  6009  	})
  6010  }
  6011  

View as plain text