github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/net/http/serve_test.go (about)

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