...
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.ReplaceAll(strings.TrimSpace(req), "\n", "\r\n") + "\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  // Test that the HTTPS server nicely rejects plaintext HTTP/1.x requests.
  1560  func TestTLSServerRejectHTTPRequests(t *testing.T) {
  1561  	setParallel(t)
  1562  	defer afterTest(t)
  1563  	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1564  		t.Error("unexpected HTTPS request")
  1565  	}))
  1566  	var errBuf bytes.Buffer
  1567  	ts.Config.ErrorLog = log.New(&errBuf, "", 0)
  1568  	defer ts.Close()
  1569  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  1570  	if err != nil {
  1571  		t.Fatal(err)
  1572  	}
  1573  	defer conn.Close()
  1574  	io.WriteString(conn, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n")
  1575  	slurp, err := ioutil.ReadAll(conn)
  1576  	if err != nil {
  1577  		t.Fatal(err)
  1578  	}
  1579  	const wantPrefix = "HTTP/1.0 400 Bad Request\r\n"
  1580  	if !strings.HasPrefix(string(slurp), wantPrefix) {
  1581  		t.Errorf("response = %q; wanted prefix %q", slurp, wantPrefix)
  1582  	}
  1583  }
  1584  
  1585  // Issue 15908
  1586  func TestAutomaticHTTP2_Serve_NoTLSConfig(t *testing.T) {
  1587  	testAutomaticHTTP2_Serve(t, nil, true)
  1588  }
  1589  
  1590  func TestAutomaticHTTP2_Serve_NonH2TLSConfig(t *testing.T) {
  1591  	testAutomaticHTTP2_Serve(t, &tls.Config{}, false)
  1592  }
  1593  
  1594  func TestAutomaticHTTP2_Serve_H2TLSConfig(t *testing.T) {
  1595  	testAutomaticHTTP2_Serve(t, &tls.Config{NextProtos: []string{"h2"}}, true)
  1596  }
  1597  
  1598  func testAutomaticHTTP2_Serve(t *testing.T, tlsConf *tls.Config, wantH2 bool) {
  1599  	setParallel(t)
  1600  	defer afterTest(t)
  1601  	ln := newLocalListener(t)
  1602  	ln.Close() // immediately (not a defer!)
  1603  	var s Server
  1604  	s.TLSConfig = tlsConf
  1605  	if err := s.Serve(ln); err == nil {
  1606  		t.Fatal("expected an error")
  1607  	}
  1608  	gotH2 := s.TLSNextProto["h2"] != nil
  1609  	if gotH2 != wantH2 {
  1610  		t.Errorf("http2 configured = %v; want %v", gotH2, wantH2)
  1611  	}
  1612  }
  1613  
  1614  func TestAutomaticHTTP2_Serve_WithTLSConfig(t *testing.T) {
  1615  	setParallel(t)
  1616  	defer afterTest(t)
  1617  	ln := newLocalListener(t)
  1618  	ln.Close() // immediately (not a defer!)
  1619  	var s Server
  1620  	// Set the TLSConfig. In reality, this would be the
  1621  	// *tls.Config given to tls.NewListener.
  1622  	s.TLSConfig = &tls.Config{
  1623  		NextProtos: []string{"h2"},
  1624  	}
  1625  	if err := s.Serve(ln); err == nil {
  1626  		t.Fatal("expected an error")
  1627  	}
  1628  	on := s.TLSNextProto["h2"] != nil
  1629  	if !on {
  1630  		t.Errorf("http2 wasn't automatically enabled")
  1631  	}
  1632  }
  1633  
  1634  func TestAutomaticHTTP2_ListenAndServe(t *testing.T) {
  1635  	cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
  1636  	if err != nil {
  1637  		t.Fatal(err)
  1638  	}
  1639  	testAutomaticHTTP2_ListenAndServe(t, &tls.Config{
  1640  		Certificates: []tls.Certificate{cert},
  1641  	})
  1642  }
  1643  
  1644  func TestAutomaticHTTP2_ListenAndServe_GetCertificate(t *testing.T) {
  1645  	cert, err := tls.X509KeyPair(internal.LocalhostCert, internal.LocalhostKey)
  1646  	if err != nil {
  1647  		t.Fatal(err)
  1648  	}
  1649  	testAutomaticHTTP2_ListenAndServe(t, &tls.Config{
  1650  		GetCertificate: func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  1651  			return &cert, nil
  1652  		},
  1653  	})
  1654  }
  1655  
  1656  func testAutomaticHTTP2_ListenAndServe(t *testing.T, tlsConf *tls.Config) {
  1657  	// Not parallel: uses global test hooks.
  1658  	defer afterTest(t)
  1659  	defer SetTestHookServerServe(nil)
  1660  	var ok bool
  1661  	var s *Server
  1662  	const maxTries = 5
  1663  	var ln net.Listener
  1664  Try:
  1665  	for try := 0; try < maxTries; try++ {
  1666  		ln = newLocalListener(t)
  1667  		addr := ln.Addr().String()
  1668  		ln.Close()
  1669  		t.Logf("Got %v", addr)
  1670  		lnc := make(chan net.Listener, 1)
  1671  		SetTestHookServerServe(func(s *Server, ln net.Listener) {
  1672  			lnc <- ln
  1673  		})
  1674  		s = &Server{
  1675  			Addr:      addr,
  1676  			TLSConfig: tlsConf,
  1677  		}
  1678  		errc := make(chan error, 1)
  1679  		go func() { errc <- s.ListenAndServeTLS("", "") }()
  1680  		select {
  1681  		case err := <-errc:
  1682  			t.Logf("On try #%v: %v", try+1, err)
  1683  			continue
  1684  		case ln = <-lnc:
  1685  			ok = true
  1686  			t.Logf("Listening on %v", ln.Addr().String())
  1687  			break Try
  1688  		}
  1689  	}
  1690  	if !ok {
  1691  		t.Fatalf("Failed to start up after %d tries", maxTries)
  1692  	}
  1693  	defer ln.Close()
  1694  	c, err := tls.Dial("tcp", ln.Addr().String(), &tls.Config{
  1695  		InsecureSkipVerify: true,
  1696  		NextProtos:         []string{"h2", "http/1.1"},
  1697  	})
  1698  	if err != nil {
  1699  		t.Fatal(err)
  1700  	}
  1701  	defer c.Close()
  1702  	if got, want := c.ConnectionState().NegotiatedProtocol, "h2"; got != want {
  1703  		t.Errorf("NegotiatedProtocol = %q; want %q", got, want)
  1704  	}
  1705  	if got, want := c.ConnectionState().NegotiatedProtocolIsMutual, true; got != want {
  1706  		t.Errorf("NegotiatedProtocolIsMutual = %v; want %v", got, want)
  1707  	}
  1708  }
  1709  
  1710  type serverExpectTest struct {
  1711  	contentLength    int // of request body
  1712  	chunked          bool
  1713  	expectation      string // e.g. "100-continue"
  1714  	readBody         bool   // whether handler should read the body (if false, sends StatusUnauthorized)
  1715  	expectedResponse string // expected substring in first line of http response
  1716  }
  1717  
  1718  func expectTest(contentLength int, expectation string, readBody bool, expectedResponse string) serverExpectTest {
  1719  	return serverExpectTest{
  1720  		contentLength:    contentLength,
  1721  		expectation:      expectation,
  1722  		readBody:         readBody,
  1723  		expectedResponse: expectedResponse,
  1724  	}
  1725  }
  1726  
  1727  var serverExpectTests = []serverExpectTest{
  1728  	// Normal 100-continues, case-insensitive.
  1729  	expectTest(100, "100-continue", true, "100 Continue"),
  1730  	expectTest(100, "100-cOntInUE", true, "100 Continue"),
  1731  
  1732  	// No 100-continue.
  1733  	expectTest(100, "", true, "200 OK"),
  1734  
  1735  	// 100-continue but requesting client to deny us,
  1736  	// so it never reads the body.
  1737  	expectTest(100, "100-continue", false, "401 Unauthorized"),
  1738  	// Likewise without 100-continue:
  1739  	expectTest(100, "", false, "401 Unauthorized"),
  1740  
  1741  	// Non-standard expectations are failures
  1742  	expectTest(0, "a-pony", false, "417 Expectation Failed"),
  1743  
  1744  	// Expect-100 requested but no body (is apparently okay: Issue 7625)
  1745  	expectTest(0, "100-continue", true, "200 OK"),
  1746  	// Expect-100 requested but handler doesn't read the body
  1747  	expectTest(0, "100-continue", false, "401 Unauthorized"),
  1748  	// Expect-100 continue with no body, but a chunked body.
  1749  	{
  1750  		expectation:      "100-continue",
  1751  		readBody:         true,
  1752  		chunked:          true,
  1753  		expectedResponse: "100 Continue",
  1754  	},
  1755  }
  1756  
  1757  // Tests that the server responds to the "Expect" request header
  1758  // correctly.
  1759  // http2 test: TestServer_Response_Automatic100Continue
  1760  func TestServerExpect(t *testing.T) {
  1761  	setParallel(t)
  1762  	defer afterTest(t)
  1763  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  1764  		// Note using r.FormValue("readbody") because for POST
  1765  		// requests that would read from r.Body, which we only
  1766  		// conditionally want to do.
  1767  		if strings.Contains(r.URL.RawQuery, "readbody=true") {
  1768  			ioutil.ReadAll(r.Body)
  1769  			w.Write([]byte("Hi"))
  1770  		} else {
  1771  			w.WriteHeader(StatusUnauthorized)
  1772  		}
  1773  	}))
  1774  	defer ts.Close()
  1775  
  1776  	runTest := func(test serverExpectTest) {
  1777  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  1778  		if err != nil {
  1779  			t.Fatalf("Dial: %v", err)
  1780  		}
  1781  		defer conn.Close()
  1782  
  1783  		// Only send the body immediately if we're acting like an HTTP client
  1784  		// that doesn't send 100-continue expectations.
  1785  		writeBody := test.contentLength != 0 && strings.ToLower(test.expectation) != "100-continue"
  1786  
  1787  		go func() {
  1788  			contentLen := fmt.Sprintf("Content-Length: %d", test.contentLength)
  1789  			if test.chunked {
  1790  				contentLen = "Transfer-Encoding: chunked"
  1791  			}
  1792  			_, err := fmt.Fprintf(conn, "POST /?readbody=%v HTTP/1.1\r\n"+
  1793  				"Connection: close\r\n"+
  1794  				"%s\r\n"+
  1795  				"Expect: %s\r\nHost: foo\r\n\r\n",
  1796  				test.readBody, contentLen, test.expectation)
  1797  			if err != nil {
  1798  				t.Errorf("On test %#v, error writing request headers: %v", test, err)
  1799  				return
  1800  			}
  1801  			if writeBody {
  1802  				var targ io.WriteCloser = struct {
  1803  					io.Writer
  1804  					io.Closer
  1805  				}{
  1806  					conn,
  1807  					ioutil.NopCloser(nil),
  1808  				}
  1809  				if test.chunked {
  1810  					targ = httputil.NewChunkedWriter(conn)
  1811  				}
  1812  				body := strings.Repeat("A", test.contentLength)
  1813  				_, err = fmt.Fprint(targ, body)
  1814  				if err == nil {
  1815  					err = targ.Close()
  1816  				}
  1817  				if err != nil {
  1818  					if !test.readBody {
  1819  						// Server likely already hung up on us.
  1820  						// See larger comment below.
  1821  						t.Logf("On test %#v, acceptable error writing request body: %v", test, err)
  1822  						return
  1823  					}
  1824  					t.Errorf("On test %#v, error writing request body: %v", test, err)
  1825  				}
  1826  			}
  1827  		}()
  1828  		bufr := bufio.NewReader(conn)
  1829  		line, err := bufr.ReadString('\n')
  1830  		if err != nil {
  1831  			if writeBody && !test.readBody {
  1832  				// This is an acceptable failure due to a possible TCP race:
  1833  				// We were still writing data and the server hung up on us. A TCP
  1834  				// implementation may send a RST if our request body data was known
  1835  				// to be lost, which may trigger our reads to fail.
  1836  				// See RFC 1122 page 88.
  1837  				t.Logf("On test %#v, acceptable error from ReadString: %v", test, err)
  1838  				return
  1839  			}
  1840  			t.Fatalf("On test %#v, ReadString: %v", test, err)
  1841  		}
  1842  		if !strings.Contains(line, test.expectedResponse) {
  1843  			t.Errorf("On test %#v, got first line = %q; want %q", test, line, test.expectedResponse)
  1844  		}
  1845  	}
  1846  
  1847  	for _, test := range serverExpectTests {
  1848  		runTest(test)
  1849  	}
  1850  }
  1851  
  1852  // Under a ~256KB (maxPostHandlerReadBytes) threshold, the server
  1853  // should consume client request bodies that a handler didn't read.
  1854  func TestServerUnreadRequestBodyLittle(t *testing.T) {
  1855  	setParallel(t)
  1856  	defer afterTest(t)
  1857  	conn := new(testConn)
  1858  	body := strings.Repeat("x", 100<<10)
  1859  	conn.readBuf.Write([]byte(fmt.Sprintf(
  1860  		"POST / HTTP/1.1\r\n"+
  1861  			"Host: test\r\n"+
  1862  			"Content-Length: %d\r\n"+
  1863  			"\r\n", len(body))))
  1864  	conn.readBuf.Write([]byte(body))
  1865  
  1866  	done := make(chan bool)
  1867  
  1868  	readBufLen := func() int {
  1869  		conn.readMu.Lock()
  1870  		defer conn.readMu.Unlock()
  1871  		return conn.readBuf.Len()
  1872  	}
  1873  
  1874  	ls := &oneConnListener{conn}
  1875  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  1876  		defer close(done)
  1877  		if bufLen := readBufLen(); bufLen < len(body)/2 {
  1878  			t.Errorf("on request, read buffer length is %d; expected about 100 KB", bufLen)
  1879  		}
  1880  		rw.WriteHeader(200)
  1881  		rw.(Flusher).Flush()
  1882  		if g, e := readBufLen(), 0; g != e {
  1883  			t.Errorf("after WriteHeader, read buffer length is %d; want %d", g, e)
  1884  		}
  1885  		if c := rw.Header().Get("Connection"); c != "" {
  1886  			t.Errorf(`Connection header = %q; want ""`, c)
  1887  		}
  1888  	}))
  1889  	<-done
  1890  }
  1891  
  1892  // Over a ~256KB (maxPostHandlerReadBytes) threshold, the server
  1893  // should ignore client request bodies that a handler didn't read
  1894  // and close the connection.
  1895  func TestServerUnreadRequestBodyLarge(t *testing.T) {
  1896  	setParallel(t)
  1897  	if testing.Short() && testenv.Builder() == "" {
  1898  		t.Log("skipping in short mode")
  1899  	}
  1900  	conn := new(testConn)
  1901  	body := strings.Repeat("x", 1<<20)
  1902  	conn.readBuf.Write([]byte(fmt.Sprintf(
  1903  		"POST / HTTP/1.1\r\n"+
  1904  			"Host: test\r\n"+
  1905  			"Content-Length: %d\r\n"+
  1906  			"\r\n", len(body))))
  1907  	conn.readBuf.Write([]byte(body))
  1908  	conn.closec = make(chan bool, 1)
  1909  
  1910  	ls := &oneConnListener{conn}
  1911  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  1912  		if conn.readBuf.Len() < len(body)/2 {
  1913  			t.Errorf("on request, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
  1914  		}
  1915  		rw.WriteHeader(200)
  1916  		rw.(Flusher).Flush()
  1917  		if conn.readBuf.Len() < len(body)/2 {
  1918  			t.Errorf("post-WriteHeader, read buffer length is %d; expected about 1MB", conn.readBuf.Len())
  1919  		}
  1920  	}))
  1921  	<-conn.closec
  1922  
  1923  	if res := conn.writeBuf.String(); !strings.Contains(res, "Connection: close") {
  1924  		t.Errorf("Expected a Connection: close header; got response: %s", res)
  1925  	}
  1926  }
  1927  
  1928  type handlerBodyCloseTest struct {
  1929  	bodySize     int
  1930  	bodyChunked  bool
  1931  	reqConnClose bool
  1932  
  1933  	wantEOFSearch bool // should Handler's Body.Close do Reads, looking for EOF?
  1934  	wantNextReq   bool // should it find the next request on the same conn?
  1935  }
  1936  
  1937  func (t handlerBodyCloseTest) connectionHeader() string {
  1938  	if t.reqConnClose {
  1939  		return "Connection: close\r\n"
  1940  	}
  1941  	return ""
  1942  }
  1943  
  1944  var handlerBodyCloseTests = [...]handlerBodyCloseTest{
  1945  	// Small enough to slurp past to the next request +
  1946  	// has Content-Length.
  1947  	0: {
  1948  		bodySize:      20 << 10,
  1949  		bodyChunked:   false,
  1950  		reqConnClose:  false,
  1951  		wantEOFSearch: true,
  1952  		wantNextReq:   true,
  1953  	},
  1954  
  1955  	// Small enough to slurp past to the next request +
  1956  	// is chunked.
  1957  	1: {
  1958  		bodySize:      20 << 10,
  1959  		bodyChunked:   true,
  1960  		reqConnClose:  false,
  1961  		wantEOFSearch: true,
  1962  		wantNextReq:   true,
  1963  	},
  1964  
  1965  	// Small enough to slurp past to the next request +
  1966  	// has Content-Length +
  1967  	// declares Connection: close (so pointless to read more).
  1968  	2: {
  1969  		bodySize:      20 << 10,
  1970  		bodyChunked:   false,
  1971  		reqConnClose:  true,
  1972  		wantEOFSearch: false,
  1973  		wantNextReq:   false,
  1974  	},
  1975  
  1976  	// Small enough to slurp past to the next request +
  1977  	// declares Connection: close,
  1978  	// but chunked, so it might have trailers.
  1979  	// TODO: maybe skip this search if no trailers were declared
  1980  	// in the headers.
  1981  	3: {
  1982  		bodySize:      20 << 10,
  1983  		bodyChunked:   true,
  1984  		reqConnClose:  true,
  1985  		wantEOFSearch: true,
  1986  		wantNextReq:   false,
  1987  	},
  1988  
  1989  	// Big with Content-Length, so give up immediately if we know it's too big.
  1990  	4: {
  1991  		bodySize:      1 << 20,
  1992  		bodyChunked:   false, // has a Content-Length
  1993  		reqConnClose:  false,
  1994  		wantEOFSearch: false,
  1995  		wantNextReq:   false,
  1996  	},
  1997  
  1998  	// Big chunked, so read a bit before giving up.
  1999  	5: {
  2000  		bodySize:      1 << 20,
  2001  		bodyChunked:   true,
  2002  		reqConnClose:  false,
  2003  		wantEOFSearch: true,
  2004  		wantNextReq:   false,
  2005  	},
  2006  
  2007  	// Big with Connection: close, but chunked, so search for trailers.
  2008  	// TODO: maybe skip this search if no trailers were declared
  2009  	// in the headers.
  2010  	6: {
  2011  		bodySize:      1 << 20,
  2012  		bodyChunked:   true,
  2013  		reqConnClose:  true,
  2014  		wantEOFSearch: true,
  2015  		wantNextReq:   false,
  2016  	},
  2017  
  2018  	// Big with Connection: close, so don't do any reads on Close.
  2019  	// With Content-Length.
  2020  	7: {
  2021  		bodySize:      1 << 20,
  2022  		bodyChunked:   false,
  2023  		reqConnClose:  true,
  2024  		wantEOFSearch: false,
  2025  		wantNextReq:   false,
  2026  	},
  2027  }
  2028  
  2029  func TestHandlerBodyClose(t *testing.T) {
  2030  	setParallel(t)
  2031  	if testing.Short() && testenv.Builder() == "" {
  2032  		t.Skip("skipping in -short mode")
  2033  	}
  2034  	for i, tt := range handlerBodyCloseTests {
  2035  		testHandlerBodyClose(t, i, tt)
  2036  	}
  2037  }
  2038  
  2039  func testHandlerBodyClose(t *testing.T, i int, tt handlerBodyCloseTest) {
  2040  	conn := new(testConn)
  2041  	body := strings.Repeat("x", tt.bodySize)
  2042  	if tt.bodyChunked {
  2043  		conn.readBuf.WriteString("POST / HTTP/1.1\r\n" +
  2044  			"Host: test\r\n" +
  2045  			tt.connectionHeader() +
  2046  			"Transfer-Encoding: chunked\r\n" +
  2047  			"\r\n")
  2048  		cw := internal.NewChunkedWriter(&conn.readBuf)
  2049  		io.WriteString(cw, body)
  2050  		cw.Close()
  2051  		conn.readBuf.WriteString("\r\n")
  2052  	} else {
  2053  		conn.readBuf.Write([]byte(fmt.Sprintf(
  2054  			"POST / HTTP/1.1\r\n"+
  2055  				"Host: test\r\n"+
  2056  				tt.connectionHeader()+
  2057  				"Content-Length: %d\r\n"+
  2058  				"\r\n", len(body))))
  2059  		conn.readBuf.Write([]byte(body))
  2060  	}
  2061  	if !tt.reqConnClose {
  2062  		conn.readBuf.WriteString("GET / HTTP/1.1\r\nHost: test\r\n\r\n")
  2063  	}
  2064  	conn.closec = make(chan bool, 1)
  2065  
  2066  	readBufLen := func() int {
  2067  		conn.readMu.Lock()
  2068  		defer conn.readMu.Unlock()
  2069  		return conn.readBuf.Len()
  2070  	}
  2071  
  2072  	ls := &oneConnListener{conn}
  2073  	var numReqs int
  2074  	var size0, size1 int
  2075  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  2076  		numReqs++
  2077  		if numReqs == 1 {
  2078  			size0 = readBufLen()
  2079  			req.Body.Close()
  2080  			size1 = readBufLen()
  2081  		}
  2082  	}))
  2083  	<-conn.closec
  2084  	if numReqs < 1 || numReqs > 2 {
  2085  		t.Fatalf("%d. bug in test. unexpected number of requests = %d", i, numReqs)
  2086  	}
  2087  	didSearch := size0 != size1
  2088  	if didSearch != tt.wantEOFSearch {
  2089  		t.Errorf("%d. did EOF search = %v; want %v (size went from %d to %d)", i, didSearch, !didSearch, size0, size1)
  2090  	}
  2091  	if tt.wantNextReq && numReqs != 2 {
  2092  		t.Errorf("%d. numReq = %d; want 2", i, numReqs)
  2093  	}
  2094  }
  2095  
  2096  // testHandlerBodyConsumer represents a function injected into a test handler to
  2097  // vary work done on a request Body.
  2098  type testHandlerBodyConsumer struct {
  2099  	name string
  2100  	f    func(io.ReadCloser)
  2101  }
  2102  
  2103  var testHandlerBodyConsumers = []testHandlerBodyConsumer{
  2104  	{"nil", func(io.ReadCloser) {}},
  2105  	{"close", func(r io.ReadCloser) { r.Close() }},
  2106  	{"discard", func(r io.ReadCloser) { io.Copy(ioutil.Discard, r) }},
  2107  }
  2108  
  2109  func TestRequestBodyReadErrorClosesConnection(t *testing.T) {
  2110  	setParallel(t)
  2111  	defer afterTest(t)
  2112  	for _, handler := range testHandlerBodyConsumers {
  2113  		conn := new(testConn)
  2114  		conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
  2115  			"Host: test\r\n" +
  2116  			"Transfer-Encoding: chunked\r\n" +
  2117  			"\r\n" +
  2118  			"hax\r\n" + // Invalid chunked encoding
  2119  			"GET /secret HTTP/1.1\r\n" +
  2120  			"Host: test\r\n" +
  2121  			"\r\n")
  2122  
  2123  		conn.closec = make(chan bool, 1)
  2124  		ls := &oneConnListener{conn}
  2125  		var numReqs int
  2126  		go Serve(ls, HandlerFunc(func(_ ResponseWriter, req *Request) {
  2127  			numReqs++
  2128  			if strings.Contains(req.URL.Path, "secret") {
  2129  				t.Error("Request for /secret encountered, should not have happened.")
  2130  			}
  2131  			handler.f(req.Body)
  2132  		}))
  2133  		<-conn.closec
  2134  		if numReqs != 1 {
  2135  			t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
  2136  		}
  2137  	}
  2138  }
  2139  
  2140  func TestInvalidTrailerClosesConnection(t *testing.T) {
  2141  	setParallel(t)
  2142  	defer afterTest(t)
  2143  	for _, handler := range testHandlerBodyConsumers {
  2144  		conn := new(testConn)
  2145  		conn.readBuf.WriteString("POST /public HTTP/1.1\r\n" +
  2146  			"Host: test\r\n" +
  2147  			"Trailer: hack\r\n" +
  2148  			"Transfer-Encoding: chunked\r\n" +
  2149  			"\r\n" +
  2150  			"3\r\n" +
  2151  			"hax\r\n" +
  2152  			"0\r\n" +
  2153  			"I'm not a valid trailer\r\n" +
  2154  			"GET /secret HTTP/1.1\r\n" +
  2155  			"Host: test\r\n" +
  2156  			"\r\n")
  2157  
  2158  		conn.closec = make(chan bool, 1)
  2159  		ln := &oneConnListener{conn}
  2160  		var numReqs int
  2161  		go Serve(ln, HandlerFunc(func(_ ResponseWriter, req *Request) {
  2162  			numReqs++
  2163  			if strings.Contains(req.URL.Path, "secret") {
  2164  				t.Errorf("Handler %s, Request for /secret encountered, should not have happened.", handler.name)
  2165  			}
  2166  			handler.f(req.Body)
  2167  		}))
  2168  		<-conn.closec
  2169  		if numReqs != 1 {
  2170  			t.Errorf("Handler %s: got %d reqs; want 1", handler.name, numReqs)
  2171  		}
  2172  	}
  2173  }
  2174  
  2175  // slowTestConn is a net.Conn that provides a means to simulate parts of a
  2176  // request being received piecemeal. Deadlines can be set and enforced in both
  2177  // Read and Write.
  2178  type slowTestConn struct {
  2179  	// over multiple calls to Read, time.Durations are slept, strings are read.
  2180  	script []interface{}
  2181  	closec chan bool
  2182  
  2183  	mu     sync.Mutex // guards rd/wd
  2184  	rd, wd time.Time  // read, write deadline
  2185  	noopConn
  2186  }
  2187  
  2188  func (c *slowTestConn) SetDeadline(t time.Time) error {
  2189  	c.SetReadDeadline(t)
  2190  	c.SetWriteDeadline(t)
  2191  	return nil
  2192  }
  2193  
  2194  func (c *slowTestConn) SetReadDeadline(t time.Time) error {
  2195  	c.mu.Lock()
  2196  	defer c.mu.Unlock()
  2197  	c.rd = t
  2198  	return nil
  2199  }
  2200  
  2201  func (c *slowTestConn) SetWriteDeadline(t time.Time) error {
  2202  	c.mu.Lock()
  2203  	defer c.mu.Unlock()
  2204  	c.wd = t
  2205  	return nil
  2206  }
  2207  
  2208  func (c *slowTestConn) Read(b []byte) (n int, err error) {
  2209  	c.mu.Lock()
  2210  	defer c.mu.Unlock()
  2211  restart:
  2212  	if !c.rd.IsZero() && time.Now().After(c.rd) {
  2213  		return 0, syscall.ETIMEDOUT
  2214  	}
  2215  	if len(c.script) == 0 {
  2216  		return 0, io.EOF
  2217  	}
  2218  
  2219  	switch cue := c.script[0].(type) {
  2220  	case time.Duration:
  2221  		if !c.rd.IsZero() {
  2222  			// If the deadline falls in the middle of our sleep window, deduct
  2223  			// part of the sleep, then return a timeout.
  2224  			if remaining := time.Until(c.rd); remaining < cue {
  2225  				c.script[0] = cue - remaining
  2226  				time.Sleep(remaining)
  2227  				return 0, syscall.ETIMEDOUT
  2228  			}
  2229  		}
  2230  		c.script = c.script[1:]
  2231  		time.Sleep(cue)
  2232  		goto restart
  2233  
  2234  	case string:
  2235  		n = copy(b, cue)
  2236  		// If cue is too big for the buffer, leave the end for the next Read.
  2237  		if len(cue) > n {
  2238  			c.script[0] = cue[n:]
  2239  		} else {
  2240  			c.script = c.script[1:]
  2241  		}
  2242  
  2243  	default:
  2244  		panic("unknown cue in slowTestConn script")
  2245  	}
  2246  
  2247  	return
  2248  }
  2249  
  2250  func (c *slowTestConn) Close() error {
  2251  	select {
  2252  	case c.closec <- true:
  2253  	default:
  2254  	}
  2255  	return nil
  2256  }
  2257  
  2258  func (c *slowTestConn) Write(b []byte) (int, error) {
  2259  	if !c.wd.IsZero() && time.Now().After(c.wd) {
  2260  		return 0, syscall.ETIMEDOUT
  2261  	}
  2262  	return len(b), nil
  2263  }
  2264  
  2265  func TestRequestBodyTimeoutClosesConnection(t *testing.T) {
  2266  	if testing.Short() {
  2267  		t.Skip("skipping in -short mode")
  2268  	}
  2269  	defer afterTest(t)
  2270  	for _, handler := range testHandlerBodyConsumers {
  2271  		conn := &slowTestConn{
  2272  			script: []interface{}{
  2273  				"POST /public HTTP/1.1\r\n" +
  2274  					"Host: test\r\n" +
  2275  					"Content-Length: 10000\r\n" +
  2276  					"\r\n",
  2277  				"foo bar baz",
  2278  				600 * time.Millisecond, // Request deadline should hit here
  2279  				"GET /secret HTTP/1.1\r\n" +
  2280  					"Host: test\r\n" +
  2281  					"\r\n",
  2282  			},
  2283  			closec: make(chan bool, 1),
  2284  		}
  2285  		ls := &oneConnListener{conn}
  2286  
  2287  		var numReqs int
  2288  		s := Server{
  2289  			Handler: HandlerFunc(func(_ ResponseWriter, req *Request) {
  2290  				numReqs++
  2291  				if strings.Contains(req.URL.Path, "secret") {
  2292  					t.Error("Request for /secret encountered, should not have happened.")
  2293  				}
  2294  				handler.f(req.Body)
  2295  			}),
  2296  			ReadTimeout: 400 * time.Millisecond,
  2297  		}
  2298  		go s.Serve(ls)
  2299  		<-conn.closec
  2300  
  2301  		if numReqs != 1 {
  2302  			t.Errorf("Handler %v: got %d reqs; want 1", handler.name, numReqs)
  2303  		}
  2304  	}
  2305  }
  2306  
  2307  func TestTimeoutHandler_h1(t *testing.T) { testTimeoutHandler(t, h1Mode) }
  2308  func TestTimeoutHandler_h2(t *testing.T) { testTimeoutHandler(t, h2Mode) }
  2309  func testTimeoutHandler(t *testing.T, h2 bool) {
  2310  	setParallel(t)
  2311  	defer afterTest(t)
  2312  	sendHi := make(chan bool, 1)
  2313  	writeErrors := make(chan error, 1)
  2314  	sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2315  		<-sendHi
  2316  		_, werr := w.Write([]byte("hi"))
  2317  		writeErrors <- werr
  2318  	})
  2319  	timeout := make(chan time.Time, 1) // write to this to force timeouts
  2320  	cst := newClientServerTest(t, h2, NewTestTimeoutHandler(sayHi, timeout))
  2321  	defer cst.close()
  2322  
  2323  	// Succeed without timing out:
  2324  	sendHi <- true
  2325  	res, err := cst.c.Get(cst.ts.URL)
  2326  	if err != nil {
  2327  		t.Error(err)
  2328  	}
  2329  	if g, e := res.StatusCode, StatusOK; g != e {
  2330  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2331  	}
  2332  	body, _ := ioutil.ReadAll(res.Body)
  2333  	if g, e := string(body), "hi"; g != e {
  2334  		t.Errorf("got body %q; expected %q", g, e)
  2335  	}
  2336  	if g := <-writeErrors; g != nil {
  2337  		t.Errorf("got unexpected Write error on first request: %v", g)
  2338  	}
  2339  
  2340  	// Times out:
  2341  	timeout <- time.Time{}
  2342  	res, err = cst.c.Get(cst.ts.URL)
  2343  	if err != nil {
  2344  		t.Error(err)
  2345  	}
  2346  	if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  2347  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2348  	}
  2349  	body, _ = ioutil.ReadAll(res.Body)
  2350  	if !strings.Contains(string(body), "<title>Timeout</title>") {
  2351  		t.Errorf("expected timeout body; got %q", string(body))
  2352  	}
  2353  	if g, w := res.Header.Get("Content-Type"), "text/html; charset=utf-8"; g != w {
  2354  		t.Errorf("response content-type = %q; want %q", g, w)
  2355  	}
  2356  
  2357  	// Now make the previously-timed out handler speak again,
  2358  	// which verifies the panic is handled:
  2359  	sendHi <- true
  2360  	if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
  2361  		t.Errorf("expected Write error of %v; got %v", e, g)
  2362  	}
  2363  }
  2364  
  2365  // See issues 8209 and 8414.
  2366  func TestTimeoutHandlerRace(t *testing.T) {
  2367  	setParallel(t)
  2368  	defer afterTest(t)
  2369  
  2370  	delayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2371  		ms, _ := strconv.Atoi(r.URL.Path[1:])
  2372  		if ms == 0 {
  2373  			ms = 1
  2374  		}
  2375  		for i := 0; i < ms; i++ {
  2376  			w.Write([]byte("hi"))
  2377  			time.Sleep(time.Millisecond)
  2378  		}
  2379  	})
  2380  
  2381  	ts := httptest.NewServer(TimeoutHandler(delayHi, 20*time.Millisecond, ""))
  2382  	defer ts.Close()
  2383  
  2384  	c := ts.Client()
  2385  
  2386  	var wg sync.WaitGroup
  2387  	gate := make(chan bool, 10)
  2388  	n := 50
  2389  	if testing.Short() {
  2390  		n = 10
  2391  		gate = make(chan bool, 3)
  2392  	}
  2393  	for i := 0; i < n; i++ {
  2394  		gate <- true
  2395  		wg.Add(1)
  2396  		go func() {
  2397  			defer wg.Done()
  2398  			defer func() { <-gate }()
  2399  			res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50)))
  2400  			if err == nil {
  2401  				io.Copy(ioutil.Discard, res.Body)
  2402  				res.Body.Close()
  2403  			}
  2404  		}()
  2405  	}
  2406  	wg.Wait()
  2407  }
  2408  
  2409  // See issues 8209 and 8414.
  2410  func TestTimeoutHandlerRaceHeader(t *testing.T) {
  2411  	setParallel(t)
  2412  	defer afterTest(t)
  2413  
  2414  	delay204 := HandlerFunc(func(w ResponseWriter, r *Request) {
  2415  		w.WriteHeader(204)
  2416  	})
  2417  
  2418  	ts := httptest.NewServer(TimeoutHandler(delay204, time.Nanosecond, ""))
  2419  	defer ts.Close()
  2420  
  2421  	var wg sync.WaitGroup
  2422  	gate := make(chan bool, 50)
  2423  	n := 500
  2424  	if testing.Short() {
  2425  		n = 10
  2426  	}
  2427  
  2428  	c := ts.Client()
  2429  	for i := 0; i < n; i++ {
  2430  		gate <- true
  2431  		wg.Add(1)
  2432  		go func() {
  2433  			defer wg.Done()
  2434  			defer func() { <-gate }()
  2435  			res, err := c.Get(ts.URL)
  2436  			if err != nil {
  2437  				t.Error(err)
  2438  				return
  2439  			}
  2440  			defer res.Body.Close()
  2441  			io.Copy(ioutil.Discard, res.Body)
  2442  		}()
  2443  	}
  2444  	wg.Wait()
  2445  }
  2446  
  2447  // Issue 9162
  2448  func TestTimeoutHandlerRaceHeaderTimeout(t *testing.T) {
  2449  	setParallel(t)
  2450  	defer afterTest(t)
  2451  	sendHi := make(chan bool, 1)
  2452  	writeErrors := make(chan error, 1)
  2453  	sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2454  		w.Header().Set("Content-Type", "text/plain")
  2455  		<-sendHi
  2456  		_, werr := w.Write([]byte("hi"))
  2457  		writeErrors <- werr
  2458  	})
  2459  	timeout := make(chan time.Time, 1) // write to this to force timeouts
  2460  	cst := newClientServerTest(t, h1Mode, NewTestTimeoutHandler(sayHi, timeout))
  2461  	defer cst.close()
  2462  
  2463  	// Succeed without timing out:
  2464  	sendHi <- true
  2465  	res, err := cst.c.Get(cst.ts.URL)
  2466  	if err != nil {
  2467  		t.Error(err)
  2468  	}
  2469  	if g, e := res.StatusCode, StatusOK; g != e {
  2470  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2471  	}
  2472  	body, _ := ioutil.ReadAll(res.Body)
  2473  	if g, e := string(body), "hi"; g != e {
  2474  		t.Errorf("got body %q; expected %q", g, e)
  2475  	}
  2476  	if g := <-writeErrors; g != nil {
  2477  		t.Errorf("got unexpected Write error on first request: %v", g)
  2478  	}
  2479  
  2480  	// Times out:
  2481  	timeout <- time.Time{}
  2482  	res, err = cst.c.Get(cst.ts.URL)
  2483  	if err != nil {
  2484  		t.Error(err)
  2485  	}
  2486  	if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  2487  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2488  	}
  2489  	body, _ = ioutil.ReadAll(res.Body)
  2490  	if !strings.Contains(string(body), "<title>Timeout</title>") {
  2491  		t.Errorf("expected timeout body; got %q", string(body))
  2492  	}
  2493  
  2494  	// Now make the previously-timed out handler speak again,
  2495  	// which verifies the panic is handled:
  2496  	sendHi <- true
  2497  	if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
  2498  		t.Errorf("expected Write error of %v; got %v", e, g)
  2499  	}
  2500  }
  2501  
  2502  // Issue 14568.
  2503  func TestTimeoutHandlerStartTimerWhenServing(t *testing.T) {
  2504  	if testing.Short() {
  2505  		t.Skip("skipping sleeping test in -short mode")
  2506  	}
  2507  	defer afterTest(t)
  2508  	var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
  2509  		w.WriteHeader(StatusNoContent)
  2510  	}
  2511  	timeout := 300 * time.Millisecond
  2512  	ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
  2513  	defer ts.Close()
  2514  
  2515  	c := ts.Client()
  2516  
  2517  	// Issue was caused by the timeout handler starting the timer when
  2518  	// was created, not when the request. So wait for more than the timeout
  2519  	// to ensure that's not the case.
  2520  	time.Sleep(2 * timeout)
  2521  	res, err := c.Get(ts.URL)
  2522  	if err != nil {
  2523  		t.Fatal(err)
  2524  	}
  2525  	defer res.Body.Close()
  2526  	if res.StatusCode != StatusNoContent {
  2527  		t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusNoContent)
  2528  	}
  2529  }
  2530  
  2531  // https://golang.org/issue/15948
  2532  func TestTimeoutHandlerEmptyResponse(t *testing.T) {
  2533  	setParallel(t)
  2534  	defer afterTest(t)
  2535  	var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
  2536  		// No response.
  2537  	}
  2538  	timeout := 300 * time.Millisecond
  2539  	ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
  2540  	defer ts.Close()
  2541  
  2542  	c := ts.Client()
  2543  
  2544  	res, err := c.Get(ts.URL)
  2545  	if err != nil {
  2546  		t.Fatal(err)
  2547  	}
  2548  	defer res.Body.Close()
  2549  	if res.StatusCode != StatusOK {
  2550  		t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusOK)
  2551  	}
  2552  }
  2553  
  2554  // https://golang.org/issues/22084
  2555  func TestTimeoutHandlerPanicRecovery(t *testing.T) {
  2556  	wrapper := func(h Handler) Handler {
  2557  		return TimeoutHandler(h, time.Second, "")
  2558  	}
  2559  	testHandlerPanic(t, false, false, wrapper, "intentional death for testing")
  2560  }
  2561  
  2562  func TestRedirectBadPath(t *testing.T) {
  2563  	// This used to crash. It's not valid input (bad path), but it
  2564  	// shouldn't crash.
  2565  	rr := httptest.NewRecorder()
  2566  	req := &Request{
  2567  		Method: "GET",
  2568  		URL: &url.URL{
  2569  			Scheme: "http",
  2570  			Path:   "not-empty-but-no-leading-slash", // bogus
  2571  		},
  2572  	}
  2573  	Redirect(rr, req, "", 304)
  2574  	if rr.Code != 304 {
  2575  		t.Errorf("Code = %d; want 304", rr.Code)
  2576  	}
  2577  }
  2578  
  2579  // Test different URL formats and schemes
  2580  func TestRedirect(t *testing.T) {
  2581  	req, _ := NewRequest("GET", "http://example.com/qux/", nil)
  2582  
  2583  	var tests = []struct {
  2584  		in   string
  2585  		want string
  2586  	}{
  2587  		// normal http
  2588  		{"http://foobar.com/baz", "http://foobar.com/baz"},
  2589  		// normal https
  2590  		{"https://foobar.com/baz", "https://foobar.com/baz"},
  2591  		// custom scheme
  2592  		{"test://foobar.com/baz", "test://foobar.com/baz"},
  2593  		// schemeless
  2594  		{"//foobar.com/baz", "//foobar.com/baz"},
  2595  		// relative to the root
  2596  		{"/foobar.com/baz", "/foobar.com/baz"},
  2597  		// relative to the current path
  2598  		{"foobar.com/baz", "/qux/foobar.com/baz"},
  2599  		// relative to the current path (+ going upwards)
  2600  		{"../quux/foobar.com/baz", "/quux/foobar.com/baz"},
  2601  		// incorrect number of slashes
  2602  		{"///foobar.com/baz", "/foobar.com/baz"},
  2603  
  2604  		// Verifies we don't path.Clean() on the wrong parts in redirects:
  2605  		{"/foo?next=http://bar.com/", "/foo?next=http://bar.com/"},
  2606  		{"http://localhost:8080/_ah/login?continue=http://localhost:8080/",
  2607  			"http://localhost:8080/_ah/login?continue=http://localhost:8080/"},
  2608  
  2609  		{"/фубар", "/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
  2610  		{"http://foo.com/фубар", "http://foo.com/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
  2611  	}
  2612  
  2613  	for _, tt := range tests {
  2614  		rec := httptest.NewRecorder()
  2615  		Redirect(rec, req, tt.in, 302)
  2616  		if got, want := rec.Code, 302; got != want {
  2617  			t.Errorf("Redirect(%q) generated status code %v; want %v", tt.in, got, want)
  2618  		}
  2619  		if got := rec.Header().Get("Location"); got != tt.want {
  2620  			t.Errorf("Redirect(%q) generated Location header %q; want %q", tt.in, got, tt.want)
  2621  		}
  2622  	}
  2623  }
  2624  
  2625  // Test that Redirect sets Content-Type header for GET and HEAD requests
  2626  // and writes a short HTML body, unless the request already has a Content-Type header.
  2627  func TestRedirect_contentTypeAndBody(t *testing.T) {
  2628  	type ctHeader struct {
  2629  		Values []string
  2630  	}
  2631  
  2632  	var tests = []struct {
  2633  		method   string
  2634  		ct       *ctHeader // Optional Content-Type header to set.
  2635  		wantCT   string
  2636  		wantBody string
  2637  	}{
  2638  		{MethodGet, nil, "text/html; charset=utf-8", "<a href=\"/foo\">Found</a>.\n\n"},
  2639  		{MethodHead, nil, "text/html; charset=utf-8", ""},
  2640  		{MethodPost, nil, "", ""},
  2641  		{MethodDelete, nil, "", ""},
  2642  		{"foo", nil, "", ""},
  2643  		{MethodGet, &ctHeader{[]string{"application/test"}}, "application/test", ""},
  2644  		{MethodGet, &ctHeader{[]string{}}, "", ""},
  2645  		{MethodGet, &ctHeader{nil}, "", ""},
  2646  	}
  2647  	for _, tt := range tests {
  2648  		req := httptest.NewRequest(tt.method, "http://example.com/qux/", nil)
  2649  		rec := httptest.NewRecorder()
  2650  		if tt.ct != nil {
  2651  			rec.Header()["Content-Type"] = tt.ct.Values
  2652  		}
  2653  		Redirect(rec, req, "/foo", 302)
  2654  		if got, want := rec.Code, 302; got != want {
  2655  			t.Errorf("Redirect(%q, %#v) generated status code %v; want %v", tt.method, tt.ct, got, want)
  2656  		}
  2657  		if got, want := rec.Header().Get("Content-Type"), tt.wantCT; got != want {
  2658  			t.Errorf("Redirect(%q, %#v) generated Content-Type header %q; want %q", tt.method, tt.ct, got, want)
  2659  		}
  2660  		resp := rec.Result()
  2661  		body, err := ioutil.ReadAll(resp.Body)
  2662  		if err != nil {
  2663  			t.Fatal(err)
  2664  		}
  2665  		if got, want := string(body), tt.wantBody; got != want {
  2666  			t.Errorf("Redirect(%q, %#v) generated Body %q; want %q", tt.method, tt.ct, got, want)
  2667  		}
  2668  	}
  2669  }
  2670  
  2671  // TestZeroLengthPostAndResponse exercises an optimization done by the Transport:
  2672  // when there is no body (either because the method doesn't permit a body, or an
  2673  // explicit Content-Length of zero is present), then the transport can re-use the
  2674  // connection immediately. But when it re-uses the connection, it typically closes
  2675  // the previous request's body, which is not optimal for zero-lengthed bodies,
  2676  // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF.
  2677  func TestZeroLengthPostAndResponse_h1(t *testing.T) {
  2678  	testZeroLengthPostAndResponse(t, h1Mode)
  2679  }
  2680  func TestZeroLengthPostAndResponse_h2(t *testing.T) {
  2681  	testZeroLengthPostAndResponse(t, h2Mode)
  2682  }
  2683  
  2684  func testZeroLengthPostAndResponse(t *testing.T, h2 bool) {
  2685  	setParallel(t)
  2686  	defer afterTest(t)
  2687  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, r *Request) {
  2688  		all, err := ioutil.ReadAll(r.Body)
  2689  		if err != nil {
  2690  			t.Fatalf("handler ReadAll: %v", err)
  2691  		}
  2692  		if len(all) != 0 {
  2693  			t.Errorf("handler got %d bytes; expected 0", len(all))
  2694  		}
  2695  		rw.Header().Set("Content-Length", "0")
  2696  	}))
  2697  	defer cst.close()
  2698  
  2699  	req, err := NewRequest("POST", cst.ts.URL, strings.NewReader(""))
  2700  	if err != nil {
  2701  		t.Fatal(err)
  2702  	}
  2703  	req.ContentLength = 0
  2704  
  2705  	var resp [5]*Response
  2706  	for i := range resp {
  2707  		resp[i], err = cst.c.Do(req)
  2708  		if err != nil {
  2709  			t.Fatalf("client post #%d: %v", i, err)
  2710  		}
  2711  	}
  2712  
  2713  	for i := range resp {
  2714  		all, err := ioutil.ReadAll(resp[i].Body)
  2715  		if err != nil {
  2716  			t.Fatalf("req #%d: client ReadAll: %v", i, err)
  2717  		}
  2718  		if len(all) != 0 {
  2719  			t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all))
  2720  		}
  2721  	}
  2722  }
  2723  
  2724  func TestHandlerPanicNil_h1(t *testing.T) { testHandlerPanic(t, false, h1Mode, nil, nil) }
  2725  func TestHandlerPanicNil_h2(t *testing.T) { testHandlerPanic(t, false, h2Mode, nil, nil) }
  2726  
  2727  func TestHandlerPanic_h1(t *testing.T) {
  2728  	testHandlerPanic(t, false, h1Mode, nil, "intentional death for testing")
  2729  }
  2730  func TestHandlerPanic_h2(t *testing.T) {
  2731  	testHandlerPanic(t, false, h2Mode, nil, "intentional death for testing")
  2732  }
  2733  
  2734  func TestHandlerPanicWithHijack(t *testing.T) {
  2735  	// Only testing HTTP/1, and our http2 server doesn't support hijacking.
  2736  	testHandlerPanic(t, true, h1Mode, nil, "intentional death for testing")
  2737  }
  2738  
  2739  func testHandlerPanic(t *testing.T, withHijack, h2 bool, wrapper func(Handler) Handler, panicValue interface{}) {
  2740  	defer afterTest(t)
  2741  	// Unlike the other tests that set the log output to ioutil.Discard
  2742  	// to quiet the output, this test uses a pipe. The pipe serves three
  2743  	// purposes:
  2744  	//
  2745  	//   1) The log.Print from the http server (generated by the caught
  2746  	//      panic) will go to the pipe instead of stderr, making the
  2747  	//      output quiet.
  2748  	//
  2749  	//   2) We read from the pipe to verify that the handler
  2750  	//      actually caught the panic and logged something.
  2751  	//
  2752  	//   3) The blocking Read call prevents this TestHandlerPanic
  2753  	//      function from exiting before the HTTP server handler
  2754  	//      finishes crashing. If this text function exited too
  2755  	//      early (and its defer log.SetOutput(os.Stderr) ran),
  2756  	//      then the crash output could spill into the next test.
  2757  	pr, pw := io.Pipe()
  2758  	log.SetOutput(pw)
  2759  	defer log.SetOutput(os.Stderr)
  2760  	defer pw.Close()
  2761  
  2762  	var handler Handler = HandlerFunc(func(w ResponseWriter, r *Request) {
  2763  		if withHijack {
  2764  			rwc, _, err := w.(Hijacker).Hijack()
  2765  			if err != nil {
  2766  				t.Logf("unexpected error: %v", err)
  2767  			}
  2768  			defer rwc.Close()
  2769  		}
  2770  		panic(panicValue)
  2771  	})
  2772  	if wrapper != nil {
  2773  		handler = wrapper(handler)
  2774  	}
  2775  	cst := newClientServerTest(t, h2, handler)
  2776  	defer cst.close()
  2777  
  2778  	// Do a blocking read on the log output pipe so its logging
  2779  	// doesn't bleed into the next test. But wait only 5 seconds
  2780  	// for it.
  2781  	done := make(chan bool, 1)
  2782  	go func() {
  2783  		buf := make([]byte, 4<<10)
  2784  		_, err := pr.Read(buf)
  2785  		pr.Close()
  2786  		if err != nil && err != io.EOF {
  2787  			t.Error(err)
  2788  		}
  2789  		done <- true
  2790  	}()
  2791  
  2792  	_, err := cst.c.Get(cst.ts.URL)
  2793  	if err == nil {
  2794  		t.Logf("expected an error")
  2795  	}
  2796  
  2797  	if panicValue == nil {
  2798  		return
  2799  	}
  2800  
  2801  	select {
  2802  	case <-done:
  2803  		return
  2804  	case <-time.After(5 * time.Second):
  2805  		t.Fatal("expected server handler to log an error")
  2806  	}
  2807  }
  2808  
  2809  type terrorWriter struct{ t *testing.T }
  2810  
  2811  func (w terrorWriter) Write(p []byte) (int, error) {
  2812  	w.t.Errorf("%s", p)
  2813  	return len(p), nil
  2814  }
  2815  
  2816  // Issue 16456: allow writing 0 bytes on hijacked conn to test hijack
  2817  // without any log spam.
  2818  func TestServerWriteHijackZeroBytes(t *testing.T) {
  2819  	defer afterTest(t)
  2820  	done := make(chan struct{})
  2821  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  2822  		defer close(done)
  2823  		w.(Flusher).Flush()
  2824  		conn, _, err := w.(Hijacker).Hijack()
  2825  		if err != nil {
  2826  			t.Errorf("Hijack: %v", err)
  2827  			return
  2828  		}
  2829  		defer conn.Close()
  2830  		_, err = w.Write(nil)
  2831  		if err != ErrHijacked {
  2832  			t.Errorf("Write error = %v; want ErrHijacked", err)
  2833  		}
  2834  	}))
  2835  	ts.Config.ErrorLog = log.New(terrorWriter{t}, "Unexpected write: ", 0)
  2836  	ts.Start()
  2837  	defer ts.Close()
  2838  
  2839  	c := ts.Client()
  2840  	res, err := c.Get(ts.URL)
  2841  	if err != nil {
  2842  		t.Fatal(err)
  2843  	}
  2844  	res.Body.Close()
  2845  	select {
  2846  	case <-done:
  2847  	case <-time.After(5 * time.Second):
  2848  		t.Fatal("timeout")
  2849  	}
  2850  }
  2851  
  2852  func TestServerNoDate_h1(t *testing.T)        { testServerNoHeader(t, h1Mode, "Date") }
  2853  func TestServerNoDate_h2(t *testing.T)        { testServerNoHeader(t, h2Mode, "Date") }
  2854  func TestServerNoContentType_h1(t *testing.T) { testServerNoHeader(t, h1Mode, "Content-Type") }
  2855  func TestServerNoContentType_h2(t *testing.T) { testServerNoHeader(t, h2Mode, "Content-Type") }
  2856  
  2857  func testServerNoHeader(t *testing.T, h2 bool, header string) {
  2858  	setParallel(t)
  2859  	defer afterTest(t)
  2860  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2861  		w.Header()[header] = nil
  2862  		io.WriteString(w, "<html>foo</html>") // non-empty
  2863  	}))
  2864  	defer cst.close()
  2865  	res, err := cst.c.Get(cst.ts.URL)
  2866  	if err != nil {
  2867  		t.Fatal(err)
  2868  	}
  2869  	res.Body.Close()
  2870  	if got, ok := res.Header[header]; ok {
  2871  		t.Fatalf("Expected no %s header; got %q", header, got)
  2872  	}
  2873  }
  2874  
  2875  func TestStripPrefix(t *testing.T) {
  2876  	setParallel(t)
  2877  	defer afterTest(t)
  2878  	h := HandlerFunc(func(w ResponseWriter, r *Request) {
  2879  		w.Header().Set("X-Path", r.URL.Path)
  2880  	})
  2881  	ts := httptest.NewServer(StripPrefix("/foo", h))
  2882  	defer ts.Close()
  2883  
  2884  	c := ts.Client()
  2885  
  2886  	res, err := c.Get(ts.URL + "/foo/bar")
  2887  	if err != nil {
  2888  		t.Fatal(err)
  2889  	}
  2890  	if g, e := res.Header.Get("X-Path"), "/bar"; g != e {
  2891  		t.Errorf("test 1: got %s, want %s", g, e)
  2892  	}
  2893  	res.Body.Close()
  2894  
  2895  	res, err = Get(ts.URL + "/bar")
  2896  	if err != nil {
  2897  		t.Fatal(err)
  2898  	}
  2899  	if g, e := res.StatusCode, 404; g != e {
  2900  		t.Errorf("test 2: got status %v, want %v", g, e)
  2901  	}
  2902  	res.Body.Close()
  2903  }
  2904  
  2905  // https://golang.org/issue/18952.
  2906  func TestStripPrefix_notModifyRequest(t *testing.T) {
  2907  	h := StripPrefix("/foo", NotFoundHandler())
  2908  	req := httptest.NewRequest("GET", "/foo/bar", nil)
  2909  	h.ServeHTTP(httptest.NewRecorder(), req)
  2910  	if req.URL.Path != "/foo/bar" {
  2911  		t.Errorf("StripPrefix should not modify the provided Request, but it did")
  2912  	}
  2913  }
  2914  
  2915  func TestRequestLimit_h1(t *testing.T) { testRequestLimit(t, h1Mode) }
  2916  func TestRequestLimit_h2(t *testing.T) { testRequestLimit(t, h2Mode) }
  2917  func testRequestLimit(t *testing.T, h2 bool) {
  2918  	setParallel(t)
  2919  	defer afterTest(t)
  2920  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2921  		t.Fatalf("didn't expect to get request in Handler")
  2922  	}), optQuietLog)
  2923  	defer cst.close()
  2924  	req, _ := NewRequest("GET", cst.ts.URL, nil)
  2925  	var bytesPerHeader = len("header12345: val12345\r\n")
  2926  	for i := 0; i < ((DefaultMaxHeaderBytes+4096)/bytesPerHeader)+1; i++ {
  2927  		req.Header.Set(fmt.Sprintf("header%05d", i), fmt.Sprintf("val%05d", i))
  2928  	}
  2929  	res, err := cst.c.Do(req)
  2930  	if res != nil {
  2931  		defer res.Body.Close()
  2932  	}
  2933  	if h2 {
  2934  		// In HTTP/2, the result depends on a race. If the client has received the
  2935  		// server's SETTINGS before RoundTrip starts sending the request, then RoundTrip
  2936  		// will fail with an error. Otherwise, the client should receive a 431 from the
  2937  		// server.
  2938  		if err == nil && res.StatusCode != 431 {
  2939  			t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
  2940  		}
  2941  	} else {
  2942  		// In HTTP/1, we expect a 431 from the server.
  2943  		// Some HTTP clients may fail on this undefined behavior (server replying and
  2944  		// closing the connection while the request is still being written), but
  2945  		// we do support it (at least currently), so we expect a response below.
  2946  		if err != nil {
  2947  			t.Fatalf("Do: %v", err)
  2948  		}
  2949  		if res.StatusCode != 431 {
  2950  			t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
  2951  		}
  2952  	}
  2953  }
  2954  
  2955  type neverEnding byte
  2956  
  2957  func (b neverEnding) Read(p []byte) (n int, err error) {
  2958  	for i := range p {
  2959  		p[i] = byte(b)
  2960  	}
  2961  	return len(p), nil
  2962  }
  2963  
  2964  type countReader struct {
  2965  	r io.Reader
  2966  	n *int64
  2967  }
  2968  
  2969  func (cr countReader) Read(p []byte) (n int, err error) {
  2970  	n, err = cr.r.Read(p)
  2971  	atomic.AddInt64(cr.n, int64(n))
  2972  	return
  2973  }
  2974  
  2975  func TestRequestBodyLimit_h1(t *testing.T) { testRequestBodyLimit(t, h1Mode) }
  2976  func TestRequestBodyLimit_h2(t *testing.T) { testRequestBodyLimit(t, h2Mode) }
  2977  func testRequestBodyLimit(t *testing.T, h2 bool) {
  2978  	setParallel(t)
  2979  	defer afterTest(t)
  2980  	const limit = 1 << 20
  2981  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2982  		r.Body = MaxBytesReader(w, r.Body, limit)
  2983  		n, err := io.Copy(ioutil.Discard, r.Body)
  2984  		if err == nil {
  2985  			t.Errorf("expected error from io.Copy")
  2986  		}
  2987  		if n != limit {
  2988  			t.Errorf("io.Copy = %d, want %d", n, limit)
  2989  		}
  2990  	}))
  2991  	defer cst.close()
  2992  
  2993  	nWritten := new(int64)
  2994  	req, _ := NewRequest("POST", cst.ts.URL, io.LimitReader(countReader{neverEnding('a'), nWritten}, limit*200))
  2995  
  2996  	// Send the POST, but don't care it succeeds or not. The
  2997  	// remote side is going to reply and then close the TCP
  2998  	// connection, and HTTP doesn't really define if that's
  2999  	// allowed or not. Some HTTP clients will get the response
  3000  	// and some (like ours, currently) will complain that the
  3001  	// request write failed, without reading the response.
  3002  	//
  3003  	// But that's okay, since what we're really testing is that
  3004  	// the remote side hung up on us before we wrote too much.
  3005  	_, _ = cst.c.Do(req)
  3006  
  3007  	if atomic.LoadInt64(nWritten) > limit*100 {
  3008  		t.Errorf("handler restricted the request body to %d bytes, but client managed to write %d",
  3009  			limit, nWritten)
  3010  	}
  3011  }
  3012  
  3013  // TestClientWriteShutdown tests that if the client shuts down the write
  3014  // side of their TCP connection, the server doesn't send a 400 Bad Request.
  3015  func TestClientWriteShutdown(t *testing.T) {
  3016  	if runtime.GOOS == "plan9" {
  3017  		t.Skip("skipping test; see https://golang.org/issue/17906")
  3018  	}
  3019  	defer afterTest(t)
  3020  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  3021  	defer ts.Close()
  3022  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3023  	if err != nil {
  3024  		t.Fatalf("Dial: %v", err)
  3025  	}
  3026  	err = conn.(*net.TCPConn).CloseWrite()
  3027  	if err != nil {
  3028  		t.Fatalf("CloseWrite: %v", err)
  3029  	}
  3030  	donec := make(chan bool)
  3031  	go func() {
  3032  		defer close(donec)
  3033  		bs, err := ioutil.ReadAll(conn)
  3034  		if err != nil {
  3035  			t.Errorf("ReadAll: %v", err)
  3036  		}
  3037  		got := string(bs)
  3038  		if got != "" {
  3039  			t.Errorf("read %q from server; want nothing", got)
  3040  		}
  3041  	}()
  3042  	select {
  3043  	case <-donec:
  3044  	case <-time.After(10 * time.Second):
  3045  		t.Fatalf("timeout")
  3046  	}
  3047  }
  3048  
  3049  // Tests that chunked server responses that write 1 byte at a time are
  3050  // buffered before chunk headers are added, not after chunk headers.
  3051  func TestServerBufferedChunking(t *testing.T) {
  3052  	conn := new(testConn)
  3053  	conn.readBuf.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
  3054  	conn.closec = make(chan bool, 1)
  3055  	ls := &oneConnListener{conn}
  3056  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3057  		rw.(Flusher).Flush() // force the Header to be sent, in chunking mode, not counting the length
  3058  		rw.Write([]byte{'x'})
  3059  		rw.Write([]byte{'y'})
  3060  		rw.Write([]byte{'z'})
  3061  	}))
  3062  	<-conn.closec
  3063  	if !bytes.HasSuffix(conn.writeBuf.Bytes(), []byte("\r\n\r\n3\r\nxyz\r\n0\r\n\r\n")) {
  3064  		t.Errorf("response didn't end with a single 3 byte 'xyz' chunk; got:\n%q",
  3065  			conn.writeBuf.Bytes())
  3066  	}
  3067  }
  3068  
  3069  // Tests that the server flushes its response headers out when it's
  3070  // ignoring the response body and waits a bit before forcefully
  3071  // closing the TCP connection, causing the client to get a RST.
  3072  // See https://golang.org/issue/3595
  3073  func TestServerGracefulClose(t *testing.T) {
  3074  	setParallel(t)
  3075  	defer afterTest(t)
  3076  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3077  		Error(w, "bye", StatusUnauthorized)
  3078  	}))
  3079  	defer ts.Close()
  3080  
  3081  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3082  	if err != nil {
  3083  		t.Fatal(err)
  3084  	}
  3085  	defer conn.Close()
  3086  	const bodySize = 5 << 20
  3087  	req := []byte(fmt.Sprintf("POST / HTTP/1.1\r\nHost: foo.com\r\nContent-Length: %d\r\n\r\n", bodySize))
  3088  	for i := 0; i < bodySize; i++ {
  3089  		req = append(req, 'x')
  3090  	}
  3091  	writeErr := make(chan error)
  3092  	go func() {
  3093  		_, err := conn.Write(req)
  3094  		writeErr <- err
  3095  	}()
  3096  	br := bufio.NewReader(conn)
  3097  	lineNum := 0
  3098  	for {
  3099  		line, err := br.ReadString('\n')
  3100  		if err == io.EOF {
  3101  			break
  3102  		}
  3103  		if err != nil {
  3104  			t.Fatalf("ReadLine: %v", err)
  3105  		}
  3106  		lineNum++
  3107  		if lineNum == 1 && !strings.Contains(line, "401 Unauthorized") {
  3108  			t.Errorf("Response line = %q; want a 401", line)
  3109  		}
  3110  	}
  3111  	// Wait for write to finish. This is a broken pipe on both
  3112  	// Darwin and Linux, but checking this isn't the point of
  3113  	// the test.
  3114  	<-writeErr
  3115  }
  3116  
  3117  func TestCaseSensitiveMethod_h1(t *testing.T) { testCaseSensitiveMethod(t, h1Mode) }
  3118  func TestCaseSensitiveMethod_h2(t *testing.T) { testCaseSensitiveMethod(t, h2Mode) }
  3119  func testCaseSensitiveMethod(t *testing.T, h2 bool) {
  3120  	defer afterTest(t)
  3121  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  3122  		if r.Method != "get" {
  3123  			t.Errorf(`Got method %q; want "get"`, r.Method)
  3124  		}
  3125  	}))
  3126  	defer cst.close()
  3127  	req, _ := NewRequest("get", cst.ts.URL, nil)
  3128  	res, err := cst.c.Do(req)
  3129  	if err != nil {
  3130  		t.Error(err)
  3131  		return
  3132  	}
  3133  
  3134  	res.Body.Close()
  3135  }
  3136  
  3137  // TestContentLengthZero tests that for both an HTTP/1.0 and HTTP/1.1
  3138  // request (both keep-alive), when a Handler never writes any
  3139  // response, the net/http package adds a "Content-Length: 0" response
  3140  // header.
  3141  func TestContentLengthZero(t *testing.T) {
  3142  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {}))
  3143  	defer ts.Close()
  3144  
  3145  	for _, version := range []string{"HTTP/1.0", "HTTP/1.1"} {
  3146  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3147  		if err != nil {
  3148  			t.Fatalf("error dialing: %v", err)
  3149  		}
  3150  		_, err = fmt.Fprintf(conn, "GET / %v\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n", version)
  3151  		if err != nil {
  3152  			t.Fatalf("error writing: %v", err)
  3153  		}
  3154  		req, _ := NewRequest("GET", "/", nil)
  3155  		res, err := ReadResponse(bufio.NewReader(conn), req)
  3156  		if err != nil {
  3157  			t.Fatalf("error reading response: %v", err)
  3158  		}
  3159  		if te := res.TransferEncoding; len(te) > 0 {
  3160  			t.Errorf("For version %q, Transfer-Encoding = %q; want none", version, te)
  3161  		}
  3162  		if cl := res.ContentLength; cl != 0 {
  3163  			t.Errorf("For version %q, Content-Length = %v; want 0", version, cl)
  3164  		}
  3165  		conn.Close()
  3166  	}
  3167  }
  3168  
  3169  func TestCloseNotifier(t *testing.T) {
  3170  	defer afterTest(t)
  3171  	gotReq := make(chan bool, 1)
  3172  	sawClose := make(chan bool, 1)
  3173  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  3174  		gotReq <- true
  3175  		cc := rw.(CloseNotifier).CloseNotify()
  3176  		<-cc
  3177  		sawClose <- true
  3178  	}))
  3179  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3180  	if err != nil {
  3181  		t.Fatalf("error dialing: %v", err)
  3182  	}
  3183  	diec := make(chan bool)
  3184  	go func() {
  3185  		_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
  3186  		if err != nil {
  3187  			t.Error(err)
  3188  			return
  3189  		}
  3190  		<-diec
  3191  		conn.Close()
  3192  	}()
  3193  For:
  3194  	for {
  3195  		select {
  3196  		case <-gotReq:
  3197  			diec <- true
  3198  		case <-sawClose:
  3199  			break For
  3200  		case <-time.After(5 * time.Second):
  3201  			t.Fatal("timeout")
  3202  		}
  3203  	}
  3204  	ts.Close()
  3205  }
  3206  
  3207  // Tests that a pipelined request does not cause the first request's
  3208  // Handler's CloseNotify channel to fire.
  3209  //
  3210  // Issue 13165 (where it used to deadlock), but behavior changed in Issue 23921.
  3211  func TestCloseNotifierPipelined(t *testing.T) {
  3212  	setParallel(t)
  3213  	defer afterTest(t)
  3214  	gotReq := make(chan bool, 2)
  3215  	sawClose := make(chan bool, 2)
  3216  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  3217  		gotReq <- true
  3218  		cc := rw.(CloseNotifier).CloseNotify()
  3219  		select {
  3220  		case <-cc:
  3221  			t.Error("unexpected CloseNotify")
  3222  		case <-time.After(100 * time.Millisecond):
  3223  		}
  3224  		sawClose <- true
  3225  	}))
  3226  	defer ts.Close()
  3227  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3228  	if err != nil {
  3229  		t.Fatalf("error dialing: %v", err)
  3230  	}
  3231  	diec := make(chan bool, 1)
  3232  	defer close(diec)
  3233  	go func() {
  3234  		const req = "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n"
  3235  		_, err = io.WriteString(conn, req+req) // two requests
  3236  		if err != nil {
  3237  			t.Error(err)
  3238  			return
  3239  		}
  3240  		<-diec
  3241  		conn.Close()
  3242  	}()
  3243  	reqs := 0
  3244  	closes := 0
  3245  	for {
  3246  		select {
  3247  		case <-gotReq:
  3248  			reqs++
  3249  			if reqs > 2 {
  3250  				t.Fatal("too many requests")
  3251  			}
  3252  		case <-sawClose:
  3253  			closes++
  3254  			if closes > 1 {
  3255  				return
  3256  			}
  3257  		case <-time.After(5 * time.Second):
  3258  			ts.CloseClientConnections()
  3259  			t.Fatal("timeout")
  3260  		}
  3261  	}
  3262  }
  3263  
  3264  func TestCloseNotifierChanLeak(t *testing.T) {
  3265  	defer afterTest(t)
  3266  	req := reqBytes("GET / HTTP/1.0\nHost: golang.org")
  3267  	for i := 0; i < 20; i++ {
  3268  		var output bytes.Buffer
  3269  		conn := &rwTestConn{
  3270  			Reader: bytes.NewReader(req),
  3271  			Writer: &output,
  3272  			closec: make(chan bool, 1),
  3273  		}
  3274  		ln := &oneConnListener{conn: conn}
  3275  		handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3276  			// Ignore the return value and never read from
  3277  			// it, testing that we don't leak goroutines
  3278  			// on the sending side:
  3279  			_ = rw.(CloseNotifier).CloseNotify()
  3280  		})
  3281  		go Serve(ln, handler)
  3282  		<-conn.closec
  3283  	}
  3284  }
  3285  
  3286  // Tests that we can use CloseNotifier in one request, and later call Hijack
  3287  // on a second request on the same connection.
  3288  //
  3289  // It also tests that the connReader stitches together its background
  3290  // 1-byte read for CloseNotifier when CloseNotifier doesn't fire with
  3291  // the rest of the second HTTP later.
  3292  //
  3293  // Issue 9763.
  3294  // HTTP/1-only test. (http2 doesn't have Hijack)
  3295  func TestHijackAfterCloseNotifier(t *testing.T) {
  3296  	defer afterTest(t)
  3297  	script := make(chan string, 2)
  3298  	script <- "closenotify"
  3299  	script <- "hijack"
  3300  	close(script)
  3301  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3302  		plan := <-script
  3303  		switch plan {
  3304  		default:
  3305  			panic("bogus plan; too many requests")
  3306  		case "closenotify":
  3307  			w.(CloseNotifier).CloseNotify() // discard result
  3308  			w.Header().Set("X-Addr", r.RemoteAddr)
  3309  		case "hijack":
  3310  			c, _, err := w.(Hijacker).Hijack()
  3311  			if err != nil {
  3312  				t.Errorf("Hijack in Handler: %v", err)
  3313  				return
  3314  			}
  3315  			if _, ok := c.(*net.TCPConn); !ok {
  3316  				// Verify it's not wrapped in some type.
  3317  				// Not strictly a go1 compat issue, but in practice it probably is.
  3318  				t.Errorf("type of hijacked conn is %T; want *net.TCPConn", c)
  3319  			}
  3320  			fmt.Fprintf(c, "HTTP/1.0 200 OK\r\nX-Addr: %v\r\nContent-Length: 0\r\n\r\n", r.RemoteAddr)
  3321  			c.Close()
  3322  			return
  3323  		}
  3324  	}))
  3325  	defer ts.Close()
  3326  	res1, err := Get(ts.URL)
  3327  	if err != nil {
  3328  		log.Fatal(err)
  3329  	}
  3330  	res2, err := Get(ts.URL)
  3331  	if err != nil {
  3332  		log.Fatal(err)
  3333  	}
  3334  	addr1 := res1.Header.Get("X-Addr")
  3335  	addr2 := res2.Header.Get("X-Addr")
  3336  	if addr1 == "" || addr1 != addr2 {
  3337  		t.Errorf("addr1, addr2 = %q, %q; want same", addr1, addr2)
  3338  	}
  3339  }
  3340  
  3341  func TestHijackBeforeRequestBodyRead(t *testing.T) {
  3342  	setParallel(t)
  3343  	defer afterTest(t)
  3344  	var requestBody = bytes.Repeat([]byte("a"), 1<<20)
  3345  	bodyOkay := make(chan bool, 1)
  3346  	gotCloseNotify := make(chan bool, 1)
  3347  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3348  		defer close(bodyOkay) // caller will read false if nothing else
  3349  
  3350  		reqBody := r.Body
  3351  		r.Body = nil // to test that server.go doesn't use this value.
  3352  
  3353  		gone := w.(CloseNotifier).CloseNotify()
  3354  		slurp, err := ioutil.ReadAll(reqBody)
  3355  		if err != nil {
  3356  			t.Errorf("Body read: %v", err)
  3357  			return
  3358  		}
  3359  		if len(slurp) != len(requestBody) {
  3360  			t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody))
  3361  			return
  3362  		}
  3363  		if !bytes.Equal(slurp, requestBody) {
  3364  			t.Error("Backend read wrong request body.") // 1MB; omitting details
  3365  			return
  3366  		}
  3367  		bodyOkay <- true
  3368  		select {
  3369  		case <-gone:
  3370  			gotCloseNotify <- true
  3371  		case <-time.After(5 * time.Second):
  3372  			gotCloseNotify <- false
  3373  		}
  3374  	}))
  3375  	defer ts.Close()
  3376  
  3377  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3378  	if err != nil {
  3379  		t.Fatal(err)
  3380  	}
  3381  	defer conn.Close()
  3382  
  3383  	fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: foo\r\nContent-Length: %d\r\n\r\n%s",
  3384  		len(requestBody), requestBody)
  3385  	if !<-bodyOkay {
  3386  		// already failed.
  3387  		return
  3388  	}
  3389  	conn.Close()
  3390  	if !<-gotCloseNotify {
  3391  		t.Error("timeout waiting for CloseNotify")
  3392  	}
  3393  }
  3394  
  3395  func TestOptions(t *testing.T) {
  3396  	uric := make(chan string, 2) // only expect 1, but leave space for 2
  3397  	mux := NewServeMux()
  3398  	mux.HandleFunc("/", func(w ResponseWriter, r *Request) {
  3399  		uric <- r.RequestURI
  3400  	})
  3401  	ts := httptest.NewServer(mux)
  3402  	defer ts.Close()
  3403  
  3404  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3405  	if err != nil {
  3406  		t.Fatal(err)
  3407  	}
  3408  	defer conn.Close()
  3409  
  3410  	// An OPTIONS * request should succeed.
  3411  	_, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
  3412  	if err != nil {
  3413  		t.Fatal(err)
  3414  	}
  3415  	br := bufio.NewReader(conn)
  3416  	res, err := ReadResponse(br, &Request{Method: "OPTIONS"})
  3417  	if err != nil {
  3418  		t.Fatal(err)
  3419  	}
  3420  	if res.StatusCode != 200 {
  3421  		t.Errorf("Got non-200 response to OPTIONS *: %#v", res)
  3422  	}
  3423  
  3424  	// A GET * request on a ServeMux should fail.
  3425  	_, err = conn.Write([]byte("GET * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
  3426  	if err != nil {
  3427  		t.Fatal(err)
  3428  	}
  3429  	res, err = ReadResponse(br, &Request{Method: "GET"})
  3430  	if err != nil {
  3431  		t.Fatal(err)
  3432  	}
  3433  	if res.StatusCode != 400 {
  3434  		t.Errorf("Got non-400 response to GET *: %#v", res)
  3435  	}
  3436  
  3437  	res, err = Get(ts.URL + "/second")
  3438  	if err != nil {
  3439  		t.Fatal(err)
  3440  	}
  3441  	res.Body.Close()
  3442  	if got := <-uric; got != "/second" {
  3443  		t.Errorf("Handler saw request for %q; want /second", got)
  3444  	}
  3445  }
  3446  
  3447  // Tests regarding the ordering of Write, WriteHeader, Header, and
  3448  // Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the
  3449  // (*response).header to the wire. In Go 1.1, the actual wire flush is
  3450  // delayed, so we could maybe tack on a Content-Length and better
  3451  // Content-Type after we see more (or all) of the output. To preserve
  3452  // compatibility with Go 1, we need to be careful to track which
  3453  // headers were live at the time of WriteHeader, so we write the same
  3454  // ones, even if the handler modifies them (~erroneously) after the
  3455  // first Write.
  3456  func TestHeaderToWire(t *testing.T) {
  3457  	tests := []struct {
  3458  		name    string
  3459  		handler func(ResponseWriter, *Request)
  3460  		check   func(got, logs string) error
  3461  	}{
  3462  		{
  3463  			name: "write without Header",
  3464  			handler: func(rw ResponseWriter, r *Request) {
  3465  				rw.Write([]byte("hello world"))
  3466  			},
  3467  			check: func(got, logs string) error {
  3468  				if !strings.Contains(got, "Content-Length:") {
  3469  					return errors.New("no content-length")
  3470  				}
  3471  				if !strings.Contains(got, "Content-Type: text/plain") {
  3472  					return errors.New("no content-type")
  3473  				}
  3474  				return nil
  3475  			},
  3476  		},
  3477  		{
  3478  			name: "Header mutation before write",
  3479  			handler: func(rw ResponseWriter, r *Request) {
  3480  				h := rw.Header()
  3481  				h.Set("Content-Type", "some/type")
  3482  				rw.Write([]byte("hello world"))
  3483  				h.Set("Too-Late", "bogus")
  3484  			},
  3485  			check: func(got, logs string) error {
  3486  				if !strings.Contains(got, "Content-Length:") {
  3487  					return errors.New("no content-length")
  3488  				}
  3489  				if !strings.Contains(got, "Content-Type: some/type") {
  3490  					return errors.New("wrong content-type")
  3491  				}
  3492  				if strings.Contains(got, "Too-Late") {
  3493  					return errors.New("don't want too-late header")
  3494  				}
  3495  				return nil
  3496  			},
  3497  		},
  3498  		{
  3499  			name: "write then useless Header mutation",
  3500  			handler: func(rw ResponseWriter, r *Request) {
  3501  				rw.Write([]byte("hello world"))
  3502  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3503  			},
  3504  			check: func(got, logs string) error {
  3505  				if strings.Contains(got, "Too-Late") {
  3506  					return errors.New("header appeared from after WriteHeader")
  3507  				}
  3508  				return nil
  3509  			},
  3510  		},
  3511  		{
  3512  			name: "flush then write",
  3513  			handler: func(rw ResponseWriter, r *Request) {
  3514  				rw.(Flusher).Flush()
  3515  				rw.Write([]byte("post-flush"))
  3516  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3517  			},
  3518  			check: func(got, logs string) error {
  3519  				if !strings.Contains(got, "Transfer-Encoding: chunked") {
  3520  					return errors.New("not chunked")
  3521  				}
  3522  				if strings.Contains(got, "Too-Late") {
  3523  					return errors.New("header appeared from after WriteHeader")
  3524  				}
  3525  				return nil
  3526  			},
  3527  		},
  3528  		{
  3529  			name: "header then flush",
  3530  			handler: func(rw ResponseWriter, r *Request) {
  3531  				rw.Header().Set("Content-Type", "some/type")
  3532  				rw.(Flusher).Flush()
  3533  				rw.Write([]byte("post-flush"))
  3534  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3535  			},
  3536  			check: func(got, logs string) error {
  3537  				if !strings.Contains(got, "Transfer-Encoding: chunked") {
  3538  					return errors.New("not chunked")
  3539  				}
  3540  				if strings.Contains(got, "Too-Late") {
  3541  					return errors.New("header appeared from after WriteHeader")
  3542  				}
  3543  				if !strings.Contains(got, "Content-Type: some/type") {
  3544  					return errors.New("wrong content-type")
  3545  				}
  3546  				return nil
  3547  			},
  3548  		},
  3549  		{
  3550  			name: "sniff-on-first-write content-type",
  3551  			handler: func(rw ResponseWriter, r *Request) {
  3552  				rw.Write([]byte("<html><head></head><body>some html</body></html>"))
  3553  				rw.Header().Set("Content-Type", "x/wrong")
  3554  			},
  3555  			check: func(got, logs string) error {
  3556  				if !strings.Contains(got, "Content-Type: text/html") {
  3557  					return errors.New("wrong content-type; want html")
  3558  				}
  3559  				return nil
  3560  			},
  3561  		},
  3562  		{
  3563  			name: "explicit content-type wins",
  3564  			handler: func(rw ResponseWriter, r *Request) {
  3565  				rw.Header().Set("Content-Type", "some/type")
  3566  				rw.Write([]byte("<html><head></head><body>some html</body></html>"))
  3567  			},
  3568  			check: func(got, logs string) error {
  3569  				if !strings.Contains(got, "Content-Type: some/type") {
  3570  					return errors.New("wrong content-type; want html")
  3571  				}
  3572  				return nil
  3573  			},
  3574  		},
  3575  		{
  3576  			name: "empty handler",
  3577  			handler: func(rw ResponseWriter, r *Request) {
  3578  			},
  3579  			check: func(got, logs string) error {
  3580  				if !strings.Contains(got, "Content-Length: 0") {
  3581  					return errors.New("want 0 content-length")
  3582  				}
  3583  				return nil
  3584  			},
  3585  		},
  3586  		{
  3587  			name: "only Header, no write",
  3588  			handler: func(rw ResponseWriter, r *Request) {
  3589  				rw.Header().Set("Some-Header", "some-value")
  3590  			},
  3591  			check: func(got, logs string) error {
  3592  				if !strings.Contains(got, "Some-Header") {
  3593  					return errors.New("didn't get header")
  3594  				}
  3595  				return nil
  3596  			},
  3597  		},
  3598  		{
  3599  			name: "WriteHeader call",
  3600  			handler: func(rw ResponseWriter, r *Request) {
  3601  				rw.WriteHeader(404)
  3602  				rw.Header().Set("Too-Late", "some-value")
  3603  			},
  3604  			check: func(got, logs string) error {
  3605  				if !strings.Contains(got, "404") {
  3606  					return errors.New("wrong status")
  3607  				}
  3608  				if strings.Contains(got, "Too-Late") {
  3609  					return errors.New("shouldn't have seen Too-Late")
  3610  				}
  3611  				return nil
  3612  			},
  3613  		},
  3614  	}
  3615  	for _, tc := range tests {
  3616  		ht := newHandlerTest(HandlerFunc(tc.handler))
  3617  		got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org")
  3618  		logs := ht.logbuf.String()
  3619  		if err := tc.check(got, logs); err != nil {
  3620  			t.Errorf("%s: %v\nGot response:\n%s\n\n%s", tc.name, err, got, logs)
  3621  		}
  3622  	}
  3623  }
  3624  
  3625  // goTimeout runs f, failing t if f takes more than ns to complete.
  3626  func goTimeout(t *testing.T, d time.Duration, f func()) {
  3627  	ch := make(chan bool, 2)
  3628  	timer := time.AfterFunc(d, func() {
  3629  		t.Errorf("Timeout expired after %v", d)
  3630  		ch <- true
  3631  	})
  3632  	defer timer.Stop()
  3633  	go func() {
  3634  		defer func() { ch <- true }()
  3635  		f()
  3636  	}()
  3637  	<-ch
  3638  }
  3639  
  3640  type errorListener struct {
  3641  	errs []error
  3642  }
  3643  
  3644  func (l *errorListener) Accept() (c net.Conn, err error) {
  3645  	if len(l.errs) == 0 {
  3646  		return nil, io.EOF
  3647  	}
  3648  	err = l.errs[0]
  3649  	l.errs = l.errs[1:]
  3650  	return
  3651  }
  3652  
  3653  func (l *errorListener) Close() error {
  3654  	return nil
  3655  }
  3656  
  3657  func (l *errorListener) Addr() net.Addr {
  3658  	return dummyAddr("test-address")
  3659  }
  3660  
  3661  func TestAcceptMaxFds(t *testing.T) {
  3662  	setParallel(t)
  3663  
  3664  	ln := &errorListener{[]error{
  3665  		&net.OpError{
  3666  			Op:  "accept",
  3667  			Err: syscall.EMFILE,
  3668  		}}}
  3669  	server := &Server{
  3670  		Handler:  HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {})),
  3671  		ErrorLog: log.New(ioutil.Discard, "", 0), // noisy otherwise
  3672  	}
  3673  	err := server.Serve(ln)
  3674  	if err != io.EOF {
  3675  		t.Errorf("got error %v, want EOF", err)
  3676  	}
  3677  }
  3678  
  3679  func TestWriteAfterHijack(t *testing.T) {
  3680  	req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
  3681  	var buf bytes.Buffer
  3682  	wrotec := make(chan bool, 1)
  3683  	conn := &rwTestConn{
  3684  		Reader: bytes.NewReader(req),
  3685  		Writer: &buf,
  3686  		closec: make(chan bool, 1),
  3687  	}
  3688  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3689  		conn, bufrw, err := rw.(Hijacker).Hijack()
  3690  		if err != nil {
  3691  			t.Error(err)
  3692  			return
  3693  		}
  3694  		go func() {
  3695  			bufrw.Write([]byte("[hijack-to-bufw]"))
  3696  			bufrw.Flush()
  3697  			conn.Write([]byte("[hijack-to-conn]"))
  3698  			conn.Close()
  3699  			wrotec <- true
  3700  		}()
  3701  	})
  3702  	ln := &oneConnListener{conn: conn}
  3703  	go Serve(ln, handler)
  3704  	<-conn.closec
  3705  	<-wrotec
  3706  	if g, w := buf.String(), "[hijack-to-bufw][hijack-to-conn]"; g != w {
  3707  		t.Errorf("wrote %q; want %q", g, w)
  3708  	}
  3709  }
  3710  
  3711  func TestDoubleHijack(t *testing.T) {
  3712  	req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
  3713  	var buf bytes.Buffer
  3714  	conn := &rwTestConn{
  3715  		Reader: bytes.NewReader(req),
  3716  		Writer: &buf,
  3717  		closec: make(chan bool, 1),
  3718  	}
  3719  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3720  		conn, _, err := rw.(Hijacker).Hijack()
  3721  		if err != nil {
  3722  			t.Error(err)
  3723  			return
  3724  		}
  3725  		_, _, err = rw.(Hijacker).Hijack()
  3726  		if err == nil {
  3727  			t.Errorf("got err = nil;  want err != nil")
  3728  		}
  3729  		conn.Close()
  3730  	})
  3731  	ln := &oneConnListener{conn: conn}
  3732  	go Serve(ln, handler)
  3733  	<-conn.closec
  3734  }
  3735  
  3736  // https://golang.org/issue/5955
  3737  // Note that this does not test the "request too large"
  3738  // exit path from the http server. This is intentional;
  3739  // not sending Connection: close is just a minor wire
  3740  // optimization and is pointless if dealing with a
  3741  // badly behaved client.
  3742  func TestHTTP10ConnectionHeader(t *testing.T) {
  3743  	defer afterTest(t)
  3744  
  3745  	mux := NewServeMux()
  3746  	mux.Handle("/", HandlerFunc(func(ResponseWriter, *Request) {}))
  3747  	ts := httptest.NewServer(mux)
  3748  	defer ts.Close()
  3749  
  3750  	// net/http uses HTTP/1.1 for requests, so write requests manually
  3751  	tests := []struct {
  3752  		req    string   // raw http request
  3753  		expect []string // expected Connection header(s)
  3754  	}{
  3755  		{
  3756  			req:    "GET / HTTP/1.0\r\n\r\n",
  3757  			expect: nil,
  3758  		},
  3759  		{
  3760  			req:    "OPTIONS * HTTP/1.0\r\n\r\n",
  3761  			expect: nil,
  3762  		},
  3763  		{
  3764  			req:    "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n",
  3765  			expect: []string{"keep-alive"},
  3766  		},
  3767  	}
  3768  
  3769  	for _, tt := range tests {
  3770  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3771  		if err != nil {
  3772  			t.Fatal("dial err:", err)
  3773  		}
  3774  
  3775  		_, err = fmt.Fprint(conn, tt.req)
  3776  		if err != nil {
  3777  			t.Fatal("conn write err:", err)
  3778  		}
  3779  
  3780  		resp, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "GET"})
  3781  		if err != nil {
  3782  			t.Fatal("ReadResponse err:", err)
  3783  		}
  3784  		conn.Close()
  3785  		resp.Body.Close()
  3786  
  3787  		got := resp.Header["Connection"]
  3788  		if !reflect.DeepEqual(got, tt.expect) {
  3789  			t.Errorf("wrong Connection headers for request %q. Got %q expect %q", tt.req, got, tt.expect)
  3790  		}
  3791  	}
  3792  }
  3793  
  3794  // See golang.org/issue/5660
  3795  func TestServerReaderFromOrder_h1(t *testing.T) { testServerReaderFromOrder(t, h1Mode) }
  3796  func TestServerReaderFromOrder_h2(t *testing.T) { testServerReaderFromOrder(t, h2Mode) }
  3797  func testServerReaderFromOrder(t *testing.T, h2 bool) {
  3798  	setParallel(t)
  3799  	defer afterTest(t)
  3800  	pr, pw := io.Pipe()
  3801  	const size = 3 << 20
  3802  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3803  		rw.Header().Set("Content-Type", "text/plain") // prevent sniffing path
  3804  		done := make(chan bool)
  3805  		go func() {
  3806  			io.Copy(rw, pr)
  3807  			close(done)
  3808  		}()
  3809  		time.Sleep(25 * time.Millisecond) // give Copy a chance to break things
  3810  		n, err := io.Copy(ioutil.Discard, req.Body)
  3811  		if err != nil {
  3812  			t.Errorf("handler Copy: %v", err)
  3813  			return
  3814  		}
  3815  		if n != size {
  3816  			t.Errorf("handler Copy = %d; want %d", n, size)
  3817  		}
  3818  		pw.Write([]byte("hi"))
  3819  		pw.Close()
  3820  		<-done
  3821  	}))
  3822  	defer cst.close()
  3823  
  3824  	req, err := NewRequest("POST", cst.ts.URL, io.LimitReader(neverEnding('a'), size))
  3825  	if err != nil {
  3826  		t.Fatal(err)
  3827  	}
  3828  	res, err := cst.c.Do(req)
  3829  	if err != nil {
  3830  		t.Fatal(err)
  3831  	}
  3832  	all, err := ioutil.ReadAll(res.Body)
  3833  	if err != nil {
  3834  		t.Fatal(err)
  3835  	}
  3836  	res.Body.Close()
  3837  	if string(all) != "hi" {
  3838  		t.Errorf("Body = %q; want hi", all)
  3839  	}
  3840  }
  3841  
  3842  // Issue 6157, Issue 6685
  3843  func TestCodesPreventingContentTypeAndBody(t *testing.T) {
  3844  	for _, code := range []int{StatusNotModified, StatusNoContent, StatusContinue} {
  3845  		ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  3846  			if r.URL.Path == "/header" {
  3847  				w.Header().Set("Content-Length", "123")
  3848  			}
  3849  			w.WriteHeader(code)
  3850  			if r.URL.Path == "/more" {
  3851  				w.Write([]byte("stuff"))
  3852  			}
  3853  		}))
  3854  		for _, req := range []string{
  3855  			"GET / HTTP/1.0",
  3856  			"GET /header HTTP/1.0",
  3857  			"GET /more HTTP/1.0",
  3858  			"GET / HTTP/1.1\nHost: foo",
  3859  			"GET /header HTTP/1.1\nHost: foo",
  3860  			"GET /more HTTP/1.1\nHost: foo",
  3861  		} {
  3862  			got := ht.rawResponse(req)
  3863  			wantStatus := fmt.Sprintf("%d %s", code, StatusText(code))
  3864  			if !strings.Contains(got, wantStatus) {
  3865  				t.Errorf("Code %d: Wanted %q Modified for %q: %s", code, wantStatus, req, got)
  3866  			} else if strings.Contains(got, "Content-Length") {
  3867  				t.Errorf("Code %d: Got a Content-Length from %q: %s", code, req, got)
  3868  			} else if strings.Contains(got, "stuff") {
  3869  				t.Errorf("Code %d: Response contains a body from %q: %s", code, req, got)
  3870  			}
  3871  		}
  3872  	}
  3873  }
  3874  
  3875  func TestContentTypeOkayOn204(t *testing.T) {
  3876  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  3877  		w.Header().Set("Content-Length", "123") // suppressed
  3878  		w.Header().Set("Content-Type", "foo/bar")
  3879  		w.WriteHeader(204)
  3880  	}))
  3881  	got := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  3882  	if !strings.Contains(got, "Content-Type: foo/bar") {
  3883  		t.Errorf("Response = %q; want Content-Type: foo/bar", got)
  3884  	}
  3885  	if strings.Contains(got, "Content-Length: 123") {
  3886  		t.Errorf("Response = %q; don't want a Content-Length", got)
  3887  	}
  3888  }
  3889  
  3890  // Issue 6995
  3891  // A server Handler can receive a Request, and then turn around and
  3892  // give a copy of that Request.Body out to the Transport (e.g. any
  3893  // proxy).  So then two people own that Request.Body (both the server
  3894  // and the http client), and both think they can close it on failure.
  3895  // Therefore, all incoming server requests Bodies need to be thread-safe.
  3896  func TestTransportAndServerSharedBodyRace_h1(t *testing.T) {
  3897  	testTransportAndServerSharedBodyRace(t, h1Mode)
  3898  }
  3899  func TestTransportAndServerSharedBodyRace_h2(t *testing.T) {
  3900  	testTransportAndServerSharedBodyRace(t, h2Mode)
  3901  }
  3902  func testTransportAndServerSharedBodyRace(t *testing.T, h2 bool) {
  3903  	setParallel(t)
  3904  	defer afterTest(t)
  3905  
  3906  	const bodySize = 1 << 20
  3907  
  3908  	// errorf is like t.Errorf, but also writes to println. When
  3909  	// this test fails, it hangs. This helps debugging and I've
  3910  	// added this enough times "temporarily".  It now gets added
  3911  	// full time.
  3912  	errorf := func(format string, args ...interface{}) {
  3913  		v := fmt.Sprintf(format, args...)
  3914  		println(v)
  3915  		t.Error(v)
  3916  	}
  3917  
  3918  	unblockBackend := make(chan bool)
  3919  	backend := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3920  		gone := rw.(CloseNotifier).CloseNotify()
  3921  		didCopy := make(chan interface{})
  3922  		go func() {
  3923  			n, err := io.CopyN(rw, req.Body, bodySize)
  3924  			didCopy <- []interface{}{n, err}
  3925  		}()
  3926  		isGone := false
  3927  	Loop:
  3928  		for {
  3929  			select {
  3930  			case <-didCopy:
  3931  				break Loop
  3932  			case <-gone:
  3933  				isGone = true
  3934  			case <-time.After(time.Second):
  3935  				println("1 second passes in backend, proxygone=", isGone)
  3936  			}
  3937  		}
  3938  		<-unblockBackend
  3939  	}))
  3940  	var quitTimer *time.Timer
  3941  	defer func() { quitTimer.Stop() }()
  3942  	defer backend.close()
  3943  
  3944  	backendRespc := make(chan *Response, 1)
  3945  	var proxy *clientServerTest
  3946  	proxy = newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3947  		req2, _ := NewRequest("POST", backend.ts.URL, req.Body)
  3948  		req2.ContentLength = bodySize
  3949  		cancel := make(chan struct{})
  3950  		req2.Cancel = cancel
  3951  
  3952  		bresp, err := proxy.c.Do(req2)
  3953  		if err != nil {
  3954  			errorf("Proxy outbound request: %v", err)
  3955  			return
  3956  		}
  3957  		_, err = io.CopyN(ioutil.Discard, bresp.Body, bodySize/2)
  3958  		if err != nil {
  3959  			errorf("Proxy copy error: %v", err)
  3960  			return
  3961  		}
  3962  		backendRespc <- bresp // to close later
  3963  
  3964  		// Try to cause a race: Both the Transport and the proxy handler's Server
  3965  		// will try to read/close req.Body (aka req2.Body)
  3966  		if h2 {
  3967  			close(cancel)
  3968  		} else {
  3969  			proxy.c.Transport.(*Transport).CancelRequest(req2)
  3970  		}
  3971  		rw.Write([]byte("OK"))
  3972  	}))
  3973  	defer proxy.close()
  3974  	defer func() {
  3975  		// Before we shut down our two httptest.Servers, start a timer.
  3976  		// We choose 7 seconds because httptest.Server starts logging
  3977  		// warnings to stderr at 5 seconds. If we don't disarm this bomb
  3978  		// in 7 seconds (after the two httptest.Server.Close calls above),
  3979  		// then we explode with stacks.
  3980  		quitTimer = time.AfterFunc(7*time.Second, func() {
  3981  			debug.SetTraceback("ALL")
  3982  			stacks := make([]byte, 1<<20)
  3983  			stacks = stacks[:runtime.Stack(stacks, true)]
  3984  			fmt.Fprintf(os.Stderr, "%s", stacks)
  3985  			log.Fatalf("Timeout.")
  3986  		})
  3987  	}()
  3988  
  3989  	defer close(unblockBackend)
  3990  	req, _ := NewRequest("POST", proxy.ts.URL, io.LimitReader(neverEnding('a'), bodySize))
  3991  	res, err := proxy.c.Do(req)
  3992  	if err != nil {
  3993  		t.Fatalf("Original request: %v", err)
  3994  	}
  3995  
  3996  	// Cleanup, so we don't leak goroutines.
  3997  	res.Body.Close()
  3998  	select {
  3999  	case res := <-backendRespc:
  4000  		res.Body.Close()
  4001  	default:
  4002  		// We failed earlier. (e.g. on proxy.c.Do(req2))
  4003  	}
  4004  }
  4005  
  4006  // Test that a hanging Request.Body.Read from another goroutine can't
  4007  // cause the Handler goroutine's Request.Body.Close to block.
  4008  // See issue 7121.
  4009  func TestRequestBodyCloseDoesntBlock(t *testing.T) {
  4010  	if testing.Short() {
  4011  		t.Skip("skipping in -short mode")
  4012  	}
  4013  	defer afterTest(t)
  4014  
  4015  	readErrCh := make(chan error, 1)
  4016  	errCh := make(chan error, 2)
  4017  
  4018  	server := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  4019  		go func(body io.Reader) {
  4020  			_, err := body.Read(make([]byte, 100))
  4021  			readErrCh <- err
  4022  		}(req.Body)
  4023  		time.Sleep(500 * time.Millisecond)
  4024  	}))
  4025  	defer server.Close()
  4026  
  4027  	closeConn := make(chan bool)
  4028  	defer close(closeConn)
  4029  	go func() {
  4030  		conn, err := net.Dial("tcp", server.Listener.Addr().String())
  4031  		if err != nil {
  4032  			errCh <- err
  4033  			return
  4034  		}
  4035  		defer conn.Close()
  4036  		_, err = conn.Write([]byte("POST / HTTP/1.1\r\nConnection: close\r\nHost: foo\r\nContent-Length: 100000\r\n\r\n"))
  4037  		if err != nil {
  4038  			errCh <- err
  4039  			return
  4040  		}
  4041  		// And now just block, making the server block on our
  4042  		// 100000 bytes of body that will never arrive.
  4043  		<-closeConn
  4044  	}()
  4045  	select {
  4046  	case err := <-readErrCh:
  4047  		if err == nil {
  4048  			t.Error("Read was nil. Expected error.")
  4049  		}
  4050  	case err := <-errCh:
  4051  		t.Error(err)
  4052  	case <-time.After(5 * time.Second):
  4053  		t.Error("timeout")
  4054  	}
  4055  }
  4056  
  4057  // test that ResponseWriter implements io.StringWriter.
  4058  func TestResponseWriterWriteString(t *testing.T) {
  4059  	okc := make(chan bool, 1)
  4060  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4061  		_, ok := w.(io.StringWriter)
  4062  		okc <- ok
  4063  	}))
  4064  	ht.rawResponse("GET / HTTP/1.0")
  4065  	select {
  4066  	case ok := <-okc:
  4067  		if !ok {
  4068  			t.Error("ResponseWriter did not implement io.StringWriter")
  4069  		}
  4070  	default:
  4071  		t.Error("handler was never called")
  4072  	}
  4073  }
  4074  
  4075  func TestAppendTime(t *testing.T) {
  4076  	var b [len(TimeFormat)]byte
  4077  	t1 := time.Date(2013, 9, 21, 15, 41, 0, 0, time.FixedZone("CEST", 2*60*60))
  4078  	res := ExportAppendTime(b[:0], t1)
  4079  	t2, err := ParseTime(string(res))
  4080  	if err != nil {
  4081  		t.Fatalf("Error parsing time: %s", err)
  4082  	}
  4083  	if !t1.Equal(t2) {
  4084  		t.Fatalf("Times differ; expected: %v, got %v (%s)", t1, t2, string(res))
  4085  	}
  4086  }
  4087  
  4088  func TestServerConnState(t *testing.T) {
  4089  	setParallel(t)
  4090  	defer afterTest(t)
  4091  	handler := map[string]func(w ResponseWriter, r *Request){
  4092  		"/": func(w ResponseWriter, r *Request) {
  4093  			fmt.Fprintf(w, "Hello.")
  4094  		},
  4095  		"/close": func(w ResponseWriter, r *Request) {
  4096  			w.Header().Set("Connection", "close")
  4097  			fmt.Fprintf(w, "Hello.")
  4098  		},
  4099  		"/hijack": func(w ResponseWriter, r *Request) {
  4100  			c, _, _ := w.(Hijacker).Hijack()
  4101  			c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
  4102  			c.Close()
  4103  		},
  4104  		"/hijack-panic": func(w ResponseWriter, r *Request) {
  4105  			c, _, _ := w.(Hijacker).Hijack()
  4106  			c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
  4107  			c.Close()
  4108  			panic("intentional panic")
  4109  		},
  4110  	}
  4111  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4112  		handler[r.URL.Path](w, r)
  4113  	}))
  4114  	defer ts.Close()
  4115  
  4116  	var mu sync.Mutex // guard stateLog and connID
  4117  	var stateLog = map[int][]ConnState{}
  4118  	var connID = map[net.Conn]int{}
  4119  
  4120  	ts.Config.ErrorLog = log.New(ioutil.Discard, "", 0)
  4121  	ts.Config.ConnState = func(c net.Conn, state ConnState) {
  4122  		if c == nil {
  4123  			t.Errorf("nil conn seen in state %s", state)
  4124  			return
  4125  		}
  4126  		mu.Lock()
  4127  		defer mu.Unlock()
  4128  		id, ok := connID[c]
  4129  		if !ok {
  4130  			id = len(connID) + 1
  4131  			connID[c] = id
  4132  		}
  4133  		stateLog[id] = append(stateLog[id], state)
  4134  	}
  4135  	ts.Start()
  4136  
  4137  	c := ts.Client()
  4138  
  4139  	mustGet := func(url string, headers ...string) {
  4140  		req, err := NewRequest("GET", url, nil)
  4141  		if err != nil {
  4142  			t.Fatal(err)
  4143  		}
  4144  		for len(headers) > 0 {
  4145  			req.Header.Add(headers[0], headers[1])
  4146  			headers = headers[2:]
  4147  		}
  4148  		res, err := c.Do(req)
  4149  		if err != nil {
  4150  			t.Errorf("Error fetching %s: %v", url, err)
  4151  			return
  4152  		}
  4153  		_, err = ioutil.ReadAll(res.Body)
  4154  		defer res.Body.Close()
  4155  		if err != nil {
  4156  			t.Errorf("Error reading %s: %v", url, err)
  4157  		}
  4158  	}
  4159  
  4160  	mustGet(ts.URL + "/")
  4161  	mustGet(ts.URL + "/close")
  4162  
  4163  	mustGet(ts.URL + "/")
  4164  	mustGet(ts.URL+"/", "Connection", "close")
  4165  
  4166  	mustGet(ts.URL + "/hijack")
  4167  	mustGet(ts.URL + "/hijack-panic")
  4168  
  4169  	// New->Closed
  4170  	{
  4171  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4172  		if err != nil {
  4173  			t.Fatal(err)
  4174  		}
  4175  		c.Close()
  4176  	}
  4177  
  4178  	// New->Active->Closed
  4179  	{
  4180  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4181  		if err != nil {
  4182  			t.Fatal(err)
  4183  		}
  4184  		if _, err := io.WriteString(c, "BOGUS REQUEST\r\n\r\n"); err != nil {
  4185  			t.Fatal(err)
  4186  		}
  4187  		c.Read(make([]byte, 1)) // block until server hangs up on us
  4188  		c.Close()
  4189  	}
  4190  
  4191  	// New->Idle->Closed
  4192  	{
  4193  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4194  		if err != nil {
  4195  			t.Fatal(err)
  4196  		}
  4197  		if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
  4198  			t.Fatal(err)
  4199  		}
  4200  		res, err := ReadResponse(bufio.NewReader(c), nil)
  4201  		if err != nil {
  4202  			t.Fatal(err)
  4203  		}
  4204  		if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
  4205  			t.Fatal(err)
  4206  		}
  4207  		c.Close()
  4208  	}
  4209  
  4210  	want := map[int][]ConnState{
  4211  		1: {StateNew, StateActive, StateIdle, StateActive, StateClosed},
  4212  		2: {StateNew, StateActive, StateIdle, StateActive, StateClosed},
  4213  		3: {StateNew, StateActive, StateHijacked},
  4214  		4: {StateNew, StateActive, StateHijacked},
  4215  		5: {StateNew, StateClosed},
  4216  		6: {StateNew, StateActive, StateClosed},
  4217  		7: {StateNew, StateActive, StateIdle, StateClosed},
  4218  	}
  4219  	logString := func(m map[int][]ConnState) string {
  4220  		var b bytes.Buffer
  4221  		var keys []int
  4222  		for id := range m {
  4223  			keys = append(keys, id)
  4224  		}
  4225  		sort.Ints(keys)
  4226  		for _, id := range keys {
  4227  			fmt.Fprintf(&b, "Conn %d: ", id)
  4228  			for _, s := range m[id] {
  4229  				fmt.Fprintf(&b, "%s ", s)
  4230  			}
  4231  			b.WriteString("\n")
  4232  		}
  4233  		return b.String()
  4234  	}
  4235  
  4236  	for i := 0; i < 5; i++ {
  4237  		time.Sleep(time.Duration(i) * 50 * time.Millisecond)
  4238  		mu.Lock()
  4239  		match := reflect.DeepEqual(stateLog, want)
  4240  		mu.Unlock()
  4241  		if match {
  4242  			return
  4243  		}
  4244  	}
  4245  
  4246  	mu.Lock()
  4247  	t.Errorf("Unexpected events.\nGot log:\n%s\n   Want:\n%s\n", logString(stateLog), logString(want))
  4248  	mu.Unlock()
  4249  }
  4250  
  4251  func TestServerKeepAlivesEnabled(t *testing.T) {
  4252  	defer afterTest(t)
  4253  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  4254  	ts.Config.SetKeepAlivesEnabled(false)
  4255  	ts.Start()
  4256  	defer ts.Close()
  4257  	res, err := Get(ts.URL)
  4258  	if err != nil {
  4259  		t.Fatal(err)
  4260  	}
  4261  	defer res.Body.Close()
  4262  	if !res.Close {
  4263  		t.Errorf("Body.Close == false; want true")
  4264  	}
  4265  }
  4266  
  4267  // golang.org/issue/7856
  4268  func TestServerEmptyBodyRace_h1(t *testing.T) { testServerEmptyBodyRace(t, h1Mode) }
  4269  func TestServerEmptyBodyRace_h2(t *testing.T) { testServerEmptyBodyRace(t, h2Mode) }
  4270  func testServerEmptyBodyRace(t *testing.T, h2 bool) {
  4271  	setParallel(t)
  4272  	defer afterTest(t)
  4273  	var n int32
  4274  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  4275  		atomic.AddInt32(&n, 1)
  4276  	}))
  4277  	defer cst.close()
  4278  	var wg sync.WaitGroup
  4279  	const reqs = 20
  4280  	for i := 0; i < reqs; i++ {
  4281  		wg.Add(1)
  4282  		go func() {
  4283  			defer wg.Done()
  4284  			res, err := cst.c.Get(cst.ts.URL)
  4285  			if err != nil {
  4286  				t.Error(err)
  4287  				return
  4288  			}
  4289  			defer res.Body.Close()
  4290  			_, err = io.Copy(ioutil.Discard, res.Body)
  4291  			if err != nil {
  4292  				t.Error(err)
  4293  				return
  4294  			}
  4295  		}()
  4296  	}
  4297  	wg.Wait()
  4298  	if got := atomic.LoadInt32(&n); got != reqs {
  4299  		t.Errorf("handler ran %d times; want %d", got, reqs)
  4300  	}
  4301  }
  4302  
  4303  func TestServerConnStateNew(t *testing.T) {
  4304  	sawNew := false // if the test is buggy, we'll race on this variable.
  4305  	srv := &Server{
  4306  		ConnState: func(c net.Conn, state ConnState) {
  4307  			if state == StateNew {
  4308  				sawNew = true // testing that this write isn't racy
  4309  			}
  4310  		},
  4311  		Handler: HandlerFunc(func(w ResponseWriter, r *Request) {}), // irrelevant
  4312  	}
  4313  	srv.Serve(&oneConnListener{
  4314  		conn: &rwTestConn{
  4315  			Reader: strings.NewReader("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"),
  4316  			Writer: ioutil.Discard,
  4317  		},
  4318  	})
  4319  	if !sawNew { // testing that this read isn't racy
  4320  		t.Error("StateNew not seen")
  4321  	}
  4322  }
  4323  
  4324  type closeWriteTestConn struct {
  4325  	rwTestConn
  4326  	didCloseWrite bool
  4327  }
  4328  
  4329  func (c *closeWriteTestConn) CloseWrite() error {
  4330  	c.didCloseWrite = true
  4331  	return nil
  4332  }
  4333  
  4334  func TestCloseWrite(t *testing.T) {
  4335  	setParallel(t)
  4336  	var srv Server
  4337  	var testConn closeWriteTestConn
  4338  	c := ExportServerNewConn(&srv, &testConn)
  4339  	ExportCloseWriteAndWait(c)
  4340  	if !testConn.didCloseWrite {
  4341  		t.Error("didn't see CloseWrite call")
  4342  	}
  4343  }
  4344  
  4345  // This verifies that a handler can Flush and then Hijack.
  4346  //
  4347  // An similar test crashed once during development, but it was only
  4348  // testing this tangentially and temporarily until another TODO was
  4349  // fixed.
  4350  //
  4351  // So add an explicit test for this.
  4352  func TestServerFlushAndHijack(t *testing.T) {
  4353  	defer afterTest(t)
  4354  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4355  		io.WriteString(w, "Hello, ")
  4356  		w.(Flusher).Flush()
  4357  		conn, buf, _ := w.(Hijacker).Hijack()
  4358  		buf.WriteString("6\r\nworld!\r\n0\r\n\r\n")
  4359  		if err := buf.Flush(); err != nil {
  4360  			t.Error(err)
  4361  		}
  4362  		if err := conn.Close(); err != nil {
  4363  			t.Error(err)
  4364  		}
  4365  	}))
  4366  	defer ts.Close()
  4367  	res, err := Get(ts.URL)
  4368  	if err != nil {
  4369  		t.Fatal(err)
  4370  	}
  4371  	defer res.Body.Close()
  4372  	all, err := ioutil.ReadAll(res.Body)
  4373  	if err != nil {
  4374  		t.Fatal(err)
  4375  	}
  4376  	if want := "Hello, world!"; string(all) != want {
  4377  		t.Errorf("Got %q; want %q", all, want)
  4378  	}
  4379  }
  4380  
  4381  // golang.org/issue/8534 -- the Server shouldn't reuse a connection
  4382  // for keep-alive after it's seen any Write error (e.g. a timeout) on
  4383  // that net.Conn.
  4384  //
  4385  // To test, verify we don't timeout or see fewer unique client
  4386  // addresses (== unique connections) than requests.
  4387  func TestServerKeepAliveAfterWriteError(t *testing.T) {
  4388  	if testing.Short() {
  4389  		t.Skip("skipping in -short mode")
  4390  	}
  4391  	defer afterTest(t)
  4392  	const numReq = 3
  4393  	addrc := make(chan string, numReq)
  4394  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4395  		addrc <- r.RemoteAddr
  4396  		time.Sleep(500 * time.Millisecond)
  4397  		w.(Flusher).Flush()
  4398  	}))
  4399  	ts.Config.WriteTimeout = 250 * time.Millisecond
  4400  	ts.Start()
  4401  	defer ts.Close()
  4402  
  4403  	errc := make(chan error, numReq)
  4404  	go func() {
  4405  		defer close(errc)
  4406  		for i := 0; i < numReq; i++ {
  4407  			res, err := Get(ts.URL)
  4408  			if res != nil {
  4409  				res.Body.Close()
  4410  			}
  4411  			errc <- err
  4412  		}
  4413  	}()
  4414  
  4415  	timeout := time.NewTimer(numReq * 2 * time.Second) // 4x overkill
  4416  	defer timeout.Stop()
  4417  	addrSeen := map[string]bool{}
  4418  	numOkay := 0
  4419  	for {
  4420  		select {
  4421  		case v := <-addrc:
  4422  			addrSeen[v] = true
  4423  		case err, ok := <-errc:
  4424  			if !ok {
  4425  				if len(addrSeen) != numReq {
  4426  					t.Errorf("saw %d unique client addresses; want %d", len(addrSeen), numReq)
  4427  				}
  4428  				if numOkay != 0 {
  4429  					t.Errorf("got %d successful client requests; want 0", numOkay)
  4430  				}
  4431  				return
  4432  			}
  4433  			if err == nil {
  4434  				numOkay++
  4435  			}
  4436  		case <-timeout.C:
  4437  			t.Fatal("timeout waiting for requests to complete")
  4438  		}
  4439  	}
  4440  }
  4441  
  4442  // Issue 9987: shouldn't add automatic Content-Length (or
  4443  // Content-Type) if a Transfer-Encoding was set by the handler.
  4444  func TestNoContentLengthIfTransferEncoding(t *testing.T) {
  4445  	defer afterTest(t)
  4446  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4447  		w.Header().Set("Transfer-Encoding", "foo")
  4448  		io.WriteString(w, "<html>")
  4449  	}))
  4450  	defer ts.Close()
  4451  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4452  	if err != nil {
  4453  		t.Fatalf("Dial: %v", err)
  4454  	}
  4455  	defer c.Close()
  4456  	if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
  4457  		t.Fatal(err)
  4458  	}
  4459  	bs := bufio.NewScanner(c)
  4460  	var got bytes.Buffer
  4461  	for bs.Scan() {
  4462  		if strings.TrimSpace(bs.Text()) == "" {
  4463  			break
  4464  		}
  4465  		got.WriteString(bs.Text())
  4466  		got.WriteByte('\n')
  4467  	}
  4468  	if err := bs.Err(); err != nil {
  4469  		t.Fatal(err)
  4470  	}
  4471  	if strings.Contains(got.String(), "Content-Length") {
  4472  		t.Errorf("Unexpected Content-Length in response headers: %s", got.String())
  4473  	}
  4474  	if strings.Contains(got.String(), "Content-Type") {
  4475  		t.Errorf("Unexpected Content-Type in response headers: %s", got.String())
  4476  	}
  4477  }
  4478  
  4479  // tolerate extra CRLF(s) before Request-Line on subsequent requests on a conn
  4480  // Issue 10876.
  4481  func TestTolerateCRLFBeforeRequestLine(t *testing.T) {
  4482  	req := []byte("POST / HTTP/1.1\r\nHost: golang.org\r\nContent-Length: 3\r\n\r\nABC" +
  4483  		"\r\n\r\n" + // <-- this stuff is bogus, but we'll ignore it
  4484  		"GET / HTTP/1.1\r\nHost: golang.org\r\n\r\n")
  4485  	var buf bytes.Buffer
  4486  	conn := &rwTestConn{
  4487  		Reader: bytes.NewReader(req),
  4488  		Writer: &buf,
  4489  		closec: make(chan bool, 1),
  4490  	}
  4491  	ln := &oneConnListener{conn: conn}
  4492  	numReq := 0
  4493  	go Serve(ln, HandlerFunc(func(rw ResponseWriter, r *Request) {
  4494  		numReq++
  4495  	}))
  4496  	<-conn.closec
  4497  	if numReq != 2 {
  4498  		t.Errorf("num requests = %d; want 2", numReq)
  4499  		t.Logf("Res: %s", buf.Bytes())
  4500  	}
  4501  }
  4502  
  4503  func TestIssue13893_Expect100(t *testing.T) {
  4504  	// test that the Server doesn't filter out Expect headers.
  4505  	req := reqBytes(`PUT /readbody HTTP/1.1
  4506  User-Agent: PycURL/7.22.0
  4507  Host: 127.0.0.1:9000
  4508  Accept: */*
  4509  Expect: 100-continue
  4510  Content-Length: 10
  4511  
  4512  HelloWorld
  4513  
  4514  `)
  4515  	var buf bytes.Buffer
  4516  	conn := &rwTestConn{
  4517  		Reader: bytes.NewReader(req),
  4518  		Writer: &buf,
  4519  		closec: make(chan bool, 1),
  4520  	}
  4521  	ln := &oneConnListener{conn: conn}
  4522  	go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
  4523  		if _, ok := r.Header["Expect"]; !ok {
  4524  			t.Error("Expect header should not be filtered out")
  4525  		}
  4526  	}))
  4527  	<-conn.closec
  4528  }
  4529  
  4530  func TestIssue11549_Expect100(t *testing.T) {
  4531  	req := reqBytes(`PUT /readbody HTTP/1.1
  4532  User-Agent: PycURL/7.22.0
  4533  Host: 127.0.0.1:9000
  4534  Accept: */*
  4535  Expect: 100-continue
  4536  Content-Length: 10
  4537  
  4538  HelloWorldPUT /noreadbody HTTP/1.1
  4539  User-Agent: PycURL/7.22.0
  4540  Host: 127.0.0.1:9000
  4541  Accept: */*
  4542  Expect: 100-continue
  4543  Content-Length: 10
  4544  
  4545  GET /should-be-ignored HTTP/1.1
  4546  Host: foo
  4547  
  4548  `)
  4549  	var buf bytes.Buffer
  4550  	conn := &rwTestConn{
  4551  		Reader: bytes.NewReader(req),
  4552  		Writer: &buf,
  4553  		closec: make(chan bool, 1),
  4554  	}
  4555  	ln := &oneConnListener{conn: conn}
  4556  	numReq := 0
  4557  	go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
  4558  		numReq++
  4559  		if r.URL.Path == "/readbody" {
  4560  			ioutil.ReadAll(r.Body)
  4561  		}
  4562  		io.WriteString(w, "Hello world!")
  4563  	}))
  4564  	<-conn.closec
  4565  	if numReq != 2 {
  4566  		t.Errorf("num requests = %d; want 2", numReq)
  4567  	}
  4568  	if !strings.Contains(buf.String(), "Connection: close\r\n") {
  4569  		t.Errorf("expected 'Connection: close' in response; got: %s", buf.String())
  4570  	}
  4571  }
  4572  
  4573  // If a Handler finishes and there's an unread request body,
  4574  // verify the server try to do implicit read on it before replying.
  4575  func TestHandlerFinishSkipBigContentLengthRead(t *testing.T) {
  4576  	setParallel(t)
  4577  	conn := &testConn{closec: make(chan bool)}
  4578  	conn.readBuf.Write([]byte(fmt.Sprintf(
  4579  		"POST / HTTP/1.1\r\n" +
  4580  			"Host: test\r\n" +
  4581  			"Content-Length: 9999999999\r\n" +
  4582  			"\r\n" + strings.Repeat("a", 1<<20))))
  4583  
  4584  	ls := &oneConnListener{conn}
  4585  	var inHandlerLen int
  4586  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  4587  		inHandlerLen = conn.readBuf.Len()
  4588  		rw.WriteHeader(404)
  4589  	}))
  4590  	<-conn.closec
  4591  	afterHandlerLen := conn.readBuf.Len()
  4592  
  4593  	if afterHandlerLen != inHandlerLen {
  4594  		t.Errorf("unexpected implicit read. Read buffer went from %d -> %d", inHandlerLen, afterHandlerLen)
  4595  	}
  4596  }
  4597  
  4598  func TestHandlerSetsBodyNil_h1(t *testing.T) { testHandlerSetsBodyNil(t, h1Mode) }
  4599  func TestHandlerSetsBodyNil_h2(t *testing.T) { testHandlerSetsBodyNil(t, h2Mode) }
  4600  func testHandlerSetsBodyNil(t *testing.T, h2 bool) {
  4601  	defer afterTest(t)
  4602  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4603  		r.Body = nil
  4604  		fmt.Fprintf(w, "%v", r.RemoteAddr)
  4605  	}))
  4606  	defer cst.close()
  4607  	get := func() string {
  4608  		res, err := cst.c.Get(cst.ts.URL)
  4609  		if err != nil {
  4610  			t.Fatal(err)
  4611  		}
  4612  		defer res.Body.Close()
  4613  		slurp, err := ioutil.ReadAll(res.Body)
  4614  		if err != nil {
  4615  			t.Fatal(err)
  4616  		}
  4617  		return string(slurp)
  4618  	}
  4619  	a, b := get(), get()
  4620  	if a != b {
  4621  		t.Errorf("Failed to reuse connections between requests: %v vs %v", a, b)
  4622  	}
  4623  }
  4624  
  4625  // Test that we validate the Host header.
  4626  // Issue 11206 (invalid bytes in Host) and 13624 (Host present in HTTP/1.1)
  4627  func TestServerValidatesHostHeader(t *testing.T) {
  4628  	tests := []struct {
  4629  		proto string
  4630  		host  string
  4631  		want  int
  4632  	}{
  4633  		{"HTTP/0.9", "", 400},
  4634  
  4635  		{"HTTP/1.1", "", 400},
  4636  		{"HTTP/1.1", "Host: \r\n", 200},
  4637  		{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
  4638  		{"HTTP/1.1", "Host: foo.com\r\n", 200},
  4639  		{"HTTP/1.1", "Host: foo-bar_baz.com\r\n", 200},
  4640  		{"HTTP/1.1", "Host: foo.com:80\r\n", 200},
  4641  		{"HTTP/1.1", "Host: ::1\r\n", 200},
  4642  		{"HTTP/1.1", "Host: [::1]\r\n", 200}, // questionable without port, but accept it
  4643  		{"HTTP/1.1", "Host: [::1]:80\r\n", 200},
  4644  		{"HTTP/1.1", "Host: [::1%25en0]:80\r\n", 200},
  4645  		{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
  4646  		{"HTTP/1.1", "Host: \x06\r\n", 400},
  4647  		{"HTTP/1.1", "Host: \xff\r\n", 400},
  4648  		{"HTTP/1.1", "Host: {\r\n", 400},
  4649  		{"HTTP/1.1", "Host: }\r\n", 400},
  4650  		{"HTTP/1.1", "Host: first\r\nHost: second\r\n", 400},
  4651  
  4652  		// HTTP/1.0 can lack a host header, but if present
  4653  		// must play by the rules too:
  4654  		{"HTTP/1.0", "", 200},
  4655  		{"HTTP/1.0", "Host: first\r\nHost: second\r\n", 400},
  4656  		{"HTTP/1.0", "Host: \xff\r\n", 400},
  4657  
  4658  		// Make an exception for HTTP upgrade requests:
  4659  		{"PRI * HTTP/2.0", "", 200},
  4660  
  4661  		// Also an exception for CONNECT requests: (Issue 18215)
  4662  		{"CONNECT golang.org:443 HTTP/1.1", "", 200},
  4663  
  4664  		// But not other HTTP/2 stuff:
  4665  		{"PRI / HTTP/2.0", "", 400},
  4666  		{"GET / HTTP/2.0", "", 400},
  4667  		{"GET / HTTP/3.0", "", 400},
  4668  	}
  4669  	for _, tt := range tests {
  4670  		conn := &testConn{closec: make(chan bool, 1)}
  4671  		methodTarget := "GET / "
  4672  		if !strings.HasPrefix(tt.proto, "HTTP/") {
  4673  			methodTarget = ""
  4674  		}
  4675  		io.WriteString(&conn.readBuf, methodTarget+tt.proto+"\r\n"+tt.host+"\r\n")
  4676  
  4677  		ln := &oneConnListener{conn}
  4678  		srv := Server{
  4679  			ErrorLog: quietLog,
  4680  			Handler:  HandlerFunc(func(ResponseWriter, *Request) {}),
  4681  		}
  4682  		go srv.Serve(ln)
  4683  		<-conn.closec
  4684  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  4685  		if err != nil {
  4686  			t.Errorf("For %s %q, ReadResponse: %v", tt.proto, tt.host, res)
  4687  			continue
  4688  		}
  4689  		if res.StatusCode != tt.want {
  4690  			t.Errorf("For %s %q, Status = %d; want %d", tt.proto, tt.host, res.StatusCode, tt.want)
  4691  		}
  4692  	}
  4693  }
  4694  
  4695  func TestServerHandlersCanHandleH2PRI(t *testing.T) {
  4696  	const upgradeResponse = "upgrade here"
  4697  	defer afterTest(t)
  4698  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4699  		conn, br, err := w.(Hijacker).Hijack()
  4700  		defer conn.Close()
  4701  		if r.Method != "PRI" || r.RequestURI != "*" {
  4702  			t.Errorf("Got method/target %q %q; want PRI *", r.Method, r.RequestURI)
  4703  			return
  4704  		}
  4705  		if !r.Close {
  4706  			t.Errorf("Request.Close = true; want false")
  4707  		}
  4708  		const want = "SM\r\n\r\n"
  4709  		buf := make([]byte, len(want))
  4710  		n, err := io.ReadFull(br, buf)
  4711  		if err != nil || string(buf[:n]) != want {
  4712  			t.Errorf("Read = %v, %v (%q), want %q", n, err, buf[:n], want)
  4713  			return
  4714  		}
  4715  		io.WriteString(conn, upgradeResponse)
  4716  	}))
  4717  	defer ts.Close()
  4718  
  4719  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4720  	if err != nil {
  4721  		t.Fatalf("Dial: %v", err)
  4722  	}
  4723  	defer c.Close()
  4724  	io.WriteString(c, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
  4725  	slurp, err := ioutil.ReadAll(c)
  4726  	if err != nil {
  4727  		t.Fatal(err)
  4728  	}
  4729  	if string(slurp) != upgradeResponse {
  4730  		t.Errorf("Handler response = %q; want %q", slurp, upgradeResponse)
  4731  	}
  4732  }
  4733  
  4734  // Test that we validate the valid bytes in HTTP/1 headers.
  4735  // Issue 11207.
  4736  func TestServerValidatesHeaders(t *testing.T) {
  4737  	setParallel(t)
  4738  	tests := []struct {
  4739  		header string
  4740  		want   int
  4741  	}{
  4742  		{"", 200},
  4743  		{"Foo: bar\r\n", 200},
  4744  		{"X-Foo: bar\r\n", 200},
  4745  		{"Foo: a space\r\n", 200},
  4746  
  4747  		{"A space: foo\r\n", 400},                            // space in header
  4748  		{"foo\xffbar: foo\r\n", 400},                         // binary in header
  4749  		{"foo\x00bar: foo\r\n", 400},                         // binary in header
  4750  		{"Foo: " + strings.Repeat("x", 1<<21) + "\r\n", 431}, // header too large
  4751  
  4752  		{"foo: foo foo\r\n", 200},    // LWS space is okay
  4753  		{"foo: foo\tfoo\r\n", 200},   // LWS tab is okay
  4754  		{"foo: foo\x00foo\r\n", 400}, // CTL 0x00 in value is bad
  4755  		{"foo: foo\x7ffoo\r\n", 400}, // CTL 0x7f in value is bad
  4756  		{"foo: foo\xfffoo\r\n", 200}, // non-ASCII high octets in value are fine
  4757  	}
  4758  	for _, tt := range tests {
  4759  		conn := &testConn{closec: make(chan bool, 1)}
  4760  		io.WriteString(&conn.readBuf, "GET / HTTP/1.1\r\nHost: foo\r\n"+tt.header+"\r\n")
  4761  
  4762  		ln := &oneConnListener{conn}
  4763  		srv := Server{
  4764  			ErrorLog: quietLog,
  4765  			Handler:  HandlerFunc(func(ResponseWriter, *Request) {}),
  4766  		}
  4767  		go srv.Serve(ln)
  4768  		<-conn.closec
  4769  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  4770  		if err != nil {
  4771  			t.Errorf("For %q, ReadResponse: %v", tt.header, res)
  4772  			continue
  4773  		}
  4774  		if res.StatusCode != tt.want {
  4775  			t.Errorf("For %q, Status = %d; want %d", tt.header, res.StatusCode, tt.want)
  4776  		}
  4777  	}
  4778  }
  4779  
  4780  func TestServerRequestContextCancel_ServeHTTPDone_h1(t *testing.T) {
  4781  	testServerRequestContextCancel_ServeHTTPDone(t, h1Mode)
  4782  }
  4783  func TestServerRequestContextCancel_ServeHTTPDone_h2(t *testing.T) {
  4784  	testServerRequestContextCancel_ServeHTTPDone(t, h2Mode)
  4785  }
  4786  func testServerRequestContextCancel_ServeHTTPDone(t *testing.T, h2 bool) {
  4787  	setParallel(t)
  4788  	defer afterTest(t)
  4789  	ctxc := make(chan context.Context, 1)
  4790  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4791  		ctx := r.Context()
  4792  		select {
  4793  		case <-ctx.Done():
  4794  			t.Error("should not be Done in ServeHTTP")
  4795  		default:
  4796  		}
  4797  		ctxc <- ctx
  4798  	}))
  4799  	defer cst.close()
  4800  	res, err := cst.c.Get(cst.ts.URL)
  4801  	if err != nil {
  4802  		t.Fatal(err)
  4803  	}
  4804  	res.Body.Close()
  4805  	ctx := <-ctxc
  4806  	select {
  4807  	case <-ctx.Done():
  4808  	default:
  4809  		t.Error("context should be done after ServeHTTP completes")
  4810  	}
  4811  }
  4812  
  4813  // Tests that the Request.Context available to the Handler is canceled
  4814  // if the peer closes their TCP connection. This requires that the server
  4815  // is always blocked in a Read call so it notices the EOF from the client.
  4816  // See issues 15927 and 15224.
  4817  func TestServerRequestContextCancel_ConnClose(t *testing.T) {
  4818  	setParallel(t)
  4819  	defer afterTest(t)
  4820  	inHandler := make(chan struct{})
  4821  	handlerDone := make(chan struct{})
  4822  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4823  		close(inHandler)
  4824  		select {
  4825  		case <-r.Context().Done():
  4826  		case <-time.After(3 * time.Second):
  4827  			t.Errorf("timeout waiting for context to be done")
  4828  		}
  4829  		close(handlerDone)
  4830  	}))
  4831  	defer ts.Close()
  4832  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4833  	if err != nil {
  4834  		t.Fatal(err)
  4835  	}
  4836  	defer c.Close()
  4837  	io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n")
  4838  	select {
  4839  	case <-inHandler:
  4840  	case <-time.After(3 * time.Second):
  4841  		t.Fatalf("timeout waiting to see ServeHTTP get called")
  4842  	}
  4843  	c.Close() // this should trigger the context being done
  4844  
  4845  	select {
  4846  	case <-handlerDone:
  4847  	case <-time.After(4 * time.Second):
  4848  		t.Fatalf("timeout waiting to see ServeHTTP exit")
  4849  	}
  4850  }
  4851  
  4852  func TestServerContext_ServerContextKey_h1(t *testing.T) {
  4853  	testServerContext_ServerContextKey(t, h1Mode)
  4854  }
  4855  func TestServerContext_ServerContextKey_h2(t *testing.T) {
  4856  	testServerContext_ServerContextKey(t, h2Mode)
  4857  }
  4858  func testServerContext_ServerContextKey(t *testing.T, h2 bool) {
  4859  	setParallel(t)
  4860  	defer afterTest(t)
  4861  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4862  		ctx := r.Context()
  4863  		got := ctx.Value(ServerContextKey)
  4864  		if _, ok := got.(*Server); !ok {
  4865  			t.Errorf("context value = %T; want *http.Server", got)
  4866  		}
  4867  	}))
  4868  	defer cst.close()
  4869  	res, err := cst.c.Get(cst.ts.URL)
  4870  	if err != nil {
  4871  		t.Fatal(err)
  4872  	}
  4873  	res.Body.Close()
  4874  }
  4875  
  4876  func TestServerContext_LocalAddrContextKey_h1(t *testing.T) {
  4877  	testServerContext_LocalAddrContextKey(t, h1Mode)
  4878  }
  4879  func TestServerContext_LocalAddrContextKey_h2(t *testing.T) {
  4880  	testServerContext_LocalAddrContextKey(t, h2Mode)
  4881  }
  4882  func testServerContext_LocalAddrContextKey(t *testing.T, h2 bool) {
  4883  	setParallel(t)
  4884  	defer afterTest(t)
  4885  	ch := make(chan interface{}, 1)
  4886  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4887  		ch <- r.Context().Value(LocalAddrContextKey)
  4888  	}))
  4889  	defer cst.close()
  4890  	if _, err := cst.c.Head(cst.ts.URL); err != nil {
  4891  		t.Fatal(err)
  4892  	}
  4893  
  4894  	host := cst.ts.Listener.Addr().String()
  4895  	select {
  4896  	case got := <-ch:
  4897  		if addr, ok := got.(net.Addr); !ok {
  4898  			t.Errorf("local addr value = %T; want net.Addr", got)
  4899  		} else if fmt.Sprint(addr) != host {
  4900  			t.Errorf("local addr = %v; want %v", addr, host)
  4901  		}
  4902  	case <-time.After(5 * time.Second):
  4903  		t.Error("timed out")
  4904  	}
  4905  }
  4906  
  4907  // https://golang.org/issue/15960
  4908  func TestHandlerSetTransferEncodingChunked(t *testing.T) {
  4909  	setParallel(t)
  4910  	defer afterTest(t)
  4911  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4912  		w.Header().Set("Transfer-Encoding", "chunked")
  4913  		w.Write([]byte("hello"))
  4914  	}))
  4915  	resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  4916  	const hdr = "Transfer-Encoding: chunked"
  4917  	if n := strings.Count(resp, hdr); n != 1 {
  4918  		t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
  4919  	}
  4920  }
  4921  
  4922  // https://golang.org/issue/16063
  4923  func TestHandlerSetTransferEncodingGzip(t *testing.T) {
  4924  	setParallel(t)
  4925  	defer afterTest(t)
  4926  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4927  		w.Header().Set("Transfer-Encoding", "gzip")
  4928  		gz := gzip.NewWriter(w)
  4929  		gz.Write([]byte("hello"))
  4930  		gz.Close()
  4931  	}))
  4932  	resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  4933  	for _, v := range []string{"gzip", "chunked"} {
  4934  		hdr := "Transfer-Encoding: " + v
  4935  		if n := strings.Count(resp, hdr); n != 1 {
  4936  			t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
  4937  		}
  4938  	}
  4939  }
  4940  
  4941  func BenchmarkClientServer(b *testing.B) {
  4942  	b.ReportAllocs()
  4943  	b.StopTimer()
  4944  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  4945  		fmt.Fprintf(rw, "Hello world.\n")
  4946  	}))
  4947  	defer ts.Close()
  4948  	b.StartTimer()
  4949  
  4950  	for i := 0; i < b.N; i++ {
  4951  		res, err := Get(ts.URL)
  4952  		if err != nil {
  4953  			b.Fatal("Get:", err)
  4954  		}
  4955  		all, err := ioutil.ReadAll(res.Body)
  4956  		res.Body.Close()
  4957  		if err != nil {
  4958  			b.Fatal("ReadAll:", err)
  4959  		}
  4960  		body := string(all)
  4961  		if body != "Hello world.\n" {
  4962  			b.Fatal("Got body:", body)
  4963  		}
  4964  	}
  4965  
  4966  	b.StopTimer()
  4967  }
  4968  
  4969  func BenchmarkClientServerParallel4(b *testing.B) {
  4970  	benchmarkClientServerParallel(b, 4, false)
  4971  }
  4972  
  4973  func BenchmarkClientServerParallel64(b *testing.B) {
  4974  	benchmarkClientServerParallel(b, 64, false)
  4975  }
  4976  
  4977  func BenchmarkClientServerParallelTLS4(b *testing.B) {
  4978  	benchmarkClientServerParallel(b, 4, true)
  4979  }
  4980  
  4981  func BenchmarkClientServerParallelTLS64(b *testing.B) {
  4982  	benchmarkClientServerParallel(b, 64, true)
  4983  }
  4984  
  4985  func benchmarkClientServerParallel(b *testing.B, parallelism int, useTLS bool) {
  4986  	b.ReportAllocs()
  4987  	ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  4988  		fmt.Fprintf(rw, "Hello world.\n")
  4989  	}))
  4990  	if useTLS {
  4991  		ts.StartTLS()
  4992  	} else {
  4993  		ts.Start()
  4994  	}
  4995  	defer ts.Close()
  4996  	b.ResetTimer()
  4997  	b.SetParallelism(parallelism)
  4998  	b.RunParallel(func(pb *testing.PB) {
  4999  		c := ts.Client()
  5000  		for pb.Next() {
  5001  			res, err := c.Get(ts.URL)
  5002  			if err != nil {
  5003  				b.Logf("Get: %v", err)
  5004  				continue
  5005  			}
  5006  			all, err := ioutil.ReadAll(res.Body)
  5007  			res.Body.Close()
  5008  			if err != nil {
  5009  				b.Logf("ReadAll: %v", err)
  5010  				continue
  5011  			}
  5012  			body := string(all)
  5013  			if body != "Hello world.\n" {
  5014  				panic("Got body: " + body)
  5015  			}
  5016  		}
  5017  	})
  5018  }
  5019  
  5020  // A benchmark for profiling the server without the HTTP client code.
  5021  // The client code runs in a subprocess.
  5022  //
  5023  // For use like:
  5024  //   $ go test -c
  5025  //   $ ./http.test -test.run=XX -test.bench=BenchmarkServer -test.benchtime=15s -test.cpuprofile=http.prof
  5026  //   $ go tool pprof http.test http.prof
  5027  //   (pprof) web
  5028  func BenchmarkServer(b *testing.B) {
  5029  	b.ReportAllocs()
  5030  	// Child process mode;
  5031  	if url := os.Getenv("TEST_BENCH_SERVER_URL"); url != "" {
  5032  		n, err := strconv.Atoi(os.Getenv("TEST_BENCH_CLIENT_N"))
  5033  		if err != nil {
  5034  			panic(err)
  5035  		}
  5036  		for i := 0; i < n; i++ {
  5037  			res, err := Get(url)
  5038  			if err != nil {
  5039  				log.Panicf("Get: %v", err)
  5040  			}
  5041  			all, err := ioutil.ReadAll(res.Body)
  5042  			res.Body.Close()
  5043  			if err != nil {
  5044  				log.Panicf("ReadAll: %v", err)
  5045  			}
  5046  			body := string(all)
  5047  			if body != "Hello world.\n" {
  5048  				log.Panicf("Got body: %q", body)
  5049  			}
  5050  		}
  5051  		os.Exit(0)
  5052  		return
  5053  	}
  5054  
  5055  	var res = []byte("Hello world.\n")
  5056  	b.StopTimer()
  5057  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  5058  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5059  		rw.Write(res)
  5060  	}))
  5061  	defer ts.Close()
  5062  	b.StartTimer()
  5063  
  5064  	cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkServer$")
  5065  	cmd.Env = append([]string{
  5066  		fmt.Sprintf("TEST_BENCH_CLIENT_N=%d", b.N),
  5067  		fmt.Sprintf("TEST_BENCH_SERVER_URL=%s", ts.URL),
  5068  	}, os.Environ()...)
  5069  	out, err := cmd.CombinedOutput()
  5070  	if err != nil {
  5071  		b.Errorf("Test failure: %v, with output: %s", err, out)
  5072  	}
  5073  }
  5074  
  5075  // getNoBody wraps Get but closes any Response.Body before returning the response.
  5076  func getNoBody(urlStr string) (*Response, error) {
  5077  	res, err := Get(urlStr)
  5078  	if err != nil {
  5079  		return nil, err
  5080  	}
  5081  	res.Body.Close()
  5082  	return res, nil
  5083  }
  5084  
  5085  // A benchmark for profiling the client without the HTTP server code.
  5086  // The server code runs in a subprocess.
  5087  func BenchmarkClient(b *testing.B) {
  5088  	b.ReportAllocs()
  5089  	b.StopTimer()
  5090  	defer afterTest(b)
  5091  
  5092  	var data = []byte("Hello world.\n")
  5093  	if server := os.Getenv("TEST_BENCH_SERVER"); server != "" {
  5094  		// Server process mode.
  5095  		port := os.Getenv("TEST_BENCH_SERVER_PORT") // can be set by user
  5096  		if port == "" {
  5097  			port = "0"
  5098  		}
  5099  		ln, err := net.Listen("tcp", "localhost:"+port)
  5100  		if err != nil {
  5101  			fmt.Fprintln(os.Stderr, err.Error())
  5102  			os.Exit(1)
  5103  		}
  5104  		fmt.Println(ln.Addr().String())
  5105  		HandleFunc("/", func(w ResponseWriter, r *Request) {
  5106  			r.ParseForm()
  5107  			if r.Form.Get("stop") != "" {
  5108  				os.Exit(0)
  5109  			}
  5110  			w.Header().Set("Content-Type", "text/html; charset=utf-8")
  5111  			w.Write(data)
  5112  		})
  5113  		var srv Server
  5114  		log.Fatal(srv.Serve(ln))
  5115  	}
  5116  
  5117  	// Start server process.
  5118  	cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkClient$")
  5119  	cmd.Env = append(os.Environ(), "TEST_BENCH_SERVER=yes")
  5120  	cmd.Stderr = os.Stderr
  5121  	stdout, err := cmd.StdoutPipe()
  5122  	if err != nil {
  5123  		b.Fatal(err)
  5124  	}
  5125  	if err := cmd.Start(); err != nil {
  5126  		b.Fatalf("subprocess failed to start: %v", err)
  5127  	}
  5128  	defer cmd.Process.Kill()
  5129  
  5130  	// Wait for the server in the child process to respond and tell us
  5131  	// its listening address, once it's started listening:
  5132  	timer := time.AfterFunc(10*time.Second, func() {
  5133  		cmd.Process.Kill()
  5134  	})
  5135  	defer timer.Stop()
  5136  	bs := bufio.NewScanner(stdout)
  5137  	if !bs.Scan() {
  5138  		b.Fatalf("failed to read listening URL from child: %v", bs.Err())
  5139  	}
  5140  	url := "http://" + strings.TrimSpace(bs.Text()) + "/"
  5141  	timer.Stop()
  5142  	if _, err := getNoBody(url); err != nil {
  5143  		b.Fatalf("initial probe of child process failed: %v", err)
  5144  	}
  5145  
  5146  	done := make(chan error)
  5147  	go func() {
  5148  		done <- cmd.Wait()
  5149  	}()
  5150  
  5151  	// Do b.N requests to the server.
  5152  	b.StartTimer()
  5153  	for i := 0; i < b.N; i++ {
  5154  		res, err := Get(url)
  5155  		if err != nil {
  5156  			b.Fatalf("Get: %v", err)
  5157  		}
  5158  		body, err := ioutil.ReadAll(res.Body)
  5159  		res.Body.Close()
  5160  		if err != nil {
  5161  			b.Fatalf("ReadAll: %v", err)
  5162  		}
  5163  		if !bytes.Equal(body, data) {
  5164  			b.Fatalf("Got body: %q", body)
  5165  		}
  5166  	}
  5167  	b.StopTimer()
  5168  
  5169  	// Instruct server process to stop.
  5170  	getNoBody(url + "?stop=yes")
  5171  	select {
  5172  	case err := <-done:
  5173  		if err != nil {
  5174  			b.Fatalf("subprocess failed: %v", err)
  5175  		}
  5176  	case <-time.After(5 * time.Second):
  5177  		b.Fatalf("subprocess did not stop")
  5178  	}
  5179  }
  5180  
  5181  func BenchmarkServerFakeConnNoKeepAlive(b *testing.B) {
  5182  	b.ReportAllocs()
  5183  	req := reqBytes(`GET / HTTP/1.0
  5184  Host: golang.org
  5185  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5186  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
  5187  Accept-Encoding: gzip,deflate,sdch
  5188  Accept-Language: en-US,en;q=0.8
  5189  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  5190  `)
  5191  	res := []byte("Hello world!\n")
  5192  
  5193  	conn := &testConn{
  5194  		// testConn.Close will not push into the channel
  5195  		// if it's full.
  5196  		closec: make(chan bool, 1),
  5197  	}
  5198  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5199  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5200  		rw.Write(res)
  5201  	})
  5202  	ln := new(oneConnListener)
  5203  	for i := 0; i < b.N; i++ {
  5204  		conn.readBuf.Reset()
  5205  		conn.writeBuf.Reset()
  5206  		conn.readBuf.Write(req)
  5207  		ln.conn = conn
  5208  		Serve(ln, handler)
  5209  		<-conn.closec
  5210  	}
  5211  }
  5212  
  5213  // repeatReader reads content count times, then EOFs.
  5214  type repeatReader struct {
  5215  	content []byte
  5216  	count   int
  5217  	off     int
  5218  }
  5219  
  5220  func (r *repeatReader) Read(p []byte) (n int, err error) {
  5221  	if r.count <= 0 {
  5222  		return 0, io.EOF
  5223  	}
  5224  	n = copy(p, r.content[r.off:])
  5225  	r.off += n
  5226  	if r.off == len(r.content) {
  5227  		r.count--
  5228  		r.off = 0
  5229  	}
  5230  	return
  5231  }
  5232  
  5233  func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) {
  5234  	b.ReportAllocs()
  5235  
  5236  	req := reqBytes(`GET / HTTP/1.1
  5237  Host: golang.org
  5238  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5239  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
  5240  Accept-Encoding: gzip,deflate,sdch
  5241  Accept-Language: en-US,en;q=0.8
  5242  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  5243  `)
  5244  	res := []byte("Hello world!\n")
  5245  
  5246  	conn := &rwTestConn{
  5247  		Reader: &repeatReader{content: req, count: b.N},
  5248  		Writer: ioutil.Discard,
  5249  		closec: make(chan bool, 1),
  5250  	}
  5251  	handled := 0
  5252  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5253  		handled++
  5254  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5255  		rw.Write(res)
  5256  	})
  5257  	ln := &oneConnListener{conn: conn}
  5258  	go Serve(ln, handler)
  5259  	<-conn.closec
  5260  	if b.N != handled {
  5261  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5262  	}
  5263  }
  5264  
  5265  // same as above, but representing the most simple possible request
  5266  // and handler. Notably: the handler does not call rw.Header().
  5267  func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) {
  5268  	b.ReportAllocs()
  5269  
  5270  	req := reqBytes(`GET / HTTP/1.1
  5271  Host: golang.org
  5272  `)
  5273  	res := []byte("Hello world!\n")
  5274  
  5275  	conn := &rwTestConn{
  5276  		Reader: &repeatReader{content: req, count: b.N},
  5277  		Writer: ioutil.Discard,
  5278  		closec: make(chan bool, 1),
  5279  	}
  5280  	handled := 0
  5281  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5282  		handled++
  5283  		rw.Write(res)
  5284  	})
  5285  	ln := &oneConnListener{conn: conn}
  5286  	go Serve(ln, handler)
  5287  	<-conn.closec
  5288  	if b.N != handled {
  5289  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5290  	}
  5291  }
  5292  
  5293  const someResponse = "<html>some response</html>"
  5294  
  5295  // A Response that's just no bigger than 2KB, the buffer-before-chunking threshold.
  5296  var response = bytes.Repeat([]byte(someResponse), 2<<10/len(someResponse))
  5297  
  5298  // Both Content-Type and Content-Length set. Should be no buffering.
  5299  func BenchmarkServerHandlerTypeLen(b *testing.B) {
  5300  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5301  		w.Header().Set("Content-Type", "text/html")
  5302  		w.Header().Set("Content-Length", strconv.Itoa(len(response)))
  5303  		w.Write(response)
  5304  	}))
  5305  }
  5306  
  5307  // A Content-Type is set, but no length. No sniffing, but will count the Content-Length.
  5308  func BenchmarkServerHandlerNoLen(b *testing.B) {
  5309  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5310  		w.Header().Set("Content-Type", "text/html")
  5311  		w.Write(response)
  5312  	}))
  5313  }
  5314  
  5315  // A Content-Length is set, but the Content-Type will be sniffed.
  5316  func BenchmarkServerHandlerNoType(b *testing.B) {
  5317  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5318  		w.Header().Set("Content-Length", strconv.Itoa(len(response)))
  5319  		w.Write(response)
  5320  	}))
  5321  }
  5322  
  5323  // Neither a Content-Type or Content-Length, so sniffed and counted.
  5324  func BenchmarkServerHandlerNoHeader(b *testing.B) {
  5325  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5326  		w.Write(response)
  5327  	}))
  5328  }
  5329  
  5330  func benchmarkHandler(b *testing.B, h Handler) {
  5331  	b.ReportAllocs()
  5332  	req := reqBytes(`GET / HTTP/1.1
  5333  Host: golang.org
  5334  `)
  5335  	conn := &rwTestConn{
  5336  		Reader: &repeatReader{content: req, count: b.N},
  5337  		Writer: ioutil.Discard,
  5338  		closec: make(chan bool, 1),
  5339  	}
  5340  	handled := 0
  5341  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5342  		handled++
  5343  		h.ServeHTTP(rw, r)
  5344  	})
  5345  	ln := &oneConnListener{conn: conn}
  5346  	go Serve(ln, handler)
  5347  	<-conn.closec
  5348  	if b.N != handled {
  5349  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5350  	}
  5351  }
  5352  
  5353  func BenchmarkServerHijack(b *testing.B) {
  5354  	b.ReportAllocs()
  5355  	req := reqBytes(`GET / HTTP/1.1
  5356  Host: golang.org
  5357  `)
  5358  	h := HandlerFunc(func(w ResponseWriter, r *Request) {
  5359  		conn, _, err := w.(Hijacker).Hijack()
  5360  		if err != nil {
  5361  			panic(err)
  5362  		}
  5363  		conn.Close()
  5364  	})
  5365  	conn := &rwTestConn{
  5366  		Writer: ioutil.Discard,
  5367  		closec: make(chan bool, 1),
  5368  	}
  5369  	ln := &oneConnListener{conn: conn}
  5370  	for i := 0; i < b.N; i++ {
  5371  		conn.Reader = bytes.NewReader(req)
  5372  		ln.conn = conn
  5373  		Serve(ln, h)
  5374  		<-conn.closec
  5375  	}
  5376  }
  5377  
  5378  func BenchmarkCloseNotifier(b *testing.B) {
  5379  	b.ReportAllocs()
  5380  	b.StopTimer()
  5381  	sawClose := make(chan bool)
  5382  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  5383  		<-rw.(CloseNotifier).CloseNotify()
  5384  		sawClose <- true
  5385  	}))
  5386  	defer ts.Close()
  5387  	tot := time.NewTimer(5 * time.Second)
  5388  	defer tot.Stop()
  5389  	b.StartTimer()
  5390  	for i := 0; i < b.N; i++ {
  5391  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5392  		if err != nil {
  5393  			b.Fatalf("error dialing: %v", err)
  5394  		}
  5395  		_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
  5396  		if err != nil {
  5397  			b.Fatal(err)
  5398  		}
  5399  		conn.Close()
  5400  		tot.Reset(5 * time.Second)
  5401  		select {
  5402  		case <-sawClose:
  5403  		case <-tot.C:
  5404  			b.Fatal("timeout")
  5405  		}
  5406  	}
  5407  	b.StopTimer()
  5408  }
  5409  
  5410  // Verify this doesn't race (Issue 16505)
  5411  func TestConcurrentServerServe(t *testing.T) {
  5412  	setParallel(t)
  5413  	for i := 0; i < 100; i++ {
  5414  		ln1 := &oneConnListener{conn: nil}
  5415  		ln2 := &oneConnListener{conn: nil}
  5416  		srv := Server{}
  5417  		go func() { srv.Serve(ln1) }()
  5418  		go func() { srv.Serve(ln2) }()
  5419  	}
  5420  }
  5421  
  5422  func TestServerIdleTimeout(t *testing.T) {
  5423  	if testing.Short() {
  5424  		t.Skip("skipping in short mode")
  5425  	}
  5426  	setParallel(t)
  5427  	defer afterTest(t)
  5428  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5429  		io.Copy(ioutil.Discard, r.Body)
  5430  		io.WriteString(w, r.RemoteAddr)
  5431  	}))
  5432  	ts.Config.ReadHeaderTimeout = 1 * time.Second
  5433  	ts.Config.IdleTimeout = 2 * time.Second
  5434  	ts.Start()
  5435  	defer ts.Close()
  5436  	c := ts.Client()
  5437  
  5438  	get := func() string {
  5439  		res, err := c.Get(ts.URL)
  5440  		if err != nil {
  5441  			t.Fatal(err)
  5442  		}
  5443  		defer res.Body.Close()
  5444  		slurp, err := ioutil.ReadAll(res.Body)
  5445  		if err != nil {
  5446  			t.Fatal(err)
  5447  		}
  5448  		return string(slurp)
  5449  	}
  5450  
  5451  	a1, a2 := get(), get()
  5452  	if a1 != a2 {
  5453  		t.Fatalf("did requests on different connections")
  5454  	}
  5455  	time.Sleep(3 * time.Second)
  5456  	a3 := get()
  5457  	if a2 == a3 {
  5458  		t.Fatal("request three unexpectedly on same connection")
  5459  	}
  5460  
  5461  	// And test that ReadHeaderTimeout still works:
  5462  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5463  	if err != nil {
  5464  		t.Fatal(err)
  5465  	}
  5466  	defer conn.Close()
  5467  	conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo.com\r\n"))
  5468  	time.Sleep(2 * time.Second)
  5469  	if _, err := io.CopyN(ioutil.Discard, conn, 1); err == nil {
  5470  		t.Fatal("copy byte succeeded; want err")
  5471  	}
  5472  }
  5473  
  5474  func get(t *testing.T, c *Client, url string) string {
  5475  	res, err := c.Get(url)
  5476  	if err != nil {
  5477  		t.Fatal(err)
  5478  	}
  5479  	defer res.Body.Close()
  5480  	slurp, err := ioutil.ReadAll(res.Body)
  5481  	if err != nil {
  5482  		t.Fatal(err)
  5483  	}
  5484  	return string(slurp)
  5485  }
  5486  
  5487  // Tests that calls to Server.SetKeepAlivesEnabled(false) closes any
  5488  // currently-open connections.
  5489  func TestServerSetKeepAlivesEnabledClosesConns(t *testing.T) {
  5490  	setParallel(t)
  5491  	defer afterTest(t)
  5492  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5493  		io.WriteString(w, r.RemoteAddr)
  5494  	}))
  5495  	defer ts.Close()
  5496  
  5497  	c := ts.Client()
  5498  	tr := c.Transport.(*Transport)
  5499  
  5500  	get := func() string { return get(t, c, ts.URL) }
  5501  
  5502  	a1, a2 := get(), get()
  5503  	if a1 != a2 {
  5504  		t.Fatal("expected first two requests on same connection")
  5505  	}
  5506  	var idle0 int
  5507  	if !waitCondition(2*time.Second, 10*time.Millisecond, func() bool {
  5508  		idle0 = tr.IdleConnKeyCountForTesting()
  5509  		return idle0 == 1
  5510  	}) {
  5511  		t.Fatalf("idle count before SetKeepAlivesEnabled called = %v; want 1", idle0)
  5512  	}
  5513  
  5514  	ts.Config.SetKeepAlivesEnabled(false)
  5515  
  5516  	var idle1 int
  5517  	if !waitCondition(2*time.Second, 10*time.Millisecond, func() bool {
  5518  		idle1 = tr.IdleConnKeyCountForTesting()
  5519  		return idle1 == 0
  5520  	}) {
  5521  		t.Fatalf("idle count after SetKeepAlivesEnabled called = %v; want 0", idle1)
  5522  	}
  5523  
  5524  	a3 := get()
  5525  	if a3 == a2 {
  5526  		t.Fatal("expected third request on new connection")
  5527  	}
  5528  }
  5529  
  5530  func TestServerShutdown_h1(t *testing.T) { testServerShutdown(t, h1Mode) }
  5531  func TestServerShutdown_h2(t *testing.T) { testServerShutdown(t, h2Mode) }
  5532  
  5533  func testServerShutdown(t *testing.T, h2 bool) {
  5534  	setParallel(t)
  5535  	defer afterTest(t)
  5536  	var doShutdown func() // set later
  5537  	var shutdownRes = make(chan error, 1)
  5538  	var gotOnShutdown = make(chan struct{}, 1)
  5539  	handler := HandlerFunc(func(w ResponseWriter, r *Request) {
  5540  		go doShutdown()
  5541  		// Shutdown is graceful, so it should not interrupt
  5542  		// this in-flight response. Add a tiny sleep here to
  5543  		// increase the odds of a failure if shutdown has
  5544  		// bugs.
  5545  		time.Sleep(20 * time.Millisecond)
  5546  		io.WriteString(w, r.RemoteAddr)
  5547  	})
  5548  	cst := newClientServerTest(t, h2, handler, func(srv *httptest.Server) {
  5549  		srv.Config.RegisterOnShutdown(func() { gotOnShutdown <- struct{}{} })
  5550  	})
  5551  	defer cst.close()
  5552  
  5553  	doShutdown = func() {
  5554  		shutdownRes <- cst.ts.Config.Shutdown(context.Background())
  5555  	}
  5556  	get(t, cst.c, cst.ts.URL) // calls t.Fail on failure
  5557  
  5558  	if err := <-shutdownRes; err != nil {
  5559  		t.Fatalf("Shutdown: %v", err)
  5560  	}
  5561  	select {
  5562  	case <-gotOnShutdown:
  5563  	case <-time.After(5 * time.Second):
  5564  		t.Errorf("onShutdown callback not called, RegisterOnShutdown broken?")
  5565  	}
  5566  
  5567  	res, err := cst.c.Get(cst.ts.URL)
  5568  	if err == nil {
  5569  		res.Body.Close()
  5570  		t.Fatal("second request should fail. server should be shut down")
  5571  	}
  5572  }
  5573  
  5574  func TestServerShutdownStateNew(t *testing.T) {
  5575  	if testing.Short() {
  5576  		t.Skip("test takes 5-6 seconds; skipping in short mode")
  5577  	}
  5578  	setParallel(t)
  5579  	defer afterTest(t)
  5580  
  5581  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5582  		// nothing.
  5583  	}))
  5584  	var connAccepted sync.WaitGroup
  5585  	ts.Config.ConnState = func(conn net.Conn, state ConnState) {
  5586  		if state == StateNew {
  5587  			connAccepted.Done()
  5588  		}
  5589  	}
  5590  	ts.Start()
  5591  	defer ts.Close()
  5592  
  5593  	// Start a connection but never write to it.
  5594  	connAccepted.Add(1)
  5595  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  5596  	if err != nil {
  5597  		t.Fatal(err)
  5598  	}
  5599  	defer c.Close()
  5600  
  5601  	// Wait for the connection to be accepted by the server. Otherwise, if
  5602  	// Shutdown happens to run first, the server will be closed when
  5603  	// encountering the connection, in which case it will be rejected
  5604  	// immediately.
  5605  	connAccepted.Wait()
  5606  
  5607  	shutdownRes := make(chan error, 1)
  5608  	go func() {
  5609  		shutdownRes <- ts.Config.Shutdown(context.Background())
  5610  	}()
  5611  	readRes := make(chan error, 1)
  5612  	go func() {
  5613  		_, err := c.Read([]byte{0})
  5614  		readRes <- err
  5615  	}()
  5616  
  5617  	const expectTimeout = 5 * time.Second
  5618  	t0 := time.Now()
  5619  	select {
  5620  	case got := <-shutdownRes:
  5621  		d := time.Since(t0)
  5622  		if got != nil {
  5623  			t.Fatalf("shutdown error after %v: %v", d, err)
  5624  		}
  5625  		if d < expectTimeout/2 {
  5626  			t.Errorf("shutdown too soon after %v", d)
  5627  		}
  5628  	case <-time.After(expectTimeout * 3 / 2):
  5629  		t.Fatalf("timeout waiting for shutdown")
  5630  	}
  5631  
  5632  	// Wait for c.Read to unblock; should be already done at this point,
  5633  	// or within a few milliseconds.
  5634  	select {
  5635  	case err := <-readRes:
  5636  		if err == nil {
  5637  			t.Error("expected error from Read")
  5638  		}
  5639  	case <-time.After(2 * time.Second):
  5640  		t.Errorf("timeout waiting for Read to unblock")
  5641  	}
  5642  }
  5643  
  5644  // Issue 17878: tests that we can call Close twice.
  5645  func TestServerCloseDeadlock(t *testing.T) {
  5646  	var s Server
  5647  	s.Close()
  5648  	s.Close()
  5649  }
  5650  
  5651  // Issue 17717: tests that Server.SetKeepAlivesEnabled is respected by
  5652  // both HTTP/1 and HTTP/2.
  5653  func TestServerKeepAlivesEnabled_h1(t *testing.T) { testServerKeepAlivesEnabled(t, h1Mode) }
  5654  func TestServerKeepAlivesEnabled_h2(t *testing.T) { testServerKeepAlivesEnabled(t, h2Mode) }
  5655  func testServerKeepAlivesEnabled(t *testing.T, h2 bool) {
  5656  	if h2 {
  5657  		restore := ExportSetH2GoawayTimeout(10 * time.Millisecond)
  5658  		defer restore()
  5659  	}
  5660  	// Not parallel: messes with global variable. (http2goAwayTimeout)
  5661  	defer afterTest(t)
  5662  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  5663  		fmt.Fprintf(w, "%v", r.RemoteAddr)
  5664  	}))
  5665  	defer cst.close()
  5666  	srv := cst.ts.Config
  5667  	srv.SetKeepAlivesEnabled(false)
  5668  	a := cst.getURL(cst.ts.URL)
  5669  	if !waitCondition(2*time.Second, 10*time.Millisecond, srv.ExportAllConnsIdle) {
  5670  		t.Fatalf("test server has active conns")
  5671  	}
  5672  	b := cst.getURL(cst.ts.URL)
  5673  	if a == b {
  5674  		t.Errorf("got same connection between first and second requests")
  5675  	}
  5676  	if !waitCondition(2*time.Second, 10*time.Millisecond, srv.ExportAllConnsIdle) {
  5677  		t.Fatalf("test server has active conns")
  5678  	}
  5679  }
  5680  
  5681  // Issue 18447: test that the Server's ReadTimeout is stopped while
  5682  // the server's doing its 1-byte background read between requests,
  5683  // waiting for the connection to maybe close.
  5684  func TestServerCancelsReadTimeoutWhenIdle(t *testing.T) {
  5685  	setParallel(t)
  5686  	defer afterTest(t)
  5687  	runTimeSensitiveTest(t, []time.Duration{
  5688  		10 * time.Millisecond,
  5689  		50 * time.Millisecond,
  5690  		250 * time.Millisecond,
  5691  		time.Second,
  5692  		2 * time.Second,
  5693  	}, func(t *testing.T, timeout time.Duration) error {
  5694  		ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5695  			select {
  5696  			case <-time.After(2 * timeout):
  5697  				fmt.Fprint(w, "ok")
  5698  			case <-r.Context().Done():
  5699  				fmt.Fprint(w, r.Context().Err())
  5700  			}
  5701  		}))
  5702  		ts.Config.ReadTimeout = timeout
  5703  		ts.Start()
  5704  		defer ts.Close()
  5705  
  5706  		c := ts.Client()
  5707  
  5708  		res, err := c.Get(ts.URL)
  5709  		if err != nil {
  5710  			return fmt.Errorf("Get: %v", err)
  5711  		}
  5712  		slurp, err := ioutil.ReadAll(res.Body)
  5713  		res.Body.Close()
  5714  		if err != nil {
  5715  			return fmt.Errorf("Body ReadAll: %v", err)
  5716  		}
  5717  		if string(slurp) != "ok" {
  5718  			return fmt.Errorf("got: %q, want ok", slurp)
  5719  		}
  5720  		return nil
  5721  	})
  5722  }
  5723  
  5724  // runTimeSensitiveTest runs test with the provided durations until one passes.
  5725  // If they all fail, t.Fatal is called with the last one's duration and error value.
  5726  func runTimeSensitiveTest(t *testing.T, durations []time.Duration, test func(t *testing.T, d time.Duration) error) {
  5727  	for i, d := range durations {
  5728  		err := test(t, d)
  5729  		if err == nil {
  5730  			return
  5731  		}
  5732  		if i == len(durations)-1 {
  5733  			t.Fatalf("failed with duration %v: %v", d, err)
  5734  		}
  5735  	}
  5736  }
  5737  
  5738  // Issue 18535: test that the Server doesn't try to do a background
  5739  // read if it's already done one.
  5740  func TestServerDuplicateBackgroundRead(t *testing.T) {
  5741  	if runtime.GOOS == "netbsd" && runtime.GOARCH == "arm" {
  5742  		testenv.SkipFlaky(t, 24826)
  5743  	}
  5744  
  5745  	setParallel(t)
  5746  	defer afterTest(t)
  5747  
  5748  	const goroutines = 5
  5749  	const requests = 2000
  5750  
  5751  	hts := httptest.NewServer(HandlerFunc(NotFound))
  5752  	defer hts.Close()
  5753  
  5754  	reqBytes := []byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")
  5755  
  5756  	var wg sync.WaitGroup
  5757  	for i := 0; i < goroutines; i++ {
  5758  		wg.Add(1)
  5759  		go func() {
  5760  			defer wg.Done()
  5761  			cn, err := net.Dial("tcp", hts.Listener.Addr().String())
  5762  			if err != nil {
  5763  				t.Error(err)
  5764  				return
  5765  			}
  5766  			defer cn.Close()
  5767  
  5768  			wg.Add(1)
  5769  			go func() {
  5770  				defer wg.Done()
  5771  				io.Copy(ioutil.Discard, cn)
  5772  			}()
  5773  
  5774  			for j := 0; j < requests; j++ {
  5775  				if t.Failed() {
  5776  					return
  5777  				}
  5778  				_, err := cn.Write(reqBytes)
  5779  				if err != nil {
  5780  					t.Error(err)
  5781  					return
  5782  				}
  5783  			}
  5784  		}()
  5785  	}
  5786  	wg.Wait()
  5787  }
  5788  
  5789  // Test that the bufio.Reader returned by Hijack includes any buffered
  5790  // byte (from the Server's backgroundRead) in its buffer. We want the
  5791  // Handler code to be able to tell that a byte is available via
  5792  // bufio.Reader.Buffered(), without resorting to Reading it
  5793  // (potentially blocking) to get at it.
  5794  func TestServerHijackGetsBackgroundByte(t *testing.T) {
  5795  	if runtime.GOOS == "plan9" {
  5796  		t.Skip("skipping test; see https://golang.org/issue/18657")
  5797  	}
  5798  	setParallel(t)
  5799  	defer afterTest(t)
  5800  	done := make(chan struct{})
  5801  	inHandler := make(chan bool, 1)
  5802  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5803  		defer close(done)
  5804  
  5805  		// Tell the client to send more data after the GET request.
  5806  		inHandler <- true
  5807  
  5808  		conn, buf, err := w.(Hijacker).Hijack()
  5809  		if err != nil {
  5810  			t.Error(err)
  5811  			return
  5812  		}
  5813  		defer conn.Close()
  5814  
  5815  		peek, err := buf.Reader.Peek(3)
  5816  		if string(peek) != "foo" || err != nil {
  5817  			t.Errorf("Peek = %q, %v; want foo, nil", peek, err)
  5818  		}
  5819  
  5820  		select {
  5821  		case <-r.Context().Done():
  5822  			t.Error("context unexpectedly canceled")
  5823  		default:
  5824  		}
  5825  	}))
  5826  	defer ts.Close()
  5827  
  5828  	cn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5829  	if err != nil {
  5830  		t.Fatal(err)
  5831  	}
  5832  	defer cn.Close()
  5833  	if _, err := cn.Write([]byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")); err != nil {
  5834  		t.Fatal(err)
  5835  	}
  5836  	<-inHandler
  5837  	if _, err := cn.Write([]byte("foo")); err != nil {
  5838  		t.Fatal(err)
  5839  	}
  5840  
  5841  	if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
  5842  		t.Fatal(err)
  5843  	}
  5844  	select {
  5845  	case <-done:
  5846  	case <-time.After(2 * time.Second):
  5847  		t.Error("timeout")
  5848  	}
  5849  }
  5850  
  5851  // Like TestServerHijackGetsBackgroundByte above but sending a
  5852  // immediate 1MB of data to the server to fill up the server's 4KB
  5853  // buffer.
  5854  func TestServerHijackGetsBackgroundByte_big(t *testing.T) {
  5855  	if runtime.GOOS == "plan9" {
  5856  		t.Skip("skipping test; see https://golang.org/issue/18657")
  5857  	}
  5858  	setParallel(t)
  5859  	defer afterTest(t)
  5860  	done := make(chan struct{})
  5861  	const size = 8 << 10
  5862  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5863  		defer close(done)
  5864  
  5865  		conn, buf, err := w.(Hijacker).Hijack()
  5866  		if err != nil {
  5867  			t.Error(err)
  5868  			return
  5869  		}
  5870  		defer conn.Close()
  5871  		slurp, err := ioutil.ReadAll(buf.Reader)
  5872  		if err != nil {
  5873  			t.Errorf("Copy: %v", err)
  5874  		}
  5875  		allX := true
  5876  		for _, v := range slurp {
  5877  			if v != 'x' {
  5878  				allX = false
  5879  			}
  5880  		}
  5881  		if len(slurp) != size {
  5882  			t.Errorf("read %d; want %d", len(slurp), size)
  5883  		} else if !allX {
  5884  			t.Errorf("read %q; want %d 'x'", slurp, size)
  5885  		}
  5886  	}))
  5887  	defer ts.Close()
  5888  
  5889  	cn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5890  	if err != nil {
  5891  		t.Fatal(err)
  5892  	}
  5893  	defer cn.Close()
  5894  	if _, err := fmt.Fprintf(cn, "GET / HTTP/1.1\r\nHost: e.com\r\n\r\n%s",
  5895  		strings.Repeat("x", size)); err != nil {
  5896  		t.Fatal(err)
  5897  	}
  5898  	if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
  5899  		t.Fatal(err)
  5900  	}
  5901  
  5902  	select {
  5903  	case <-done:
  5904  	case <-time.After(2 * time.Second):
  5905  		t.Error("timeout")
  5906  	}
  5907  }
  5908  
  5909  // Issue 18319: test that the Server validates the request method.
  5910  func TestServerValidatesMethod(t *testing.T) {
  5911  	tests := []struct {
  5912  		method string
  5913  		want   int
  5914  	}{
  5915  		{"GET", 200},
  5916  		{"GE(T", 400},
  5917  	}
  5918  	for _, tt := range tests {
  5919  		conn := &testConn{closec: make(chan bool, 1)}
  5920  		io.WriteString(&conn.readBuf, tt.method+" / HTTP/1.1\r\nHost: foo.example\r\n\r\n")
  5921  
  5922  		ln := &oneConnListener{conn}
  5923  		go Serve(ln, serve(200))
  5924  		<-conn.closec
  5925  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  5926  		if err != nil {
  5927  			t.Errorf("For %s, ReadResponse: %v", tt.method, res)
  5928  			continue
  5929  		}
  5930  		if res.StatusCode != tt.want {
  5931  			t.Errorf("For %s, Status = %d; want %d", tt.method, res.StatusCode, tt.want)
  5932  		}
  5933  	}
  5934  }
  5935  
  5936  // Listener for TestServerListenNotComparableListener.
  5937  type eofListenerNotComparable []int
  5938  
  5939  func (eofListenerNotComparable) Accept() (net.Conn, error) { return nil, io.EOF }
  5940  func (eofListenerNotComparable) Addr() net.Addr            { return nil }
  5941  func (eofListenerNotComparable) Close() error              { return nil }
  5942  
  5943  // Issue 24812: don't crash on non-comparable Listener
  5944  func TestServerListenNotComparableListener(t *testing.T) {
  5945  	var s Server
  5946  	s.Serve(make(eofListenerNotComparable, 1)) // used to panic
  5947  }
  5948  
  5949  // countCloseListener is a Listener wrapper that counts the number of Close calls.
  5950  type countCloseListener struct {
  5951  	net.Listener
  5952  	closes int32 // atomic
  5953  }
  5954  
  5955  func (p *countCloseListener) Close() error {
  5956  	atomic.AddInt32(&p.closes, 1)
  5957  	return nil
  5958  }
  5959  
  5960  // Issue 24803: don't call Listener.Close on Server.Shutdown.
  5961  func TestServerCloseListenerOnce(t *testing.T) {
  5962  	setParallel(t)
  5963  	defer afterTest(t)
  5964  
  5965  	ln := newLocalListener(t)
  5966  	defer ln.Close()
  5967  
  5968  	cl := &countCloseListener{Listener: ln}
  5969  	server := &Server{}
  5970  	sdone := make(chan bool, 1)
  5971  
  5972  	go func() {
  5973  		server.Serve(cl)
  5974  		sdone <- true
  5975  	}()
  5976  	time.Sleep(10 * time.Millisecond)
  5977  	server.Shutdown(context.Background())
  5978  	ln.Close()
  5979  	<-sdone
  5980  
  5981  	nclose := atomic.LoadInt32(&cl.closes)
  5982  	if nclose != 1 {
  5983  		t.Errorf("Close calls = %v; want 1", nclose)
  5984  	}
  5985  }
  5986  
  5987  // Issue 20239: don't block in Serve if Shutdown is called first.
  5988  func TestServerShutdownThenServe(t *testing.T) {
  5989  	var srv Server
  5990  	cl := &countCloseListener{Listener: nil}
  5991  	srv.Shutdown(context.Background())
  5992  	got := srv.Serve(cl)
  5993  	if got != ErrServerClosed {
  5994  		t.Errorf("Serve err = %v; want ErrServerClosed", got)
  5995  	}
  5996  	nclose := atomic.LoadInt32(&cl.closes)
  5997  	if nclose != 1 {
  5998  		t.Errorf("Close calls = %v; want 1", nclose)
  5999  	}
  6000  }
  6001  
  6002  // Issue 23351: document and test behavior of ServeMux with ports
  6003  func TestStripPortFromHost(t *testing.T) {
  6004  	mux := NewServeMux()
  6005  
  6006  	mux.HandleFunc("example.com/", func(w ResponseWriter, r *Request) {
  6007  		fmt.Fprintf(w, "OK")
  6008  	})
  6009  	mux.HandleFunc("example.com:9000/", func(w ResponseWriter, r *Request) {
  6010  		fmt.Fprintf(w, "uh-oh!")
  6011  	})
  6012  
  6013  	req := httptest.NewRequest("GET", "http://example.com:9000/", nil)
  6014  	rw := httptest.NewRecorder()
  6015  
  6016  	mux.ServeHTTP(rw, req)
  6017  
  6018  	response := rw.Body.String()
  6019  	if response != "OK" {
  6020  		t.Errorf("Response gotten was %q", response)
  6021  	}
  6022  }
  6023  
  6024  func BenchmarkResponseStatusLine(b *testing.B) {
  6025  	b.ReportAllocs()
  6026  	b.RunParallel(func(pb *testing.PB) {
  6027  		bw := bufio.NewWriter(ioutil.Discard)
  6028  		var buf3 [3]byte
  6029  		for pb.Next() {
  6030  			Export_writeStatusLine(bw, true, 200, buf3[:])
  6031  		}
  6032  	})
  6033  }
  6034  

View as plain text