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