Source file src/net/http/serve_test.go

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // End-to-end serving tests
     6  
     7  package http_test
     8  
     9  import (
    10  	"bufio"
    11  	"bytes"
    12  	"compress/gzip"
    13  	"compress/zlib"
    14  	"context"
    15  	"crypto/tls"
    16  	"encoding/json"
    17  	"errors"
    18  	"fmt"
    19  	"internal/testenv"
    20  	"io"
    21  	"log"
    22  	"math/rand"
    23  	"net"
    24  	. "net/http"
    25  	"net/http/httptest"
    26  	"net/http/httptrace"
    27  	"net/http/httputil"
    28  	"net/http/internal"
    29  	"net/http/internal/testcert"
    30  	"net/url"
    31  	"os"
    32  	"os/exec"
    33  	"path/filepath"
    34  	"reflect"
    35  	"regexp"
    36  	"runtime"
    37  	"runtime/debug"
    38  	"strconv"
    39  	"strings"
    40  	"sync"
    41  	"sync/atomic"
    42  	"syscall"
    43  	"testing"
    44  	"time"
    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 []any
  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: []any{
  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  // cancelableTimeoutContext overwrites the error message to DeadlineExceeded
  2278  type cancelableTimeoutContext struct {
  2279  	context.Context
  2280  }
  2281  
  2282  func (c cancelableTimeoutContext) Err() error {
  2283  	if c.Context.Err() != nil {
  2284  		return context.DeadlineExceeded
  2285  	}
  2286  	return nil
  2287  }
  2288  
  2289  func TestTimeoutHandler_h1(t *testing.T) { testTimeoutHandler(t, h1Mode) }
  2290  func TestTimeoutHandler_h2(t *testing.T) { testTimeoutHandler(t, h2Mode) }
  2291  func testTimeoutHandler(t *testing.T, h2 bool) {
  2292  	setParallel(t)
  2293  	defer afterTest(t)
  2294  	sendHi := make(chan bool, 1)
  2295  	writeErrors := make(chan error, 1)
  2296  	sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2297  		<-sendHi
  2298  		_, werr := w.Write([]byte("hi"))
  2299  		writeErrors <- werr
  2300  	})
  2301  	ctx, cancel := context.WithCancel(context.Background())
  2302  	h := NewTestTimeoutHandler(sayHi, cancelableTimeoutContext{ctx})
  2303  	cst := newClientServerTest(t, h2, h)
  2304  	defer cst.close()
  2305  
  2306  	// Succeed without timing out:
  2307  	sendHi <- true
  2308  	res, err := cst.c.Get(cst.ts.URL)
  2309  	if err != nil {
  2310  		t.Error(err)
  2311  	}
  2312  	if g, e := res.StatusCode, StatusOK; g != e {
  2313  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2314  	}
  2315  	body, _ := io.ReadAll(res.Body)
  2316  	if g, e := string(body), "hi"; g != e {
  2317  		t.Errorf("got body %q; expected %q", g, e)
  2318  	}
  2319  	if g := <-writeErrors; g != nil {
  2320  		t.Errorf("got unexpected Write error on first request: %v", g)
  2321  	}
  2322  
  2323  	// Times out:
  2324  	cancel()
  2325  
  2326  	res, err = cst.c.Get(cst.ts.URL)
  2327  	if err != nil {
  2328  		t.Error(err)
  2329  	}
  2330  	if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  2331  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2332  	}
  2333  	body, _ = io.ReadAll(res.Body)
  2334  	if !strings.Contains(string(body), "<title>Timeout</title>") {
  2335  		t.Errorf("expected timeout body; got %q", string(body))
  2336  	}
  2337  	if g, w := res.Header.Get("Content-Type"), "text/html; charset=utf-8"; g != w {
  2338  		t.Errorf("response content-type = %q; want %q", g, w)
  2339  	}
  2340  
  2341  	// Now make the previously-timed out handler speak again,
  2342  	// which verifies the panic is handled:
  2343  	sendHi <- true
  2344  	if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
  2345  		t.Errorf("expected Write error of %v; got %v", e, g)
  2346  	}
  2347  }
  2348  
  2349  // See issues 8209 and 8414.
  2350  func TestTimeoutHandlerRace(t *testing.T) {
  2351  	setParallel(t)
  2352  	defer afterTest(t)
  2353  
  2354  	delayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2355  		ms, _ := strconv.Atoi(r.URL.Path[1:])
  2356  		if ms == 0 {
  2357  			ms = 1
  2358  		}
  2359  		for i := 0; i < ms; i++ {
  2360  			w.Write([]byte("hi"))
  2361  			time.Sleep(time.Millisecond)
  2362  		}
  2363  	})
  2364  
  2365  	ts := httptest.NewServer(TimeoutHandler(delayHi, 20*time.Millisecond, ""))
  2366  	defer ts.Close()
  2367  
  2368  	c := ts.Client()
  2369  
  2370  	var wg sync.WaitGroup
  2371  	gate := make(chan bool, 10)
  2372  	n := 50
  2373  	if testing.Short() {
  2374  		n = 10
  2375  		gate = make(chan bool, 3)
  2376  	}
  2377  	for i := 0; i < n; i++ {
  2378  		gate <- true
  2379  		wg.Add(1)
  2380  		go func() {
  2381  			defer wg.Done()
  2382  			defer func() { <-gate }()
  2383  			res, err := c.Get(fmt.Sprintf("%s/%d", ts.URL, rand.Intn(50)))
  2384  			if err == nil {
  2385  				io.Copy(io.Discard, res.Body)
  2386  				res.Body.Close()
  2387  			}
  2388  		}()
  2389  	}
  2390  	wg.Wait()
  2391  }
  2392  
  2393  // See issues 8209 and 8414.
  2394  // Both issues involved panics in the implementation of TimeoutHandler.
  2395  func TestTimeoutHandlerRaceHeader(t *testing.T) {
  2396  	setParallel(t)
  2397  	defer afterTest(t)
  2398  
  2399  	delay204 := HandlerFunc(func(w ResponseWriter, r *Request) {
  2400  		w.WriteHeader(204)
  2401  	})
  2402  
  2403  	ts := httptest.NewServer(TimeoutHandler(delay204, time.Nanosecond, ""))
  2404  	defer ts.Close()
  2405  
  2406  	var wg sync.WaitGroup
  2407  	gate := make(chan bool, 50)
  2408  	n := 500
  2409  	if testing.Short() {
  2410  		n = 10
  2411  	}
  2412  
  2413  	c := ts.Client()
  2414  	for i := 0; i < n; i++ {
  2415  		gate <- true
  2416  		wg.Add(1)
  2417  		go func() {
  2418  			defer wg.Done()
  2419  			defer func() { <-gate }()
  2420  			res, err := c.Get(ts.URL)
  2421  			if err != nil {
  2422  				// We see ECONNRESET from the connection occasionally,
  2423  				// and that's OK: this test is checking that the server does not panic.
  2424  				t.Log(err)
  2425  				return
  2426  			}
  2427  			defer res.Body.Close()
  2428  			io.Copy(io.Discard, res.Body)
  2429  		}()
  2430  	}
  2431  	wg.Wait()
  2432  }
  2433  
  2434  // Issue 9162
  2435  func TestTimeoutHandlerRaceHeaderTimeout(t *testing.T) {
  2436  	setParallel(t)
  2437  	defer afterTest(t)
  2438  	sendHi := make(chan bool, 1)
  2439  	writeErrors := make(chan error, 1)
  2440  	sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2441  		w.Header().Set("Content-Type", "text/plain")
  2442  		<-sendHi
  2443  		_, werr := w.Write([]byte("hi"))
  2444  		writeErrors <- werr
  2445  	})
  2446  	ctx, cancel := context.WithCancel(context.Background())
  2447  	h := NewTestTimeoutHandler(sayHi, cancelableTimeoutContext{ctx})
  2448  	cst := newClientServerTest(t, h1Mode, h)
  2449  	defer cst.close()
  2450  
  2451  	// Succeed without timing out:
  2452  	sendHi <- true
  2453  	res, err := cst.c.Get(cst.ts.URL)
  2454  	if err != nil {
  2455  		t.Error(err)
  2456  	}
  2457  	if g, e := res.StatusCode, StatusOK; g != e {
  2458  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2459  	}
  2460  	body, _ := io.ReadAll(res.Body)
  2461  	if g, e := string(body), "hi"; g != e {
  2462  		t.Errorf("got body %q; expected %q", g, e)
  2463  	}
  2464  	if g := <-writeErrors; g != nil {
  2465  		t.Errorf("got unexpected Write error on first request: %v", g)
  2466  	}
  2467  
  2468  	// Times out:
  2469  	cancel()
  2470  
  2471  	res, err = cst.c.Get(cst.ts.URL)
  2472  	if err != nil {
  2473  		t.Error(err)
  2474  	}
  2475  	if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  2476  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2477  	}
  2478  	body, _ = io.ReadAll(res.Body)
  2479  	if !strings.Contains(string(body), "<title>Timeout</title>") {
  2480  		t.Errorf("expected timeout body; got %q", string(body))
  2481  	}
  2482  
  2483  	// Now make the previously-timed out handler speak again,
  2484  	// which verifies the panic is handled:
  2485  	sendHi <- true
  2486  	if g, e := <-writeErrors, ErrHandlerTimeout; g != e {
  2487  		t.Errorf("expected Write error of %v; got %v", e, g)
  2488  	}
  2489  }
  2490  
  2491  // Issue 14568.
  2492  func TestTimeoutHandlerStartTimerWhenServing(t *testing.T) {
  2493  	if testing.Short() {
  2494  		t.Skip("skipping sleeping test in -short mode")
  2495  	}
  2496  	defer afterTest(t)
  2497  	var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
  2498  		w.WriteHeader(StatusNoContent)
  2499  	}
  2500  	timeout := 300 * time.Millisecond
  2501  	ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
  2502  	defer ts.Close()
  2503  
  2504  	c := ts.Client()
  2505  
  2506  	// Issue was caused by the timeout handler starting the timer when
  2507  	// was created, not when the request. So wait for more than the timeout
  2508  	// to ensure that's not the case.
  2509  	time.Sleep(2 * timeout)
  2510  	res, err := c.Get(ts.URL)
  2511  	if err != nil {
  2512  		t.Fatal(err)
  2513  	}
  2514  	defer res.Body.Close()
  2515  	if res.StatusCode != StatusNoContent {
  2516  		t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusNoContent)
  2517  	}
  2518  }
  2519  
  2520  func TestTimeoutHandlerContextCanceled(t *testing.T) {
  2521  	setParallel(t)
  2522  	defer afterTest(t)
  2523  	writeErrors := make(chan error, 1)
  2524  	sayHi := HandlerFunc(func(w ResponseWriter, r *Request) {
  2525  		w.Header().Set("Content-Type", "text/plain")
  2526  		var err error
  2527  		// The request context has already been canceled, but
  2528  		// retry the write for a while to give the timeout handler
  2529  		// a chance to notice.
  2530  		for i := 0; i < 100; i++ {
  2531  			_, err = w.Write([]byte("a"))
  2532  			if err != nil {
  2533  				break
  2534  			}
  2535  			time.Sleep(1 * time.Millisecond)
  2536  		}
  2537  		writeErrors <- err
  2538  	})
  2539  	ctx, cancel := context.WithCancel(context.Background())
  2540  	cancel()
  2541  	h := NewTestTimeoutHandler(sayHi, ctx)
  2542  	cst := newClientServerTest(t, h1Mode, h)
  2543  	defer cst.close()
  2544  
  2545  	res, err := cst.c.Get(cst.ts.URL)
  2546  	if err != nil {
  2547  		t.Error(err)
  2548  	}
  2549  	if g, e := res.StatusCode, StatusServiceUnavailable; g != e {
  2550  		t.Errorf("got res.StatusCode %d; expected %d", g, e)
  2551  	}
  2552  	body, _ := io.ReadAll(res.Body)
  2553  	if g, e := string(body), ""; g != e {
  2554  		t.Errorf("got body %q; expected %q", g, e)
  2555  	}
  2556  	if g, e := <-writeErrors, context.Canceled; g != e {
  2557  		t.Errorf("got unexpected Write in handler: %v, want %g", g, e)
  2558  	}
  2559  }
  2560  
  2561  // https://golang.org/issue/15948
  2562  func TestTimeoutHandlerEmptyResponse(t *testing.T) {
  2563  	setParallel(t)
  2564  	defer afterTest(t)
  2565  	var handler HandlerFunc = func(w ResponseWriter, _ *Request) {
  2566  		// No response.
  2567  	}
  2568  	timeout := 300 * time.Millisecond
  2569  	ts := httptest.NewServer(TimeoutHandler(handler, timeout, ""))
  2570  	defer ts.Close()
  2571  
  2572  	c := ts.Client()
  2573  
  2574  	res, err := c.Get(ts.URL)
  2575  	if err != nil {
  2576  		t.Fatal(err)
  2577  	}
  2578  	defer res.Body.Close()
  2579  	if res.StatusCode != StatusOK {
  2580  		t.Errorf("got res.StatusCode %d, want %v", res.StatusCode, StatusOK)
  2581  	}
  2582  }
  2583  
  2584  // https://golang.org/issues/22084
  2585  func TestTimeoutHandlerPanicRecovery(t *testing.T) {
  2586  	wrapper := func(h Handler) Handler {
  2587  		return TimeoutHandler(h, time.Second, "")
  2588  	}
  2589  	testHandlerPanic(t, false, false, wrapper, "intentional death for testing")
  2590  }
  2591  
  2592  func TestRedirectBadPath(t *testing.T) {
  2593  	// This used to crash. It's not valid input (bad path), but it
  2594  	// shouldn't crash.
  2595  	rr := httptest.NewRecorder()
  2596  	req := &Request{
  2597  		Method: "GET",
  2598  		URL: &url.URL{
  2599  			Scheme: "http",
  2600  			Path:   "not-empty-but-no-leading-slash", // bogus
  2601  		},
  2602  	}
  2603  	Redirect(rr, req, "", 304)
  2604  	if rr.Code != 304 {
  2605  		t.Errorf("Code = %d; want 304", rr.Code)
  2606  	}
  2607  }
  2608  
  2609  // Test different URL formats and schemes
  2610  func TestRedirect(t *testing.T) {
  2611  	req, _ := NewRequest("GET", "http://example.com/qux/", nil)
  2612  
  2613  	var tests = []struct {
  2614  		in   string
  2615  		want string
  2616  	}{
  2617  		// normal http
  2618  		{"http://foobar.com/baz", "http://foobar.com/baz"},
  2619  		// normal https
  2620  		{"https://foobar.com/baz", "https://foobar.com/baz"},
  2621  		// custom scheme
  2622  		{"test://foobar.com/baz", "test://foobar.com/baz"},
  2623  		// schemeless
  2624  		{"//foobar.com/baz", "//foobar.com/baz"},
  2625  		// relative to the root
  2626  		{"/foobar.com/baz", "/foobar.com/baz"},
  2627  		// relative to the current path
  2628  		{"foobar.com/baz", "/qux/foobar.com/baz"},
  2629  		// relative to the current path (+ going upwards)
  2630  		{"../quux/foobar.com/baz", "/quux/foobar.com/baz"},
  2631  		// incorrect number of slashes
  2632  		{"///foobar.com/baz", "/foobar.com/baz"},
  2633  
  2634  		// Verifies we don't path.Clean() on the wrong parts in redirects:
  2635  		{"/foo?next=http://bar.com/", "/foo?next=http://bar.com/"},
  2636  		{"http://localhost:8080/_ah/login?continue=http://localhost:8080/",
  2637  			"http://localhost:8080/_ah/login?continue=http://localhost:8080/"},
  2638  
  2639  		{"/фубар", "/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
  2640  		{"http://foo.com/фубар", "http://foo.com/%d1%84%d1%83%d0%b1%d0%b0%d1%80"},
  2641  	}
  2642  
  2643  	for _, tt := range tests {
  2644  		rec := httptest.NewRecorder()
  2645  		Redirect(rec, req, tt.in, 302)
  2646  		if got, want := rec.Code, 302; got != want {
  2647  			t.Errorf("Redirect(%q) generated status code %v; want %v", tt.in, got, want)
  2648  		}
  2649  		if got := rec.Header().Get("Location"); got != tt.want {
  2650  			t.Errorf("Redirect(%q) generated Location header %q; want %q", tt.in, got, tt.want)
  2651  		}
  2652  	}
  2653  }
  2654  
  2655  // Test that Redirect sets Content-Type header for GET and HEAD requests
  2656  // and writes a short HTML body, unless the request already has a Content-Type header.
  2657  func TestRedirectContentTypeAndBody(t *testing.T) {
  2658  	type ctHeader struct {
  2659  		Values []string
  2660  	}
  2661  
  2662  	var tests = []struct {
  2663  		method   string
  2664  		ct       *ctHeader // Optional Content-Type header to set.
  2665  		wantCT   string
  2666  		wantBody string
  2667  	}{
  2668  		{MethodGet, nil, "text/html; charset=utf-8", "<a href=\"/foo\">Found</a>.\n\n"},
  2669  		{MethodHead, nil, "text/html; charset=utf-8", ""},
  2670  		{MethodPost, nil, "", ""},
  2671  		{MethodDelete, nil, "", ""},
  2672  		{"foo", nil, "", ""},
  2673  		{MethodGet, &ctHeader{[]string{"application/test"}}, "application/test", ""},
  2674  		{MethodGet, &ctHeader{[]string{}}, "", ""},
  2675  		{MethodGet, &ctHeader{nil}, "", ""},
  2676  	}
  2677  	for _, tt := range tests {
  2678  		req := httptest.NewRequest(tt.method, "http://example.com/qux/", nil)
  2679  		rec := httptest.NewRecorder()
  2680  		if tt.ct != nil {
  2681  			rec.Header()["Content-Type"] = tt.ct.Values
  2682  		}
  2683  		Redirect(rec, req, "/foo", 302)
  2684  		if got, want := rec.Code, 302; got != want {
  2685  			t.Errorf("Redirect(%q, %#v) generated status code %v; want %v", tt.method, tt.ct, got, want)
  2686  		}
  2687  		if got, want := rec.Header().Get("Content-Type"), tt.wantCT; got != want {
  2688  			t.Errorf("Redirect(%q, %#v) generated Content-Type header %q; want %q", tt.method, tt.ct, got, want)
  2689  		}
  2690  		resp := rec.Result()
  2691  		body, err := io.ReadAll(resp.Body)
  2692  		if err != nil {
  2693  			t.Fatal(err)
  2694  		}
  2695  		if got, want := string(body), tt.wantBody; got != want {
  2696  			t.Errorf("Redirect(%q, %#v) generated Body %q; want %q", tt.method, tt.ct, got, want)
  2697  		}
  2698  	}
  2699  }
  2700  
  2701  // TestZeroLengthPostAndResponse exercises an optimization done by the Transport:
  2702  // when there is no body (either because the method doesn't permit a body, or an
  2703  // explicit Content-Length of zero is present), then the transport can re-use the
  2704  // connection immediately. But when it re-uses the connection, it typically closes
  2705  // the previous request's body, which is not optimal for zero-lengthed bodies,
  2706  // as the client would then see http.ErrBodyReadAfterClose and not 0, io.EOF.
  2707  func TestZeroLengthPostAndResponse_h1(t *testing.T) {
  2708  	testZeroLengthPostAndResponse(t, h1Mode)
  2709  }
  2710  func TestZeroLengthPostAndResponse_h2(t *testing.T) {
  2711  	testZeroLengthPostAndResponse(t, h2Mode)
  2712  }
  2713  
  2714  func testZeroLengthPostAndResponse(t *testing.T, h2 bool) {
  2715  	setParallel(t)
  2716  	defer afterTest(t)
  2717  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, r *Request) {
  2718  		all, err := io.ReadAll(r.Body)
  2719  		if err != nil {
  2720  			t.Fatalf("handler ReadAll: %v", err)
  2721  		}
  2722  		if len(all) != 0 {
  2723  			t.Errorf("handler got %d bytes; expected 0", len(all))
  2724  		}
  2725  		rw.Header().Set("Content-Length", "0")
  2726  	}))
  2727  	defer cst.close()
  2728  
  2729  	req, err := NewRequest("POST", cst.ts.URL, strings.NewReader(""))
  2730  	if err != nil {
  2731  		t.Fatal(err)
  2732  	}
  2733  	req.ContentLength = 0
  2734  
  2735  	var resp [5]*Response
  2736  	for i := range resp {
  2737  		resp[i], err = cst.c.Do(req)
  2738  		if err != nil {
  2739  			t.Fatalf("client post #%d: %v", i, err)
  2740  		}
  2741  	}
  2742  
  2743  	for i := range resp {
  2744  		all, err := io.ReadAll(resp[i].Body)
  2745  		if err != nil {
  2746  			t.Fatalf("req #%d: client ReadAll: %v", i, err)
  2747  		}
  2748  		if len(all) != 0 {
  2749  			t.Errorf("req #%d: client got %d bytes; expected 0", i, len(all))
  2750  		}
  2751  	}
  2752  }
  2753  
  2754  func TestHandlerPanicNil_h1(t *testing.T) { testHandlerPanic(t, false, h1Mode, nil, nil) }
  2755  func TestHandlerPanicNil_h2(t *testing.T) { testHandlerPanic(t, false, h2Mode, nil, nil) }
  2756  
  2757  func TestHandlerPanic_h1(t *testing.T) {
  2758  	testHandlerPanic(t, false, h1Mode, nil, "intentional death for testing")
  2759  }
  2760  func TestHandlerPanic_h2(t *testing.T) {
  2761  	testHandlerPanic(t, false, h2Mode, nil, "intentional death for testing")
  2762  }
  2763  
  2764  func TestHandlerPanicWithHijack(t *testing.T) {
  2765  	// Only testing HTTP/1, and our http2 server doesn't support hijacking.
  2766  	testHandlerPanic(t, true, h1Mode, nil, "intentional death for testing")
  2767  }
  2768  
  2769  func testHandlerPanic(t *testing.T, withHijack, h2 bool, wrapper func(Handler) Handler, panicValue any) {
  2770  	defer afterTest(t)
  2771  	// Unlike the other tests that set the log output to io.Discard
  2772  	// to quiet the output, this test uses a pipe. The pipe serves three
  2773  	// purposes:
  2774  	//
  2775  	//   1) The log.Print from the http server (generated by the caught
  2776  	//      panic) will go to the pipe instead of stderr, making the
  2777  	//      output quiet.
  2778  	//
  2779  	//   2) We read from the pipe to verify that the handler
  2780  	//      actually caught the panic and logged something.
  2781  	//
  2782  	//   3) The blocking Read call prevents this TestHandlerPanic
  2783  	//      function from exiting before the HTTP server handler
  2784  	//      finishes crashing. If this text function exited too
  2785  	//      early (and its defer log.SetOutput(os.Stderr) ran),
  2786  	//      then the crash output could spill into the next test.
  2787  	pr, pw := io.Pipe()
  2788  	log.SetOutput(pw)
  2789  	defer log.SetOutput(os.Stderr)
  2790  	defer pw.Close()
  2791  
  2792  	var handler Handler = HandlerFunc(func(w ResponseWriter, r *Request) {
  2793  		if withHijack {
  2794  			rwc, _, err := w.(Hijacker).Hijack()
  2795  			if err != nil {
  2796  				t.Logf("unexpected error: %v", err)
  2797  			}
  2798  			defer rwc.Close()
  2799  		}
  2800  		panic(panicValue)
  2801  	})
  2802  	if wrapper != nil {
  2803  		handler = wrapper(handler)
  2804  	}
  2805  	cst := newClientServerTest(t, h2, handler)
  2806  	defer cst.close()
  2807  
  2808  	// Do a blocking read on the log output pipe so its logging
  2809  	// doesn't bleed into the next test. But wait only 5 seconds
  2810  	// for it.
  2811  	done := make(chan bool, 1)
  2812  	go func() {
  2813  		buf := make([]byte, 4<<10)
  2814  		_, err := pr.Read(buf)
  2815  		pr.Close()
  2816  		if err != nil && err != io.EOF {
  2817  			t.Error(err)
  2818  		}
  2819  		done <- true
  2820  	}()
  2821  
  2822  	_, err := cst.c.Get(cst.ts.URL)
  2823  	if err == nil {
  2824  		t.Logf("expected an error")
  2825  	}
  2826  
  2827  	if panicValue == nil {
  2828  		return
  2829  	}
  2830  
  2831  	select {
  2832  	case <-done:
  2833  		return
  2834  	case <-time.After(5 * time.Second):
  2835  		t.Fatal("expected server handler to log an error")
  2836  	}
  2837  }
  2838  
  2839  type terrorWriter struct{ t *testing.T }
  2840  
  2841  func (w terrorWriter) Write(p []byte) (int, error) {
  2842  	w.t.Errorf("%s", p)
  2843  	return len(p), nil
  2844  }
  2845  
  2846  // Issue 16456: allow writing 0 bytes on hijacked conn to test hijack
  2847  // without any log spam.
  2848  func TestServerWriteHijackZeroBytes(t *testing.T) {
  2849  	defer afterTest(t)
  2850  	done := make(chan struct{})
  2851  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  2852  		defer close(done)
  2853  		w.(Flusher).Flush()
  2854  		conn, _, err := w.(Hijacker).Hijack()
  2855  		if err != nil {
  2856  			t.Errorf("Hijack: %v", err)
  2857  			return
  2858  		}
  2859  		defer conn.Close()
  2860  		_, err = w.Write(nil)
  2861  		if err != ErrHijacked {
  2862  			t.Errorf("Write error = %v; want ErrHijacked", err)
  2863  		}
  2864  	}))
  2865  	ts.Config.ErrorLog = log.New(terrorWriter{t}, "Unexpected write: ", 0)
  2866  	ts.Start()
  2867  	defer ts.Close()
  2868  
  2869  	c := ts.Client()
  2870  	res, err := c.Get(ts.URL)
  2871  	if err != nil {
  2872  		t.Fatal(err)
  2873  	}
  2874  	res.Body.Close()
  2875  	select {
  2876  	case <-done:
  2877  	case <-time.After(5 * time.Second):
  2878  		t.Fatal("timeout")
  2879  	}
  2880  }
  2881  
  2882  func TestServerNoDate_h1(t *testing.T)        { testServerNoHeader(t, h1Mode, "Date") }
  2883  func TestServerNoDate_h2(t *testing.T)        { testServerNoHeader(t, h2Mode, "Date") }
  2884  func TestServerNoContentType_h1(t *testing.T) { testServerNoHeader(t, h1Mode, "Content-Type") }
  2885  func TestServerNoContentType_h2(t *testing.T) { testServerNoHeader(t, h2Mode, "Content-Type") }
  2886  
  2887  func testServerNoHeader(t *testing.T, h2 bool, header string) {
  2888  	setParallel(t)
  2889  	defer afterTest(t)
  2890  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2891  		w.Header()[header] = nil
  2892  		io.WriteString(w, "<html>foo</html>") // non-empty
  2893  	}))
  2894  	defer cst.close()
  2895  	res, err := cst.c.Get(cst.ts.URL)
  2896  	if err != nil {
  2897  		t.Fatal(err)
  2898  	}
  2899  	res.Body.Close()
  2900  	if got, ok := res.Header[header]; ok {
  2901  		t.Fatalf("Expected no %s header; got %q", header, got)
  2902  	}
  2903  }
  2904  
  2905  func TestStripPrefix(t *testing.T) {
  2906  	setParallel(t)
  2907  	defer afterTest(t)
  2908  	h := HandlerFunc(func(w ResponseWriter, r *Request) {
  2909  		w.Header().Set("X-Path", r.URL.Path)
  2910  		w.Header().Set("X-RawPath", r.URL.RawPath)
  2911  	})
  2912  	ts := httptest.NewServer(StripPrefix("/foo/bar", h))
  2913  	defer ts.Close()
  2914  
  2915  	c := ts.Client()
  2916  
  2917  	cases := []struct {
  2918  		reqPath string
  2919  		path    string // If empty we want a 404.
  2920  		rawPath string
  2921  	}{
  2922  		{"/foo/bar/qux", "/qux", ""},
  2923  		{"/foo/bar%2Fqux", "/qux", "%2Fqux"},
  2924  		{"/foo%2Fbar/qux", "", ""}, // Escaped prefix does not match.
  2925  		{"/bar", "", ""},           // No prefix match.
  2926  	}
  2927  	for _, tc := range cases {
  2928  		t.Run(tc.reqPath, func(t *testing.T) {
  2929  			res, err := c.Get(ts.URL + tc.reqPath)
  2930  			if err != nil {
  2931  				t.Fatal(err)
  2932  			}
  2933  			res.Body.Close()
  2934  			if tc.path == "" {
  2935  				if res.StatusCode != StatusNotFound {
  2936  					t.Errorf("got %q, want 404 Not Found", res.Status)
  2937  				}
  2938  				return
  2939  			}
  2940  			if res.StatusCode != StatusOK {
  2941  				t.Fatalf("got %q, want 200 OK", res.Status)
  2942  			}
  2943  			if g, w := res.Header.Get("X-Path"), tc.path; g != w {
  2944  				t.Errorf("got Path %q, want %q", g, w)
  2945  			}
  2946  			if g, w := res.Header.Get("X-RawPath"), tc.rawPath; g != w {
  2947  				t.Errorf("got RawPath %q, want %q", g, w)
  2948  			}
  2949  		})
  2950  	}
  2951  }
  2952  
  2953  // https://golang.org/issue/18952.
  2954  func TestStripPrefixNotModifyRequest(t *testing.T) {
  2955  	h := StripPrefix("/foo", NotFoundHandler())
  2956  	req := httptest.NewRequest("GET", "/foo/bar", nil)
  2957  	h.ServeHTTP(httptest.NewRecorder(), req)
  2958  	if req.URL.Path != "/foo/bar" {
  2959  		t.Errorf("StripPrefix should not modify the provided Request, but it did")
  2960  	}
  2961  }
  2962  
  2963  func TestRequestLimit_h1(t *testing.T) { testRequestLimit(t, h1Mode) }
  2964  func TestRequestLimit_h2(t *testing.T) { testRequestLimit(t, h2Mode) }
  2965  func testRequestLimit(t *testing.T, h2 bool) {
  2966  	setParallel(t)
  2967  	defer afterTest(t)
  2968  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  2969  		t.Fatalf("didn't expect to get request in Handler")
  2970  	}), optQuietLog)
  2971  	defer cst.close()
  2972  	req, _ := NewRequest("GET", cst.ts.URL, nil)
  2973  	var bytesPerHeader = len("header12345: val12345\r\n")
  2974  	for i := 0; i < ((DefaultMaxHeaderBytes+4096)/bytesPerHeader)+1; i++ {
  2975  		req.Header.Set(fmt.Sprintf("header%05d", i), fmt.Sprintf("val%05d", i))
  2976  	}
  2977  	res, err := cst.c.Do(req)
  2978  	if res != nil {
  2979  		defer res.Body.Close()
  2980  	}
  2981  	if h2 {
  2982  		// In HTTP/2, the result depends on a race. If the client has received the
  2983  		// server's SETTINGS before RoundTrip starts sending the request, then RoundTrip
  2984  		// will fail with an error. Otherwise, the client should receive a 431 from the
  2985  		// server.
  2986  		if err == nil && res.StatusCode != 431 {
  2987  			t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
  2988  		}
  2989  	} else {
  2990  		// In HTTP/1, we expect a 431 from the server.
  2991  		// Some HTTP clients may fail on this undefined behavior (server replying and
  2992  		// closing the connection while the request is still being written), but
  2993  		// we do support it (at least currently), so we expect a response below.
  2994  		if err != nil {
  2995  			t.Fatalf("Do: %v", err)
  2996  		}
  2997  		if res.StatusCode != 431 {
  2998  			t.Fatalf("expected 431 response status; got: %d %s", res.StatusCode, res.Status)
  2999  		}
  3000  	}
  3001  }
  3002  
  3003  type neverEnding byte
  3004  
  3005  func (b neverEnding) Read(p []byte) (n int, err error) {
  3006  	for i := range p {
  3007  		p[i] = byte(b)
  3008  	}
  3009  	return len(p), nil
  3010  }
  3011  
  3012  type countReader struct {
  3013  	r io.Reader
  3014  	n *int64
  3015  }
  3016  
  3017  func (cr countReader) Read(p []byte) (n int, err error) {
  3018  	n, err = cr.r.Read(p)
  3019  	atomic.AddInt64(cr.n, int64(n))
  3020  	return
  3021  }
  3022  
  3023  func TestRequestBodyLimit_h1(t *testing.T) { testRequestBodyLimit(t, h1Mode) }
  3024  func TestRequestBodyLimit_h2(t *testing.T) { testRequestBodyLimit(t, h2Mode) }
  3025  func testRequestBodyLimit(t *testing.T, h2 bool) {
  3026  	setParallel(t)
  3027  	defer afterTest(t)
  3028  	const limit = 1 << 20
  3029  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  3030  		r.Body = MaxBytesReader(w, r.Body, limit)
  3031  		n, err := io.Copy(io.Discard, r.Body)
  3032  		if err == nil {
  3033  			t.Errorf("expected error from io.Copy")
  3034  		}
  3035  		if n != limit {
  3036  			t.Errorf("io.Copy = %d, want %d", n, limit)
  3037  		}
  3038  		mbErr, ok := err.(*MaxBytesError)
  3039  		if !ok {
  3040  			t.Errorf("expected MaxBytesError, got %T", err)
  3041  		}
  3042  		if mbErr.Limit != limit {
  3043  			t.Errorf("MaxBytesError.Limit = %d, want %d", mbErr.Limit, limit)
  3044  		}
  3045  	}))
  3046  	defer cst.close()
  3047  
  3048  	nWritten := new(int64)
  3049  	req, _ := NewRequest("POST", cst.ts.URL, io.LimitReader(countReader{neverEnding('a'), nWritten}, limit*200))
  3050  
  3051  	// Send the POST, but don't care it succeeds or not. The
  3052  	// remote side is going to reply and then close the TCP
  3053  	// connection, and HTTP doesn't really define if that's
  3054  	// allowed or not. Some HTTP clients will get the response
  3055  	// and some (like ours, currently) will complain that the
  3056  	// request write failed, without reading the response.
  3057  	//
  3058  	// But that's okay, since what we're really testing is that
  3059  	// the remote side hung up on us before we wrote too much.
  3060  	_, _ = cst.c.Do(req)
  3061  
  3062  	if atomic.LoadInt64(nWritten) > limit*100 {
  3063  		t.Errorf("handler restricted the request body to %d bytes, but client managed to write %d",
  3064  			limit, nWritten)
  3065  	}
  3066  }
  3067  
  3068  // TestClientWriteShutdown tests that if the client shuts down the write
  3069  // side of their TCP connection, the server doesn't send a 400 Bad Request.
  3070  func TestClientWriteShutdown(t *testing.T) {
  3071  	if runtime.GOOS == "plan9" {
  3072  		t.Skip("skipping test; see https://golang.org/issue/17906")
  3073  	}
  3074  	defer afterTest(t)
  3075  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  3076  	defer ts.Close()
  3077  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3078  	if err != nil {
  3079  		t.Fatalf("Dial: %v", err)
  3080  	}
  3081  	err = conn.(*net.TCPConn).CloseWrite()
  3082  	if err != nil {
  3083  		t.Fatalf("CloseWrite: %v", err)
  3084  	}
  3085  
  3086  	bs, err := io.ReadAll(conn)
  3087  	if err != nil {
  3088  		t.Errorf("ReadAll: %v", err)
  3089  	}
  3090  	got := string(bs)
  3091  	if got != "" {
  3092  		t.Errorf("read %q from server; want nothing", got)
  3093  	}
  3094  }
  3095  
  3096  // Tests that chunked server responses that write 1 byte at a time are
  3097  // buffered before chunk headers are added, not after chunk headers.
  3098  func TestServerBufferedChunking(t *testing.T) {
  3099  	conn := new(testConn)
  3100  	conn.readBuf.Write([]byte("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"))
  3101  	conn.closec = make(chan bool, 1)
  3102  	ls := &oneConnListener{conn}
  3103  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3104  		rw.(Flusher).Flush() // force the Header to be sent, in chunking mode, not counting the length
  3105  		rw.Write([]byte{'x'})
  3106  		rw.Write([]byte{'y'})
  3107  		rw.Write([]byte{'z'})
  3108  	}))
  3109  	<-conn.closec
  3110  	if !bytes.HasSuffix(conn.writeBuf.Bytes(), []byte("\r\n\r\n3\r\nxyz\r\n0\r\n\r\n")) {
  3111  		t.Errorf("response didn't end with a single 3 byte 'xyz' chunk; got:\n%q",
  3112  			conn.writeBuf.Bytes())
  3113  	}
  3114  }
  3115  
  3116  // Tests that the server flushes its response headers out when it's
  3117  // ignoring the response body and waits a bit before forcefully
  3118  // closing the TCP connection, causing the client to get a RST.
  3119  // See https://golang.org/issue/3595
  3120  func TestServerGracefulClose(t *testing.T) {
  3121  	setParallel(t)
  3122  	defer afterTest(t)
  3123  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3124  		Error(w, "bye", StatusUnauthorized)
  3125  	}))
  3126  	defer ts.Close()
  3127  
  3128  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3129  	if err != nil {
  3130  		t.Fatal(err)
  3131  	}
  3132  	defer conn.Close()
  3133  	const bodySize = 5 << 20
  3134  	req := []byte(fmt.Sprintf("POST / HTTP/1.1\r\nHost: foo.com\r\nContent-Length: %d\r\n\r\n", bodySize))
  3135  	for i := 0; i < bodySize; i++ {
  3136  		req = append(req, 'x')
  3137  	}
  3138  	writeErr := make(chan error)
  3139  	go func() {
  3140  		_, err := conn.Write(req)
  3141  		writeErr <- err
  3142  	}()
  3143  	br := bufio.NewReader(conn)
  3144  	lineNum := 0
  3145  	for {
  3146  		line, err := br.ReadString('\n')
  3147  		if err == io.EOF {
  3148  			break
  3149  		}
  3150  		if err != nil {
  3151  			t.Fatalf("ReadLine: %v", err)
  3152  		}
  3153  		lineNum++
  3154  		if lineNum == 1 && !strings.Contains(line, "401 Unauthorized") {
  3155  			t.Errorf("Response line = %q; want a 401", line)
  3156  		}
  3157  	}
  3158  	// Wait for write to finish. This is a broken pipe on both
  3159  	// Darwin and Linux, but checking this isn't the point of
  3160  	// the test.
  3161  	<-writeErr
  3162  }
  3163  
  3164  func TestCaseSensitiveMethod_h1(t *testing.T) { testCaseSensitiveMethod(t, h1Mode) }
  3165  func TestCaseSensitiveMethod_h2(t *testing.T) { testCaseSensitiveMethod(t, h2Mode) }
  3166  func testCaseSensitiveMethod(t *testing.T, h2 bool) {
  3167  	defer afterTest(t)
  3168  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  3169  		if r.Method != "get" {
  3170  			t.Errorf(`Got method %q; want "get"`, r.Method)
  3171  		}
  3172  	}))
  3173  	defer cst.close()
  3174  	req, _ := NewRequest("get", cst.ts.URL, nil)
  3175  	res, err := cst.c.Do(req)
  3176  	if err != nil {
  3177  		t.Error(err)
  3178  		return
  3179  	}
  3180  
  3181  	res.Body.Close()
  3182  }
  3183  
  3184  // TestContentLengthZero tests that for both an HTTP/1.0 and HTTP/1.1
  3185  // request (both keep-alive), when a Handler never writes any
  3186  // response, the net/http package adds a "Content-Length: 0" response
  3187  // header.
  3188  func TestContentLengthZero(t *testing.T) {
  3189  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {}))
  3190  	defer ts.Close()
  3191  
  3192  	for _, version := range []string{"HTTP/1.0", "HTTP/1.1"} {
  3193  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3194  		if err != nil {
  3195  			t.Fatalf("error dialing: %v", err)
  3196  		}
  3197  		_, err = fmt.Fprintf(conn, "GET / %v\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n", version)
  3198  		if err != nil {
  3199  			t.Fatalf("error writing: %v", err)
  3200  		}
  3201  		req, _ := NewRequest("GET", "/", nil)
  3202  		res, err := ReadResponse(bufio.NewReader(conn), req)
  3203  		if err != nil {
  3204  			t.Fatalf("error reading response: %v", err)
  3205  		}
  3206  		if te := res.TransferEncoding; len(te) > 0 {
  3207  			t.Errorf("For version %q, Transfer-Encoding = %q; want none", version, te)
  3208  		}
  3209  		if cl := res.ContentLength; cl != 0 {
  3210  			t.Errorf("For version %q, Content-Length = %v; want 0", version, cl)
  3211  		}
  3212  		conn.Close()
  3213  	}
  3214  }
  3215  
  3216  func TestCloseNotifier(t *testing.T) {
  3217  	defer afterTest(t)
  3218  	gotReq := make(chan bool, 1)
  3219  	sawClose := make(chan bool, 1)
  3220  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  3221  		gotReq <- true
  3222  		cc := rw.(CloseNotifier).CloseNotify()
  3223  		<-cc
  3224  		sawClose <- true
  3225  	}))
  3226  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3227  	if err != nil {
  3228  		t.Fatalf("error dialing: %v", err)
  3229  	}
  3230  	diec := make(chan bool)
  3231  	go func() {
  3232  		_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
  3233  		if err != nil {
  3234  			t.Error(err)
  3235  			return
  3236  		}
  3237  		<-diec
  3238  		conn.Close()
  3239  	}()
  3240  For:
  3241  	for {
  3242  		select {
  3243  		case <-gotReq:
  3244  			diec <- true
  3245  		case <-sawClose:
  3246  			break For
  3247  		case <-time.After(5 * time.Second):
  3248  			t.Fatal("timeout")
  3249  		}
  3250  	}
  3251  	ts.Close()
  3252  }
  3253  
  3254  // Tests that a pipelined request does not cause the first request's
  3255  // Handler's CloseNotify channel to fire.
  3256  //
  3257  // Issue 13165 (where it used to deadlock), but behavior changed in Issue 23921.
  3258  func TestCloseNotifierPipelined(t *testing.T) {
  3259  	setParallel(t)
  3260  	defer afterTest(t)
  3261  	gotReq := make(chan bool, 2)
  3262  	sawClose := make(chan bool, 2)
  3263  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  3264  		gotReq <- true
  3265  		cc := rw.(CloseNotifier).CloseNotify()
  3266  		select {
  3267  		case <-cc:
  3268  			t.Error("unexpected CloseNotify")
  3269  		case <-time.After(100 * time.Millisecond):
  3270  		}
  3271  		sawClose <- true
  3272  	}))
  3273  	defer ts.Close()
  3274  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3275  	if err != nil {
  3276  		t.Fatalf("error dialing: %v", err)
  3277  	}
  3278  	diec := make(chan bool, 1)
  3279  	defer close(diec)
  3280  	go func() {
  3281  		const req = "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n"
  3282  		_, err = io.WriteString(conn, req+req) // two requests
  3283  		if err != nil {
  3284  			t.Error(err)
  3285  			return
  3286  		}
  3287  		<-diec
  3288  		conn.Close()
  3289  	}()
  3290  	reqs := 0
  3291  	closes := 0
  3292  	for {
  3293  		select {
  3294  		case <-gotReq:
  3295  			reqs++
  3296  			if reqs > 2 {
  3297  				t.Fatal("too many requests")
  3298  			}
  3299  		case <-sawClose:
  3300  			closes++
  3301  			if closes > 1 {
  3302  				return
  3303  			}
  3304  		case <-time.After(5 * time.Second):
  3305  			ts.CloseClientConnections()
  3306  			t.Fatal("timeout")
  3307  		}
  3308  	}
  3309  }
  3310  
  3311  func TestCloseNotifierChanLeak(t *testing.T) {
  3312  	defer afterTest(t)
  3313  	req := reqBytes("GET / HTTP/1.0\nHost: golang.org")
  3314  	for i := 0; i < 20; i++ {
  3315  		var output bytes.Buffer
  3316  		conn := &rwTestConn{
  3317  			Reader: bytes.NewReader(req),
  3318  			Writer: &output,
  3319  			closec: make(chan bool, 1),
  3320  		}
  3321  		ln := &oneConnListener{conn: conn}
  3322  		handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3323  			// Ignore the return value and never read from
  3324  			// it, testing that we don't leak goroutines
  3325  			// on the sending side:
  3326  			_ = rw.(CloseNotifier).CloseNotify()
  3327  		})
  3328  		go Serve(ln, handler)
  3329  		<-conn.closec
  3330  	}
  3331  }
  3332  
  3333  // Tests that we can use CloseNotifier in one request, and later call Hijack
  3334  // on a second request on the same connection.
  3335  //
  3336  // It also tests that the connReader stitches together its background
  3337  // 1-byte read for CloseNotifier when CloseNotifier doesn't fire with
  3338  // the rest of the second HTTP later.
  3339  //
  3340  // Issue 9763.
  3341  // HTTP/1-only test. (http2 doesn't have Hijack)
  3342  func TestHijackAfterCloseNotifier(t *testing.T) {
  3343  	defer afterTest(t)
  3344  	script := make(chan string, 2)
  3345  	script <- "closenotify"
  3346  	script <- "hijack"
  3347  	close(script)
  3348  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3349  		plan := <-script
  3350  		switch plan {
  3351  		default:
  3352  			panic("bogus plan; too many requests")
  3353  		case "closenotify":
  3354  			w.(CloseNotifier).CloseNotify() // discard result
  3355  			w.Header().Set("X-Addr", r.RemoteAddr)
  3356  		case "hijack":
  3357  			c, _, err := w.(Hijacker).Hijack()
  3358  			if err != nil {
  3359  				t.Errorf("Hijack in Handler: %v", err)
  3360  				return
  3361  			}
  3362  			if _, ok := c.(*net.TCPConn); !ok {
  3363  				// Verify it's not wrapped in some type.
  3364  				// Not strictly a go1 compat issue, but in practice it probably is.
  3365  				t.Errorf("type of hijacked conn is %T; want *net.TCPConn", c)
  3366  			}
  3367  			fmt.Fprintf(c, "HTTP/1.0 200 OK\r\nX-Addr: %v\r\nContent-Length: 0\r\n\r\n", r.RemoteAddr)
  3368  			c.Close()
  3369  			return
  3370  		}
  3371  	}))
  3372  	defer ts.Close()
  3373  	res1, err := Get(ts.URL)
  3374  	if err != nil {
  3375  		log.Fatal(err)
  3376  	}
  3377  	res2, err := Get(ts.URL)
  3378  	if err != nil {
  3379  		log.Fatal(err)
  3380  	}
  3381  	addr1 := res1.Header.Get("X-Addr")
  3382  	addr2 := res2.Header.Get("X-Addr")
  3383  	if addr1 == "" || addr1 != addr2 {
  3384  		t.Errorf("addr1, addr2 = %q, %q; want same", addr1, addr2)
  3385  	}
  3386  }
  3387  
  3388  func TestHijackBeforeRequestBodyRead(t *testing.T) {
  3389  	setParallel(t)
  3390  	defer afterTest(t)
  3391  	var requestBody = bytes.Repeat([]byte("a"), 1<<20)
  3392  	bodyOkay := make(chan bool, 1)
  3393  	gotCloseNotify := make(chan bool, 1)
  3394  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  3395  		defer close(bodyOkay) // caller will read false if nothing else
  3396  
  3397  		reqBody := r.Body
  3398  		r.Body = nil // to test that server.go doesn't use this value.
  3399  
  3400  		gone := w.(CloseNotifier).CloseNotify()
  3401  		slurp, err := io.ReadAll(reqBody)
  3402  		if err != nil {
  3403  			t.Errorf("Body read: %v", err)
  3404  			return
  3405  		}
  3406  		if len(slurp) != len(requestBody) {
  3407  			t.Errorf("Backend read %d request body bytes; want %d", len(slurp), len(requestBody))
  3408  			return
  3409  		}
  3410  		if !bytes.Equal(slurp, requestBody) {
  3411  			t.Error("Backend read wrong request body.") // 1MB; omitting details
  3412  			return
  3413  		}
  3414  		bodyOkay <- true
  3415  		select {
  3416  		case <-gone:
  3417  			gotCloseNotify <- true
  3418  		case <-time.After(5 * time.Second):
  3419  			gotCloseNotify <- false
  3420  		}
  3421  	}))
  3422  	defer ts.Close()
  3423  
  3424  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3425  	if err != nil {
  3426  		t.Fatal(err)
  3427  	}
  3428  	defer conn.Close()
  3429  
  3430  	fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: foo\r\nContent-Length: %d\r\n\r\n%s",
  3431  		len(requestBody), requestBody)
  3432  	if !<-bodyOkay {
  3433  		// already failed.
  3434  		return
  3435  	}
  3436  	conn.Close()
  3437  	if !<-gotCloseNotify {
  3438  		t.Error("timeout waiting for CloseNotify")
  3439  	}
  3440  }
  3441  
  3442  func TestOptions(t *testing.T) {
  3443  	uric := make(chan string, 2) // only expect 1, but leave space for 2
  3444  	mux := NewServeMux()
  3445  	mux.HandleFunc("/", func(w ResponseWriter, r *Request) {
  3446  		uric <- r.RequestURI
  3447  	})
  3448  	ts := httptest.NewServer(mux)
  3449  	defer ts.Close()
  3450  
  3451  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3452  	if err != nil {
  3453  		t.Fatal(err)
  3454  	}
  3455  	defer conn.Close()
  3456  
  3457  	// An OPTIONS * request should succeed.
  3458  	_, err = conn.Write([]byte("OPTIONS * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
  3459  	if err != nil {
  3460  		t.Fatal(err)
  3461  	}
  3462  	br := bufio.NewReader(conn)
  3463  	res, err := ReadResponse(br, &Request{Method: "OPTIONS"})
  3464  	if err != nil {
  3465  		t.Fatal(err)
  3466  	}
  3467  	if res.StatusCode != 200 {
  3468  		t.Errorf("Got non-200 response to OPTIONS *: %#v", res)
  3469  	}
  3470  
  3471  	// A GET * request on a ServeMux should fail.
  3472  	_, err = conn.Write([]byte("GET * HTTP/1.1\r\nHost: foo.com\r\n\r\n"))
  3473  	if err != nil {
  3474  		t.Fatal(err)
  3475  	}
  3476  	res, err = ReadResponse(br, &Request{Method: "GET"})
  3477  	if err != nil {
  3478  		t.Fatal(err)
  3479  	}
  3480  	if res.StatusCode != 400 {
  3481  		t.Errorf("Got non-400 response to GET *: %#v", res)
  3482  	}
  3483  
  3484  	res, err = Get(ts.URL + "/second")
  3485  	if err != nil {
  3486  		t.Fatal(err)
  3487  	}
  3488  	res.Body.Close()
  3489  	if got := <-uric; got != "/second" {
  3490  		t.Errorf("Handler saw request for %q; want /second", got)
  3491  	}
  3492  }
  3493  
  3494  // Tests regarding the ordering of Write, WriteHeader, Header, and
  3495  // Flush calls. In Go 1.0, rw.WriteHeader immediately flushed the
  3496  // (*response).header to the wire. In Go 1.1, the actual wire flush is
  3497  // delayed, so we could maybe tack on a Content-Length and better
  3498  // Content-Type after we see more (or all) of the output. To preserve
  3499  // compatibility with Go 1, we need to be careful to track which
  3500  // headers were live at the time of WriteHeader, so we write the same
  3501  // ones, even if the handler modifies them (~erroneously) after the
  3502  // first Write.
  3503  func TestHeaderToWire(t *testing.T) {
  3504  	tests := []struct {
  3505  		name    string
  3506  		handler func(ResponseWriter, *Request)
  3507  		check   func(got, logs string) error
  3508  	}{
  3509  		{
  3510  			name: "write without Header",
  3511  			handler: func(rw ResponseWriter, r *Request) {
  3512  				rw.Write([]byte("hello world"))
  3513  			},
  3514  			check: func(got, logs string) error {
  3515  				if !strings.Contains(got, "Content-Length:") {
  3516  					return errors.New("no content-length")
  3517  				}
  3518  				if !strings.Contains(got, "Content-Type: text/plain") {
  3519  					return errors.New("no content-type")
  3520  				}
  3521  				return nil
  3522  			},
  3523  		},
  3524  		{
  3525  			name: "Header mutation before write",
  3526  			handler: func(rw ResponseWriter, r *Request) {
  3527  				h := rw.Header()
  3528  				h.Set("Content-Type", "some/type")
  3529  				rw.Write([]byte("hello world"))
  3530  				h.Set("Too-Late", "bogus")
  3531  			},
  3532  			check: func(got, logs string) error {
  3533  				if !strings.Contains(got, "Content-Length:") {
  3534  					return errors.New("no content-length")
  3535  				}
  3536  				if !strings.Contains(got, "Content-Type: some/type") {
  3537  					return errors.New("wrong content-type")
  3538  				}
  3539  				if strings.Contains(got, "Too-Late") {
  3540  					return errors.New("don't want too-late header")
  3541  				}
  3542  				return nil
  3543  			},
  3544  		},
  3545  		{
  3546  			name: "write then useless Header mutation",
  3547  			handler: func(rw ResponseWriter, r *Request) {
  3548  				rw.Write([]byte("hello world"))
  3549  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3550  			},
  3551  			check: func(got, logs string) error {
  3552  				if strings.Contains(got, "Too-Late") {
  3553  					return errors.New("header appeared from after WriteHeader")
  3554  				}
  3555  				return nil
  3556  			},
  3557  		},
  3558  		{
  3559  			name: "flush then write",
  3560  			handler: func(rw ResponseWriter, r *Request) {
  3561  				rw.(Flusher).Flush()
  3562  				rw.Write([]byte("post-flush"))
  3563  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3564  			},
  3565  			check: func(got, logs string) error {
  3566  				if !strings.Contains(got, "Transfer-Encoding: chunked") {
  3567  					return errors.New("not chunked")
  3568  				}
  3569  				if strings.Contains(got, "Too-Late") {
  3570  					return errors.New("header appeared from after WriteHeader")
  3571  				}
  3572  				return nil
  3573  			},
  3574  		},
  3575  		{
  3576  			name: "header then flush",
  3577  			handler: func(rw ResponseWriter, r *Request) {
  3578  				rw.Header().Set("Content-Type", "some/type")
  3579  				rw.(Flusher).Flush()
  3580  				rw.Write([]byte("post-flush"))
  3581  				rw.Header().Set("Too-Late", "Write already wrote headers")
  3582  			},
  3583  			check: func(got, logs string) error {
  3584  				if !strings.Contains(got, "Transfer-Encoding: chunked") {
  3585  					return errors.New("not chunked")
  3586  				}
  3587  				if strings.Contains(got, "Too-Late") {
  3588  					return errors.New("header appeared from after WriteHeader")
  3589  				}
  3590  				if !strings.Contains(got, "Content-Type: some/type") {
  3591  					return errors.New("wrong content-type")
  3592  				}
  3593  				return nil
  3594  			},
  3595  		},
  3596  		{
  3597  			name: "sniff-on-first-write content-type",
  3598  			handler: func(rw ResponseWriter, r *Request) {
  3599  				rw.Write([]byte("<html><head></head><body>some html</body></html>"))
  3600  				rw.Header().Set("Content-Type", "x/wrong")
  3601  			},
  3602  			check: func(got, logs string) error {
  3603  				if !strings.Contains(got, "Content-Type: text/html") {
  3604  					return errors.New("wrong content-type; want html")
  3605  				}
  3606  				return nil
  3607  			},
  3608  		},
  3609  		{
  3610  			name: "explicit content-type wins",
  3611  			handler: func(rw ResponseWriter, r *Request) {
  3612  				rw.Header().Set("Content-Type", "some/type")
  3613  				rw.Write([]byte("<html><head></head><body>some html</body></html>"))
  3614  			},
  3615  			check: func(got, logs string) error {
  3616  				if !strings.Contains(got, "Content-Type: some/type") {
  3617  					return errors.New("wrong content-type; want html")
  3618  				}
  3619  				return nil
  3620  			},
  3621  		},
  3622  		{
  3623  			name: "empty handler",
  3624  			handler: func(rw ResponseWriter, r *Request) {
  3625  			},
  3626  			check: func(got, logs string) error {
  3627  				if !strings.Contains(got, "Content-Length: 0") {
  3628  					return errors.New("want 0 content-length")
  3629  				}
  3630  				return nil
  3631  			},
  3632  		},
  3633  		{
  3634  			name: "only Header, no write",
  3635  			handler: func(rw ResponseWriter, r *Request) {
  3636  				rw.Header().Set("Some-Header", "some-value")
  3637  			},
  3638  			check: func(got, logs string) error {
  3639  				if !strings.Contains(got, "Some-Header") {
  3640  					return errors.New("didn't get header")
  3641  				}
  3642  				return nil
  3643  			},
  3644  		},
  3645  		{
  3646  			name: "WriteHeader call",
  3647  			handler: func(rw ResponseWriter, r *Request) {
  3648  				rw.WriteHeader(404)
  3649  				rw.Header().Set("Too-Late", "some-value")
  3650  			},
  3651  			check: func(got, logs string) error {
  3652  				if !strings.Contains(got, "404") {
  3653  					return errors.New("wrong status")
  3654  				}
  3655  				if strings.Contains(got, "Too-Late") {
  3656  					return errors.New("shouldn't have seen Too-Late")
  3657  				}
  3658  				return nil
  3659  			},
  3660  		},
  3661  	}
  3662  	for _, tc := range tests {
  3663  		ht := newHandlerTest(HandlerFunc(tc.handler))
  3664  		got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org")
  3665  		logs := ht.logbuf.String()
  3666  		if err := tc.check(got, logs); err != nil {
  3667  			t.Errorf("%s: %v\nGot response:\n%s\n\n%s", tc.name, err, got, logs)
  3668  		}
  3669  	}
  3670  }
  3671  
  3672  type errorListener struct {
  3673  	errs []error
  3674  }
  3675  
  3676  func (l *errorListener) Accept() (c net.Conn, err error) {
  3677  	if len(l.errs) == 0 {
  3678  		return nil, io.EOF
  3679  	}
  3680  	err = l.errs[0]
  3681  	l.errs = l.errs[1:]
  3682  	return
  3683  }
  3684  
  3685  func (l *errorListener) Close() error {
  3686  	return nil
  3687  }
  3688  
  3689  func (l *errorListener) Addr() net.Addr {
  3690  	return dummyAddr("test-address")
  3691  }
  3692  
  3693  func TestAcceptMaxFds(t *testing.T) {
  3694  	setParallel(t)
  3695  
  3696  	ln := &errorListener{[]error{
  3697  		&net.OpError{
  3698  			Op:  "accept",
  3699  			Err: syscall.EMFILE,
  3700  		}}}
  3701  	server := &Server{
  3702  		Handler:  HandlerFunc(HandlerFunc(func(ResponseWriter, *Request) {})),
  3703  		ErrorLog: log.New(io.Discard, "", 0), // noisy otherwise
  3704  	}
  3705  	err := server.Serve(ln)
  3706  	if err != io.EOF {
  3707  		t.Errorf("got error %v, want EOF", err)
  3708  	}
  3709  }
  3710  
  3711  func TestWriteAfterHijack(t *testing.T) {
  3712  	req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
  3713  	var buf bytes.Buffer
  3714  	wrotec := make(chan bool, 1)
  3715  	conn := &rwTestConn{
  3716  		Reader: bytes.NewReader(req),
  3717  		Writer: &buf,
  3718  		closec: make(chan bool, 1),
  3719  	}
  3720  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3721  		conn, bufrw, err := rw.(Hijacker).Hijack()
  3722  		if err != nil {
  3723  			t.Error(err)
  3724  			return
  3725  		}
  3726  		go func() {
  3727  			bufrw.Write([]byte("[hijack-to-bufw]"))
  3728  			bufrw.Flush()
  3729  			conn.Write([]byte("[hijack-to-conn]"))
  3730  			conn.Close()
  3731  			wrotec <- true
  3732  		}()
  3733  	})
  3734  	ln := &oneConnListener{conn: conn}
  3735  	go Serve(ln, handler)
  3736  	<-conn.closec
  3737  	<-wrotec
  3738  	if g, w := buf.String(), "[hijack-to-bufw][hijack-to-conn]"; g != w {
  3739  		t.Errorf("wrote %q; want %q", g, w)
  3740  	}
  3741  }
  3742  
  3743  func TestDoubleHijack(t *testing.T) {
  3744  	req := reqBytes("GET / HTTP/1.1\nHost: golang.org")
  3745  	var buf bytes.Buffer
  3746  	conn := &rwTestConn{
  3747  		Reader: bytes.NewReader(req),
  3748  		Writer: &buf,
  3749  		closec: make(chan bool, 1),
  3750  	}
  3751  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  3752  		conn, _, err := rw.(Hijacker).Hijack()
  3753  		if err != nil {
  3754  			t.Error(err)
  3755  			return
  3756  		}
  3757  		_, _, err = rw.(Hijacker).Hijack()
  3758  		if err == nil {
  3759  			t.Errorf("got err = nil;  want err != nil")
  3760  		}
  3761  		conn.Close()
  3762  	})
  3763  	ln := &oneConnListener{conn: conn}
  3764  	go Serve(ln, handler)
  3765  	<-conn.closec
  3766  }
  3767  
  3768  // https://golang.org/issue/5955
  3769  // Note that this does not test the "request too large"
  3770  // exit path from the http server. This is intentional;
  3771  // not sending Connection: close is just a minor wire
  3772  // optimization and is pointless if dealing with a
  3773  // badly behaved client.
  3774  func TestHTTP10ConnectionHeader(t *testing.T) {
  3775  	defer afterTest(t)
  3776  
  3777  	mux := NewServeMux()
  3778  	mux.Handle("/", HandlerFunc(func(ResponseWriter, *Request) {}))
  3779  	ts := httptest.NewServer(mux)
  3780  	defer ts.Close()
  3781  
  3782  	// net/http uses HTTP/1.1 for requests, so write requests manually
  3783  	tests := []struct {
  3784  		req    string   // raw http request
  3785  		expect []string // expected Connection header(s)
  3786  	}{
  3787  		{
  3788  			req:    "GET / HTTP/1.0\r\n\r\n",
  3789  			expect: nil,
  3790  		},
  3791  		{
  3792  			req:    "OPTIONS * HTTP/1.0\r\n\r\n",
  3793  			expect: nil,
  3794  		},
  3795  		{
  3796  			req:    "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n",
  3797  			expect: []string{"keep-alive"},
  3798  		},
  3799  	}
  3800  
  3801  	for _, tt := range tests {
  3802  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  3803  		if err != nil {
  3804  			t.Fatal("dial err:", err)
  3805  		}
  3806  
  3807  		_, err = fmt.Fprint(conn, tt.req)
  3808  		if err != nil {
  3809  			t.Fatal("conn write err:", err)
  3810  		}
  3811  
  3812  		resp, err := ReadResponse(bufio.NewReader(conn), &Request{Method: "GET"})
  3813  		if err != nil {
  3814  			t.Fatal("ReadResponse err:", err)
  3815  		}
  3816  		conn.Close()
  3817  		resp.Body.Close()
  3818  
  3819  		got := resp.Header["Connection"]
  3820  		if !reflect.DeepEqual(got, tt.expect) {
  3821  			t.Errorf("wrong Connection headers for request %q. Got %q expect %q", tt.req, got, tt.expect)
  3822  		}
  3823  	}
  3824  }
  3825  
  3826  // See golang.org/issue/5660
  3827  func TestServerReaderFromOrder_h1(t *testing.T) { testServerReaderFromOrder(t, h1Mode) }
  3828  func TestServerReaderFromOrder_h2(t *testing.T) { testServerReaderFromOrder(t, h2Mode) }
  3829  func testServerReaderFromOrder(t *testing.T, h2 bool) {
  3830  	setParallel(t)
  3831  	defer afterTest(t)
  3832  	pr, pw := io.Pipe()
  3833  	const size = 3 << 20
  3834  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3835  		rw.Header().Set("Content-Type", "text/plain") // prevent sniffing path
  3836  		done := make(chan bool)
  3837  		go func() {
  3838  			io.Copy(rw, pr)
  3839  			close(done)
  3840  		}()
  3841  		time.Sleep(25 * time.Millisecond) // give Copy a chance to break things
  3842  		n, err := io.Copy(io.Discard, req.Body)
  3843  		if err != nil {
  3844  			t.Errorf("handler Copy: %v", err)
  3845  			return
  3846  		}
  3847  		if n != size {
  3848  			t.Errorf("handler Copy = %d; want %d", n, size)
  3849  		}
  3850  		pw.Write([]byte("hi"))
  3851  		pw.Close()
  3852  		<-done
  3853  	}))
  3854  	defer cst.close()
  3855  
  3856  	req, err := NewRequest("POST", cst.ts.URL, io.LimitReader(neverEnding('a'), size))
  3857  	if err != nil {
  3858  		t.Fatal(err)
  3859  	}
  3860  	res, err := cst.c.Do(req)
  3861  	if err != nil {
  3862  		t.Fatal(err)
  3863  	}
  3864  	all, err := io.ReadAll(res.Body)
  3865  	if err != nil {
  3866  		t.Fatal(err)
  3867  	}
  3868  	res.Body.Close()
  3869  	if string(all) != "hi" {
  3870  		t.Errorf("Body = %q; want hi", all)
  3871  	}
  3872  }
  3873  
  3874  // Issue 6157, Issue 6685
  3875  func TestCodesPreventingContentTypeAndBody(t *testing.T) {
  3876  	for _, code := range []int{StatusNotModified, StatusNoContent} {
  3877  		ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  3878  			if r.URL.Path == "/header" {
  3879  				w.Header().Set("Content-Length", "123")
  3880  			}
  3881  			w.WriteHeader(code)
  3882  			if r.URL.Path == "/more" {
  3883  				w.Write([]byte("stuff"))
  3884  			}
  3885  		}))
  3886  		for _, req := range []string{
  3887  			"GET / HTTP/1.0",
  3888  			"GET /header HTTP/1.0",
  3889  			"GET /more HTTP/1.0",
  3890  			"GET / HTTP/1.1\nHost: foo",
  3891  			"GET /header HTTP/1.1\nHost: foo",
  3892  			"GET /more HTTP/1.1\nHost: foo",
  3893  		} {
  3894  			got := ht.rawResponse(req)
  3895  			wantStatus := fmt.Sprintf("%d %s", code, StatusText(code))
  3896  			if !strings.Contains(got, wantStatus) {
  3897  				t.Errorf("Code %d: Wanted %q Modified for %q: %s", code, wantStatus, req, got)
  3898  			} else if strings.Contains(got, "Content-Length") {
  3899  				t.Errorf("Code %d: Got a Content-Length from %q: %s", code, req, got)
  3900  			} else if strings.Contains(got, "stuff") {
  3901  				t.Errorf("Code %d: Response contains a body from %q: %s", code, req, got)
  3902  			}
  3903  		}
  3904  	}
  3905  }
  3906  
  3907  func TestContentTypeOkayOn204(t *testing.T) {
  3908  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  3909  		w.Header().Set("Content-Length", "123") // suppressed
  3910  		w.Header().Set("Content-Type", "foo/bar")
  3911  		w.WriteHeader(204)
  3912  	}))
  3913  	got := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  3914  	if !strings.Contains(got, "Content-Type: foo/bar") {
  3915  		t.Errorf("Response = %q; want Content-Type: foo/bar", got)
  3916  	}
  3917  	if strings.Contains(got, "Content-Length: 123") {
  3918  		t.Errorf("Response = %q; don't want a Content-Length", got)
  3919  	}
  3920  }
  3921  
  3922  // Issue 6995
  3923  // A server Handler can receive a Request, and then turn around and
  3924  // give a copy of that Request.Body out to the Transport (e.g. any
  3925  // proxy).  So then two people own that Request.Body (both the server
  3926  // and the http client), and both think they can close it on failure.
  3927  // Therefore, all incoming server requests Bodies need to be thread-safe.
  3928  func TestTransportAndServerSharedBodyRace_h1(t *testing.T) {
  3929  	testTransportAndServerSharedBodyRace(t, h1Mode)
  3930  }
  3931  func TestTransportAndServerSharedBodyRace_h2(t *testing.T) {
  3932  	testTransportAndServerSharedBodyRace(t, h2Mode)
  3933  }
  3934  func testTransportAndServerSharedBodyRace(t *testing.T, h2 bool) {
  3935  	setParallel(t)
  3936  	defer afterTest(t)
  3937  
  3938  	const bodySize = 1 << 20
  3939  
  3940  	// errorf is like t.Errorf, but also writes to println. When
  3941  	// this test fails, it hangs. This helps debugging and I've
  3942  	// added this enough times "temporarily".  It now gets added
  3943  	// full time.
  3944  	errorf := func(format string, args ...any) {
  3945  		v := fmt.Sprintf(format, args...)
  3946  		println(v)
  3947  		t.Error(v)
  3948  	}
  3949  
  3950  	unblockBackend := make(chan bool)
  3951  	backend := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3952  		gone := rw.(CloseNotifier).CloseNotify()
  3953  		didCopy := make(chan any)
  3954  		go func() {
  3955  			n, err := io.CopyN(rw, req.Body, bodySize)
  3956  			didCopy <- []any{n, err}
  3957  		}()
  3958  		isGone := false
  3959  	Loop:
  3960  		for {
  3961  			select {
  3962  			case <-didCopy:
  3963  				break Loop
  3964  			case <-gone:
  3965  				isGone = true
  3966  			case <-time.After(time.Second):
  3967  				println("1 second passes in backend, proxygone=", isGone)
  3968  			}
  3969  		}
  3970  		<-unblockBackend
  3971  	}))
  3972  	var quitTimer *time.Timer
  3973  	defer func() { quitTimer.Stop() }()
  3974  	defer backend.close()
  3975  
  3976  	backendRespc := make(chan *Response, 1)
  3977  	var proxy *clientServerTest
  3978  	proxy = newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  3979  		req2, _ := NewRequest("POST", backend.ts.URL, req.Body)
  3980  		req2.ContentLength = bodySize
  3981  		cancel := make(chan struct{})
  3982  		req2.Cancel = cancel
  3983  
  3984  		bresp, err := proxy.c.Do(req2)
  3985  		if err != nil {
  3986  			errorf("Proxy outbound request: %v", err)
  3987  			return
  3988  		}
  3989  		_, err = io.CopyN(io.Discard, bresp.Body, bodySize/2)
  3990  		if err != nil {
  3991  			errorf("Proxy copy error: %v", err)
  3992  			return
  3993  		}
  3994  		backendRespc <- bresp // to close later
  3995  
  3996  		// Try to cause a race: Both the Transport and the proxy handler's Server
  3997  		// will try to read/close req.Body (aka req2.Body)
  3998  		if h2 {
  3999  			close(cancel)
  4000  		} else {
  4001  			proxy.c.Transport.(*Transport).CancelRequest(req2)
  4002  		}
  4003  		rw.Write([]byte("OK"))
  4004  	}))
  4005  	defer proxy.close()
  4006  	defer func() {
  4007  		// Before we shut down our two httptest.Servers, start a timer.
  4008  		// We choose 7 seconds because httptest.Server starts logging
  4009  		// warnings to stderr at 5 seconds. If we don't disarm this bomb
  4010  		// in 7 seconds (after the two httptest.Server.Close calls above),
  4011  		// then we explode with stacks.
  4012  		quitTimer = time.AfterFunc(7*time.Second, func() {
  4013  			debug.SetTraceback("ALL")
  4014  			stacks := make([]byte, 1<<20)
  4015  			stacks = stacks[:runtime.Stack(stacks, true)]
  4016  			fmt.Fprintf(os.Stderr, "%s", stacks)
  4017  			log.Fatalf("Timeout.")
  4018  		})
  4019  	}()
  4020  
  4021  	defer close(unblockBackend)
  4022  	req, _ := NewRequest("POST", proxy.ts.URL, io.LimitReader(neverEnding('a'), bodySize))
  4023  	res, err := proxy.c.Do(req)
  4024  	if err != nil {
  4025  		t.Fatalf("Original request: %v", err)
  4026  	}
  4027  
  4028  	// Cleanup, so we don't leak goroutines.
  4029  	res.Body.Close()
  4030  	select {
  4031  	case res := <-backendRespc:
  4032  		res.Body.Close()
  4033  	default:
  4034  		// We failed earlier. (e.g. on proxy.c.Do(req2))
  4035  	}
  4036  }
  4037  
  4038  // Test that a hanging Request.Body.Read from another goroutine can't
  4039  // cause the Handler goroutine's Request.Body.Close to block.
  4040  // See issue 7121.
  4041  func TestRequestBodyCloseDoesntBlock(t *testing.T) {
  4042  	if testing.Short() {
  4043  		t.Skip("skipping in -short mode")
  4044  	}
  4045  	defer afterTest(t)
  4046  
  4047  	readErrCh := make(chan error, 1)
  4048  	errCh := make(chan error, 2)
  4049  
  4050  	server := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  4051  		go func(body io.Reader) {
  4052  			_, err := body.Read(make([]byte, 100))
  4053  			readErrCh <- err
  4054  		}(req.Body)
  4055  		time.Sleep(500 * time.Millisecond)
  4056  	}))
  4057  	defer server.Close()
  4058  
  4059  	closeConn := make(chan bool)
  4060  	defer close(closeConn)
  4061  	go func() {
  4062  		conn, err := net.Dial("tcp", server.Listener.Addr().String())
  4063  		if err != nil {
  4064  			errCh <- err
  4065  			return
  4066  		}
  4067  		defer conn.Close()
  4068  		_, err = conn.Write([]byte("POST / HTTP/1.1\r\nConnection: close\r\nHost: foo\r\nContent-Length: 100000\r\n\r\n"))
  4069  		if err != nil {
  4070  			errCh <- err
  4071  			return
  4072  		}
  4073  		// And now just block, making the server block on our
  4074  		// 100000 bytes of body that will never arrive.
  4075  		<-closeConn
  4076  	}()
  4077  	select {
  4078  	case err := <-readErrCh:
  4079  		if err == nil {
  4080  			t.Error("Read was nil. Expected error.")
  4081  		}
  4082  	case err := <-errCh:
  4083  		t.Error(err)
  4084  	case <-time.After(5 * time.Second):
  4085  		t.Error("timeout")
  4086  	}
  4087  }
  4088  
  4089  // test that ResponseWriter implements io.StringWriter.
  4090  func TestResponseWriterWriteString(t *testing.T) {
  4091  	okc := make(chan bool, 1)
  4092  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4093  		_, ok := w.(io.StringWriter)
  4094  		okc <- ok
  4095  	}))
  4096  	ht.rawResponse("GET / HTTP/1.0")
  4097  	select {
  4098  	case ok := <-okc:
  4099  		if !ok {
  4100  			t.Error("ResponseWriter did not implement io.StringWriter")
  4101  		}
  4102  	default:
  4103  		t.Error("handler was never called")
  4104  	}
  4105  }
  4106  
  4107  func TestAppendTime(t *testing.T) {
  4108  	var b [len(TimeFormat)]byte
  4109  	t1 := time.Date(2013, 9, 21, 15, 41, 0, 0, time.FixedZone("CEST", 2*60*60))
  4110  	res := ExportAppendTime(b[:0], t1)
  4111  	t2, err := ParseTime(string(res))
  4112  	if err != nil {
  4113  		t.Fatalf("Error parsing time: %s", err)
  4114  	}
  4115  	if !t1.Equal(t2) {
  4116  		t.Fatalf("Times differ; expected: %v, got %v (%s)", t1, t2, string(res))
  4117  	}
  4118  }
  4119  
  4120  func TestServerConnState(t *testing.T) {
  4121  	setParallel(t)
  4122  	defer afterTest(t)
  4123  	handler := map[string]func(w ResponseWriter, r *Request){
  4124  		"/": func(w ResponseWriter, r *Request) {
  4125  			fmt.Fprintf(w, "Hello.")
  4126  		},
  4127  		"/close": func(w ResponseWriter, r *Request) {
  4128  			w.Header().Set("Connection", "close")
  4129  			fmt.Fprintf(w, "Hello.")
  4130  		},
  4131  		"/hijack": func(w ResponseWriter, r *Request) {
  4132  			c, _, _ := w.(Hijacker).Hijack()
  4133  			c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
  4134  			c.Close()
  4135  		},
  4136  		"/hijack-panic": func(w ResponseWriter, r *Request) {
  4137  			c, _, _ := w.(Hijacker).Hijack()
  4138  			c.Write([]byte("HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello."))
  4139  			c.Close()
  4140  			panic("intentional panic")
  4141  		},
  4142  	}
  4143  
  4144  	// A stateLog is a log of states over the lifetime of a connection.
  4145  	type stateLog struct {
  4146  		active   net.Conn // The connection for which the log is recorded; set to the first connection seen in StateNew.
  4147  		got      []ConnState
  4148  		want     []ConnState
  4149  		complete chan<- struct{} // If non-nil, closed when either 'got' is equal to 'want', or 'got' is no longer a prefix of 'want'.
  4150  	}
  4151  	activeLog := make(chan *stateLog, 1)
  4152  
  4153  	// wantLog invokes doRequests, then waits for the resulting connection to
  4154  	// either pass through the sequence of states in want or enter a state outside
  4155  	// of that sequence.
  4156  	wantLog := func(doRequests func(), want ...ConnState) {
  4157  		t.Helper()
  4158  		complete := make(chan struct{})
  4159  		activeLog <- &stateLog{want: want, complete: complete}
  4160  
  4161  		doRequests()
  4162  
  4163  		stateDelay := 5 * time.Second
  4164  		if deadline, ok := t.Deadline(); ok {
  4165  			// Allow an arbitrarily long delay.
  4166  			// This test was observed to be flaky on the darwin-arm64-corellium builder,
  4167  			// so we're increasing the deadline to see if it starts passing.
  4168  			// See https://golang.org/issue/37322.
  4169  			const arbitraryCleanupMargin = 1 * time.Second
  4170  			stateDelay = time.Until(deadline) - arbitraryCleanupMargin
  4171  		}
  4172  		timer := time.NewTimer(stateDelay)
  4173  		select {
  4174  		case <-timer.C:
  4175  			t.Errorf("Timed out after %v waiting for connection to change state.", stateDelay)
  4176  		case <-complete:
  4177  			timer.Stop()
  4178  		}
  4179  		sl := <-activeLog
  4180  		if !reflect.DeepEqual(sl.got, sl.want) {
  4181  			t.Errorf("Request(s) produced unexpected state sequence.\nGot:  %v\nWant: %v", sl.got, sl.want)
  4182  		}
  4183  		// Don't return sl to activeLog: we don't expect any further states after
  4184  		// this point, and want to keep the ConnState callback blocked until the
  4185  		// next call to wantLog.
  4186  	}
  4187  
  4188  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4189  		handler[r.URL.Path](w, r)
  4190  	}))
  4191  	defer func() {
  4192  		activeLog <- &stateLog{} // If the test failed, allow any remaining ConnState callbacks to complete.
  4193  		ts.Close()
  4194  	}()
  4195  
  4196  	ts.Config.ErrorLog = log.New(io.Discard, "", 0)
  4197  	ts.Config.ConnState = func(c net.Conn, state ConnState) {
  4198  		if c == nil {
  4199  			t.Errorf("nil conn seen in state %s", state)
  4200  			return
  4201  		}
  4202  		sl := <-activeLog
  4203  		if sl.active == nil && state == StateNew {
  4204  			sl.active = c
  4205  		} else if sl.active != c {
  4206  			t.Errorf("unexpected conn in state %s", state)
  4207  			activeLog <- sl
  4208  			return
  4209  		}
  4210  		sl.got = append(sl.got, state)
  4211  		if sl.complete != nil && (len(sl.got) >= len(sl.want) || !reflect.DeepEqual(sl.got, sl.want[:len(sl.got)])) {
  4212  			close(sl.complete)
  4213  			sl.complete = nil
  4214  		}
  4215  		activeLog <- sl
  4216  	}
  4217  
  4218  	ts.Start()
  4219  	c := ts.Client()
  4220  
  4221  	mustGet := func(url string, headers ...string) {
  4222  		t.Helper()
  4223  		req, err := NewRequest("GET", url, nil)
  4224  		if err != nil {
  4225  			t.Fatal(err)
  4226  		}
  4227  		for len(headers) > 0 {
  4228  			req.Header.Add(headers[0], headers[1])
  4229  			headers = headers[2:]
  4230  		}
  4231  		res, err := c.Do(req)
  4232  		if err != nil {
  4233  			t.Errorf("Error fetching %s: %v", url, err)
  4234  			return
  4235  		}
  4236  		_, err = io.ReadAll(res.Body)
  4237  		defer res.Body.Close()
  4238  		if err != nil {
  4239  			t.Errorf("Error reading %s: %v", url, err)
  4240  		}
  4241  	}
  4242  
  4243  	wantLog(func() {
  4244  		mustGet(ts.URL + "/")
  4245  		mustGet(ts.URL + "/close")
  4246  	}, StateNew, StateActive, StateIdle, StateActive, StateClosed)
  4247  
  4248  	wantLog(func() {
  4249  		mustGet(ts.URL + "/")
  4250  		mustGet(ts.URL+"/", "Connection", "close")
  4251  	}, StateNew, StateActive, StateIdle, StateActive, StateClosed)
  4252  
  4253  	wantLog(func() {
  4254  		mustGet(ts.URL + "/hijack")
  4255  	}, StateNew, StateActive, StateHijacked)
  4256  
  4257  	wantLog(func() {
  4258  		mustGet(ts.URL + "/hijack-panic")
  4259  	}, StateNew, StateActive, StateHijacked)
  4260  
  4261  	wantLog(func() {
  4262  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4263  		if err != nil {
  4264  			t.Fatal(err)
  4265  		}
  4266  		c.Close()
  4267  	}, StateNew, StateClosed)
  4268  
  4269  	wantLog(func() {
  4270  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4271  		if err != nil {
  4272  			t.Fatal(err)
  4273  		}
  4274  		if _, err := io.WriteString(c, "BOGUS REQUEST\r\n\r\n"); err != nil {
  4275  			t.Fatal(err)
  4276  		}
  4277  		c.Read(make([]byte, 1)) // block until server hangs up on us
  4278  		c.Close()
  4279  	}, StateNew, StateActive, StateClosed)
  4280  
  4281  	wantLog(func() {
  4282  		c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4283  		if err != nil {
  4284  			t.Fatal(err)
  4285  		}
  4286  		if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
  4287  			t.Fatal(err)
  4288  		}
  4289  		res, err := ReadResponse(bufio.NewReader(c), nil)
  4290  		if err != nil {
  4291  			t.Fatal(err)
  4292  		}
  4293  		if _, err := io.Copy(io.Discard, res.Body); err != nil {
  4294  			t.Fatal(err)
  4295  		}
  4296  		c.Close()
  4297  	}, StateNew, StateActive, StateIdle, StateClosed)
  4298  }
  4299  
  4300  func TestServerKeepAlivesEnabled(t *testing.T) {
  4301  	defer afterTest(t)
  4302  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
  4303  	ts.Config.SetKeepAlivesEnabled(false)
  4304  	ts.Start()
  4305  	defer ts.Close()
  4306  	res, err := Get(ts.URL)
  4307  	if err != nil {
  4308  		t.Fatal(err)
  4309  	}
  4310  	defer res.Body.Close()
  4311  	if !res.Close {
  4312  		t.Errorf("Body.Close == false; want true")
  4313  	}
  4314  }
  4315  
  4316  // golang.org/issue/7856
  4317  func TestServerEmptyBodyRace_h1(t *testing.T) { testServerEmptyBodyRace(t, h1Mode) }
  4318  func TestServerEmptyBodyRace_h2(t *testing.T) { testServerEmptyBodyRace(t, h2Mode) }
  4319  func testServerEmptyBodyRace(t *testing.T, h2 bool) {
  4320  	setParallel(t)
  4321  	defer afterTest(t)
  4322  	var n int32
  4323  	cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, req *Request) {
  4324  		atomic.AddInt32(&n, 1)
  4325  	}), optQuietLog)
  4326  	defer cst.close()
  4327  	var wg sync.WaitGroup
  4328  	const reqs = 20
  4329  	for i := 0; i < reqs; i++ {
  4330  		wg.Add(1)
  4331  		go func() {
  4332  			defer wg.Done()
  4333  			res, err := cst.c.Get(cst.ts.URL)
  4334  			if err != nil {
  4335  				// Try to deflake spurious "connection reset by peer" under load.
  4336  				// See golang.org/issue/22540.
  4337  				time.Sleep(10 * time.Millisecond)
  4338  				res, err = cst.c.Get(cst.ts.URL)
  4339  				if err != nil {
  4340  					t.Error(err)
  4341  					return
  4342  				}
  4343  			}
  4344  			defer res.Body.Close()
  4345  			_, err = io.Copy(io.Discard, res.Body)
  4346  			if err != nil {
  4347  				t.Error(err)
  4348  				return
  4349  			}
  4350  		}()
  4351  	}
  4352  	wg.Wait()
  4353  	if got := atomic.LoadInt32(&n); got != reqs {
  4354  		t.Errorf("handler ran %d times; want %d", got, reqs)
  4355  	}
  4356  }
  4357  
  4358  func TestServerConnStateNew(t *testing.T) {
  4359  	sawNew := false // if the test is buggy, we'll race on this variable.
  4360  	srv := &Server{
  4361  		ConnState: func(c net.Conn, state ConnState) {
  4362  			if state == StateNew {
  4363  				sawNew = true // testing that this write isn't racy
  4364  			}
  4365  		},
  4366  		Handler: HandlerFunc(func(w ResponseWriter, r *Request) {}), // irrelevant
  4367  	}
  4368  	srv.Serve(&oneConnListener{
  4369  		conn: &rwTestConn{
  4370  			Reader: strings.NewReader("GET / HTTP/1.1\r\nHost: foo\r\n\r\n"),
  4371  			Writer: io.Discard,
  4372  		},
  4373  	})
  4374  	if !sawNew { // testing that this read isn't racy
  4375  		t.Error("StateNew not seen")
  4376  	}
  4377  }
  4378  
  4379  type closeWriteTestConn struct {
  4380  	rwTestConn
  4381  	didCloseWrite bool
  4382  }
  4383  
  4384  func (c *closeWriteTestConn) CloseWrite() error {
  4385  	c.didCloseWrite = true
  4386  	return nil
  4387  }
  4388  
  4389  func TestCloseWrite(t *testing.T) {
  4390  	setParallel(t)
  4391  	var srv Server
  4392  	var testConn closeWriteTestConn
  4393  	c := ExportServerNewConn(&srv, &testConn)
  4394  	ExportCloseWriteAndWait(c)
  4395  	if !testConn.didCloseWrite {
  4396  		t.Error("didn't see CloseWrite call")
  4397  	}
  4398  }
  4399  
  4400  // This verifies that a handler can Flush and then Hijack.
  4401  //
  4402  // A similar test crashed once during development, but it was only
  4403  // testing this tangentially and temporarily until another TODO was
  4404  // fixed.
  4405  //
  4406  // So add an explicit test for this.
  4407  func TestServerFlushAndHijack(t *testing.T) {
  4408  	defer afterTest(t)
  4409  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4410  		io.WriteString(w, "Hello, ")
  4411  		w.(Flusher).Flush()
  4412  		conn, buf, _ := w.(Hijacker).Hijack()
  4413  		buf.WriteString("6\r\nworld!\r\n0\r\n\r\n")
  4414  		if err := buf.Flush(); err != nil {
  4415  			t.Error(err)
  4416  		}
  4417  		if err := conn.Close(); err != nil {
  4418  			t.Error(err)
  4419  		}
  4420  	}))
  4421  	defer ts.Close()
  4422  	res, err := Get(ts.URL)
  4423  	if err != nil {
  4424  		t.Fatal(err)
  4425  	}
  4426  	defer res.Body.Close()
  4427  	all, err := io.ReadAll(res.Body)
  4428  	if err != nil {
  4429  		t.Fatal(err)
  4430  	}
  4431  	if want := "Hello, world!"; string(all) != want {
  4432  		t.Errorf("Got %q; want %q", all, want)
  4433  	}
  4434  }
  4435  
  4436  // golang.org/issue/8534 -- the Server shouldn't reuse a connection
  4437  // for keep-alive after it's seen any Write error (e.g. a timeout) on
  4438  // that net.Conn.
  4439  //
  4440  // To test, verify we don't timeout or see fewer unique client
  4441  // addresses (== unique connections) than requests.
  4442  func TestServerKeepAliveAfterWriteError(t *testing.T) {
  4443  	if testing.Short() {
  4444  		t.Skip("skipping in -short mode")
  4445  	}
  4446  	defer afterTest(t)
  4447  	const numReq = 3
  4448  	addrc := make(chan string, numReq)
  4449  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4450  		addrc <- r.RemoteAddr
  4451  		time.Sleep(500 * time.Millisecond)
  4452  		w.(Flusher).Flush()
  4453  	}))
  4454  	ts.Config.WriteTimeout = 250 * time.Millisecond
  4455  	ts.Start()
  4456  	defer ts.Close()
  4457  
  4458  	errc := make(chan error, numReq)
  4459  	go func() {
  4460  		defer close(errc)
  4461  		for i := 0; i < numReq; i++ {
  4462  			res, err := Get(ts.URL)
  4463  			if res != nil {
  4464  				res.Body.Close()
  4465  			}
  4466  			errc <- err
  4467  		}
  4468  	}()
  4469  
  4470  	timeout := time.NewTimer(numReq * 2 * time.Second) // 4x overkill
  4471  	defer timeout.Stop()
  4472  	addrSeen := map[string]bool{}
  4473  	numOkay := 0
  4474  	for {
  4475  		select {
  4476  		case v := <-addrc:
  4477  			addrSeen[v] = true
  4478  		case err, ok := <-errc:
  4479  			if !ok {
  4480  				if len(addrSeen) != numReq {
  4481  					t.Errorf("saw %d unique client addresses; want %d", len(addrSeen), numReq)
  4482  				}
  4483  				if numOkay != 0 {
  4484  					t.Errorf("got %d successful client requests; want 0", numOkay)
  4485  				}
  4486  				return
  4487  			}
  4488  			if err == nil {
  4489  				numOkay++
  4490  			}
  4491  		case <-timeout.C:
  4492  			t.Fatal("timeout waiting for requests to complete")
  4493  		}
  4494  	}
  4495  }
  4496  
  4497  // Issue 9987: shouldn't add automatic Content-Length (or
  4498  // Content-Type) if a Transfer-Encoding was set by the handler.
  4499  func TestNoContentLengthIfTransferEncoding(t *testing.T) {
  4500  	defer afterTest(t)
  4501  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4502  		w.Header().Set("Transfer-Encoding", "foo")
  4503  		io.WriteString(w, "<html>")
  4504  	}))
  4505  	defer ts.Close()
  4506  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4507  	if err != nil {
  4508  		t.Fatalf("Dial: %v", err)
  4509  	}
  4510  	defer c.Close()
  4511  	if _, err := io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n"); err != nil {
  4512  		t.Fatal(err)
  4513  	}
  4514  	bs := bufio.NewScanner(c)
  4515  	var got bytes.Buffer
  4516  	for bs.Scan() {
  4517  		if strings.TrimSpace(bs.Text()) == "" {
  4518  			break
  4519  		}
  4520  		got.WriteString(bs.Text())
  4521  		got.WriteByte('\n')
  4522  	}
  4523  	if err := bs.Err(); err != nil {
  4524  		t.Fatal(err)
  4525  	}
  4526  	if strings.Contains(got.String(), "Content-Length") {
  4527  		t.Errorf("Unexpected Content-Length in response headers: %s", got.String())
  4528  	}
  4529  	if strings.Contains(got.String(), "Content-Type") {
  4530  		t.Errorf("Unexpected Content-Type in response headers: %s", got.String())
  4531  	}
  4532  }
  4533  
  4534  // tolerate extra CRLF(s) before Request-Line on subsequent requests on a conn
  4535  // Issue 10876.
  4536  func TestTolerateCRLFBeforeRequestLine(t *testing.T) {
  4537  	req := []byte("POST / HTTP/1.1\r\nHost: golang.org\r\nContent-Length: 3\r\n\r\nABC" +
  4538  		"\r\n\r\n" + // <-- this stuff is bogus, but we'll ignore it
  4539  		"GET / HTTP/1.1\r\nHost: golang.org\r\n\r\n")
  4540  	var buf bytes.Buffer
  4541  	conn := &rwTestConn{
  4542  		Reader: bytes.NewReader(req),
  4543  		Writer: &buf,
  4544  		closec: make(chan bool, 1),
  4545  	}
  4546  	ln := &oneConnListener{conn: conn}
  4547  	numReq := 0
  4548  	go Serve(ln, HandlerFunc(func(rw ResponseWriter, r *Request) {
  4549  		numReq++
  4550  	}))
  4551  	<-conn.closec
  4552  	if numReq != 2 {
  4553  		t.Errorf("num requests = %d; want 2", numReq)
  4554  		t.Logf("Res: %s", buf.Bytes())
  4555  	}
  4556  }
  4557  
  4558  func TestIssue13893_Expect100(t *testing.T) {
  4559  	// test that the Server doesn't filter out Expect headers.
  4560  	req := reqBytes(`PUT /readbody HTTP/1.1
  4561  User-Agent: PycURL/7.22.0
  4562  Host: 127.0.0.1:9000
  4563  Accept: */*
  4564  Expect: 100-continue
  4565  Content-Length: 10
  4566  
  4567  HelloWorld
  4568  
  4569  `)
  4570  	var buf bytes.Buffer
  4571  	conn := &rwTestConn{
  4572  		Reader: bytes.NewReader(req),
  4573  		Writer: &buf,
  4574  		closec: make(chan bool, 1),
  4575  	}
  4576  	ln := &oneConnListener{conn: conn}
  4577  	go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
  4578  		if _, ok := r.Header["Expect"]; !ok {
  4579  			t.Error("Expect header should not be filtered out")
  4580  		}
  4581  	}))
  4582  	<-conn.closec
  4583  }
  4584  
  4585  func TestIssue11549_Expect100(t *testing.T) {
  4586  	req := reqBytes(`PUT /readbody HTTP/1.1
  4587  User-Agent: PycURL/7.22.0
  4588  Host: 127.0.0.1:9000
  4589  Accept: */*
  4590  Expect: 100-continue
  4591  Content-Length: 10
  4592  
  4593  HelloWorldPUT /noreadbody HTTP/1.1
  4594  User-Agent: PycURL/7.22.0
  4595  Host: 127.0.0.1:9000
  4596  Accept: */*
  4597  Expect: 100-continue
  4598  Content-Length: 10
  4599  
  4600  GET /should-be-ignored HTTP/1.1
  4601  Host: foo
  4602  
  4603  `)
  4604  	var buf bytes.Buffer
  4605  	conn := &rwTestConn{
  4606  		Reader: bytes.NewReader(req),
  4607  		Writer: &buf,
  4608  		closec: make(chan bool, 1),
  4609  	}
  4610  	ln := &oneConnListener{conn: conn}
  4611  	numReq := 0
  4612  	go Serve(ln, HandlerFunc(func(w ResponseWriter, r *Request) {
  4613  		numReq++
  4614  		if r.URL.Path == "/readbody" {
  4615  			io.ReadAll(r.Body)
  4616  		}
  4617  		io.WriteString(w, "Hello world!")
  4618  	}))
  4619  	<-conn.closec
  4620  	if numReq != 2 {
  4621  		t.Errorf("num requests = %d; want 2", numReq)
  4622  	}
  4623  	if !strings.Contains(buf.String(), "Connection: close\r\n") {
  4624  		t.Errorf("expected 'Connection: close' in response; got: %s", buf.String())
  4625  	}
  4626  }
  4627  
  4628  // If a Handler finishes and there's an unread request body,
  4629  // verify the server try to do implicit read on it before replying.
  4630  func TestHandlerFinishSkipBigContentLengthRead(t *testing.T) {
  4631  	setParallel(t)
  4632  	conn := &testConn{closec: make(chan bool)}
  4633  	conn.readBuf.Write([]byte(fmt.Sprintf(
  4634  		"POST / HTTP/1.1\r\n" +
  4635  			"Host: test\r\n" +
  4636  			"Content-Length: 9999999999\r\n" +
  4637  			"\r\n" + strings.Repeat("a", 1<<20))))
  4638  
  4639  	ls := &oneConnListener{conn}
  4640  	var inHandlerLen int
  4641  	go Serve(ls, HandlerFunc(func(rw ResponseWriter, req *Request) {
  4642  		inHandlerLen = conn.readBuf.Len()
  4643  		rw.WriteHeader(404)
  4644  	}))
  4645  	<-conn.closec
  4646  	afterHandlerLen := conn.readBuf.Len()
  4647  
  4648  	if afterHandlerLen != inHandlerLen {
  4649  		t.Errorf("unexpected implicit read. Read buffer went from %d -> %d", inHandlerLen, afterHandlerLen)
  4650  	}
  4651  }
  4652  
  4653  func TestHandlerSetsBodyNil_h1(t *testing.T) { testHandlerSetsBodyNil(t, h1Mode) }
  4654  func TestHandlerSetsBodyNil_h2(t *testing.T) { testHandlerSetsBodyNil(t, h2Mode) }
  4655  func testHandlerSetsBodyNil(t *testing.T, h2 bool) {
  4656  	defer afterTest(t)
  4657  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4658  		r.Body = nil
  4659  		fmt.Fprintf(w, "%v", r.RemoteAddr)
  4660  	}))
  4661  	defer cst.close()
  4662  	get := func() string {
  4663  		res, err := cst.c.Get(cst.ts.URL)
  4664  		if err != nil {
  4665  			t.Fatal(err)
  4666  		}
  4667  		defer res.Body.Close()
  4668  		slurp, err := io.ReadAll(res.Body)
  4669  		if err != nil {
  4670  			t.Fatal(err)
  4671  		}
  4672  		return string(slurp)
  4673  	}
  4674  	a, b := get(), get()
  4675  	if a != b {
  4676  		t.Errorf("Failed to reuse connections between requests: %v vs %v", a, b)
  4677  	}
  4678  }
  4679  
  4680  // Test that we validate the Host header.
  4681  // Issue 11206 (invalid bytes in Host) and 13624 (Host present in HTTP/1.1)
  4682  func TestServerValidatesHostHeader(t *testing.T) {
  4683  	tests := []struct {
  4684  		proto string
  4685  		host  string
  4686  		want  int
  4687  	}{
  4688  		{"HTTP/0.9", "", 505},
  4689  
  4690  		{"HTTP/1.1", "", 400},
  4691  		{"HTTP/1.1", "Host: \r\n", 200},
  4692  		{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
  4693  		{"HTTP/1.1", "Host: foo.com\r\n", 200},
  4694  		{"HTTP/1.1", "Host: foo-bar_baz.com\r\n", 200},
  4695  		{"HTTP/1.1", "Host: foo.com:80\r\n", 200},
  4696  		{"HTTP/1.1", "Host: ::1\r\n", 200},
  4697  		{"HTTP/1.1", "Host: [::1]\r\n", 200}, // questionable without port, but accept it
  4698  		{"HTTP/1.1", "Host: [::1]:80\r\n", 200},
  4699  		{"HTTP/1.1", "Host: [::1%25en0]:80\r\n", 200},
  4700  		{"HTTP/1.1", "Host: 1.2.3.4\r\n", 200},
  4701  		{"HTTP/1.1", "Host: \x06\r\n", 400},
  4702  		{"HTTP/1.1", "Host: \xff\r\n", 400},
  4703  		{"HTTP/1.1", "Host: {\r\n", 400},
  4704  		{"HTTP/1.1", "Host: }\r\n", 400},
  4705  		{"HTTP/1.1", "Host: first\r\nHost: second\r\n", 400},
  4706  
  4707  		// HTTP/1.0 can lack a host header, but if present
  4708  		// must play by the rules too:
  4709  		{"HTTP/1.0", "", 200},
  4710  		{"HTTP/1.0", "Host: first\r\nHost: second\r\n", 400},
  4711  		{"HTTP/1.0", "Host: \xff\r\n", 400},
  4712  
  4713  		// Make an exception for HTTP upgrade requests:
  4714  		{"PRI * HTTP/2.0", "", 200},
  4715  
  4716  		// Also an exception for CONNECT requests: (Issue 18215)
  4717  		{"CONNECT golang.org:443 HTTP/1.1", "", 200},
  4718  
  4719  		// But not other HTTP/2 stuff:
  4720  		{"PRI / HTTP/2.0", "", 505},
  4721  		{"GET / HTTP/2.0", "", 505},
  4722  		{"GET / HTTP/3.0", "", 505},
  4723  	}
  4724  	for _, tt := range tests {
  4725  		conn := &testConn{closec: make(chan bool, 1)}
  4726  		methodTarget := "GET / "
  4727  		if !strings.HasPrefix(tt.proto, "HTTP/") {
  4728  			methodTarget = ""
  4729  		}
  4730  		io.WriteString(&conn.readBuf, methodTarget+tt.proto+"\r\n"+tt.host+"\r\n")
  4731  
  4732  		ln := &oneConnListener{conn}
  4733  		srv := Server{
  4734  			ErrorLog: quietLog,
  4735  			Handler:  HandlerFunc(func(ResponseWriter, *Request) {}),
  4736  		}
  4737  		go srv.Serve(ln)
  4738  		<-conn.closec
  4739  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  4740  		if err != nil {
  4741  			t.Errorf("For %s %q, ReadResponse: %v", tt.proto, tt.host, res)
  4742  			continue
  4743  		}
  4744  		if res.StatusCode != tt.want {
  4745  			t.Errorf("For %s %q, Status = %d; want %d", tt.proto, tt.host, res.StatusCode, tt.want)
  4746  		}
  4747  	}
  4748  }
  4749  
  4750  func TestServerHandlersCanHandleH2PRI(t *testing.T) {
  4751  	const upgradeResponse = "upgrade here"
  4752  	defer afterTest(t)
  4753  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4754  		conn, br, err := w.(Hijacker).Hijack()
  4755  		if err != nil {
  4756  			t.Error(err)
  4757  			return
  4758  		}
  4759  		defer conn.Close()
  4760  		if r.Method != "PRI" || r.RequestURI != "*" {
  4761  			t.Errorf("Got method/target %q %q; want PRI *", r.Method, r.RequestURI)
  4762  			return
  4763  		}
  4764  		if !r.Close {
  4765  			t.Errorf("Request.Close = true; want false")
  4766  		}
  4767  		const want = "SM\r\n\r\n"
  4768  		buf := make([]byte, len(want))
  4769  		n, err := io.ReadFull(br, buf)
  4770  		if err != nil || string(buf[:n]) != want {
  4771  			t.Errorf("Read = %v, %v (%q), want %q", n, err, buf[:n], want)
  4772  			return
  4773  		}
  4774  		io.WriteString(conn, upgradeResponse)
  4775  	}))
  4776  	defer ts.Close()
  4777  
  4778  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4779  	if err != nil {
  4780  		t.Fatalf("Dial: %v", err)
  4781  	}
  4782  	defer c.Close()
  4783  	io.WriteString(c, "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
  4784  	slurp, err := io.ReadAll(c)
  4785  	if err != nil {
  4786  		t.Fatal(err)
  4787  	}
  4788  	if string(slurp) != upgradeResponse {
  4789  		t.Errorf("Handler response = %q; want %q", slurp, upgradeResponse)
  4790  	}
  4791  }
  4792  
  4793  // Test that we validate the valid bytes in HTTP/1 headers.
  4794  // Issue 11207.
  4795  func TestServerValidatesHeaders(t *testing.T) {
  4796  	setParallel(t)
  4797  	tests := []struct {
  4798  		header string
  4799  		want   int
  4800  	}{
  4801  		{"", 200},
  4802  		{"Foo: bar\r\n", 200},
  4803  		{"X-Foo: bar\r\n", 200},
  4804  		{"Foo: a space\r\n", 200},
  4805  
  4806  		{"A space: foo\r\n", 400},                            // space in header
  4807  		{"foo\xffbar: foo\r\n", 400},                         // binary in header
  4808  		{"foo\x00bar: foo\r\n", 400},                         // binary in header
  4809  		{"Foo: " + strings.Repeat("x", 1<<21) + "\r\n", 431}, // header too large
  4810  		// Spaces between the header key and colon are not allowed.
  4811  		// See RFC 7230, Section 3.2.4.
  4812  		{"Foo : bar\r\n", 400},
  4813  		{"Foo\t: bar\r\n", 400},
  4814  
  4815  		{"foo: foo foo\r\n", 200},    // LWS space is okay
  4816  		{"foo: foo\tfoo\r\n", 200},   // LWS tab is okay
  4817  		{"foo: foo\x00foo\r\n", 400}, // CTL 0x00 in value is bad
  4818  		{"foo: foo\x7ffoo\r\n", 400}, // CTL 0x7f in value is bad
  4819  		{"foo: foo\xfffoo\r\n", 200}, // non-ASCII high octets in value are fine
  4820  	}
  4821  	for _, tt := range tests {
  4822  		conn := &testConn{closec: make(chan bool, 1)}
  4823  		io.WriteString(&conn.readBuf, "GET / HTTP/1.1\r\nHost: foo\r\n"+tt.header+"\r\n")
  4824  
  4825  		ln := &oneConnListener{conn}
  4826  		srv := Server{
  4827  			ErrorLog: quietLog,
  4828  			Handler:  HandlerFunc(func(ResponseWriter, *Request) {}),
  4829  		}
  4830  		go srv.Serve(ln)
  4831  		<-conn.closec
  4832  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  4833  		if err != nil {
  4834  			t.Errorf("For %q, ReadResponse: %v", tt.header, res)
  4835  			continue
  4836  		}
  4837  		if res.StatusCode != tt.want {
  4838  			t.Errorf("For %q, Status = %d; want %d", tt.header, res.StatusCode, tt.want)
  4839  		}
  4840  	}
  4841  }
  4842  
  4843  func TestServerRequestContextCancel_ServeHTTPDone_h1(t *testing.T) {
  4844  	testServerRequestContextCancel_ServeHTTPDone(t, h1Mode)
  4845  }
  4846  func TestServerRequestContextCancel_ServeHTTPDone_h2(t *testing.T) {
  4847  	testServerRequestContextCancel_ServeHTTPDone(t, h2Mode)
  4848  }
  4849  func testServerRequestContextCancel_ServeHTTPDone(t *testing.T, h2 bool) {
  4850  	setParallel(t)
  4851  	defer afterTest(t)
  4852  	ctxc := make(chan context.Context, 1)
  4853  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4854  		ctx := r.Context()
  4855  		select {
  4856  		case <-ctx.Done():
  4857  			t.Error("should not be Done in ServeHTTP")
  4858  		default:
  4859  		}
  4860  		ctxc <- ctx
  4861  	}))
  4862  	defer cst.close()
  4863  	res, err := cst.c.Get(cst.ts.URL)
  4864  	if err != nil {
  4865  		t.Fatal(err)
  4866  	}
  4867  	res.Body.Close()
  4868  	ctx := <-ctxc
  4869  	select {
  4870  	case <-ctx.Done():
  4871  	default:
  4872  		t.Error("context should be done after ServeHTTP completes")
  4873  	}
  4874  }
  4875  
  4876  // Tests that the Request.Context available to the Handler is canceled
  4877  // if the peer closes their TCP connection. This requires that the server
  4878  // is always blocked in a Read call so it notices the EOF from the client.
  4879  // See issues 15927 and 15224.
  4880  func TestServerRequestContextCancel_ConnClose(t *testing.T) {
  4881  	setParallel(t)
  4882  	defer afterTest(t)
  4883  	inHandler := make(chan struct{})
  4884  	handlerDone := make(chan struct{})
  4885  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  4886  		close(inHandler)
  4887  		<-r.Context().Done()
  4888  		close(handlerDone)
  4889  	}))
  4890  	defer ts.Close()
  4891  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  4892  	if err != nil {
  4893  		t.Fatal(err)
  4894  	}
  4895  	defer c.Close()
  4896  	io.WriteString(c, "GET / HTTP/1.1\r\nHost: foo\r\n\r\n")
  4897  	<-inHandler
  4898  	c.Close() // this should trigger the context being done
  4899  	<-handlerDone
  4900  }
  4901  
  4902  func TestServerContext_ServerContextKey_h1(t *testing.T) {
  4903  	testServerContext_ServerContextKey(t, h1Mode)
  4904  }
  4905  func TestServerContext_ServerContextKey_h2(t *testing.T) {
  4906  	testServerContext_ServerContextKey(t, h2Mode)
  4907  }
  4908  func testServerContext_ServerContextKey(t *testing.T, h2 bool) {
  4909  	setParallel(t)
  4910  	defer afterTest(t)
  4911  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4912  		ctx := r.Context()
  4913  		got := ctx.Value(ServerContextKey)
  4914  		if _, ok := got.(*Server); !ok {
  4915  			t.Errorf("context value = %T; want *http.Server", got)
  4916  		}
  4917  	}))
  4918  	defer cst.close()
  4919  	res, err := cst.c.Get(cst.ts.URL)
  4920  	if err != nil {
  4921  		t.Fatal(err)
  4922  	}
  4923  	res.Body.Close()
  4924  }
  4925  
  4926  func TestServerContext_LocalAddrContextKey_h1(t *testing.T) {
  4927  	testServerContext_LocalAddrContextKey(t, h1Mode)
  4928  }
  4929  func TestServerContext_LocalAddrContextKey_h2(t *testing.T) {
  4930  	testServerContext_LocalAddrContextKey(t, h2Mode)
  4931  }
  4932  func testServerContext_LocalAddrContextKey(t *testing.T, h2 bool) {
  4933  	setParallel(t)
  4934  	defer afterTest(t)
  4935  	ch := make(chan any, 1)
  4936  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
  4937  		ch <- r.Context().Value(LocalAddrContextKey)
  4938  	}))
  4939  	defer cst.close()
  4940  	if _, err := cst.c.Head(cst.ts.URL); err != nil {
  4941  		t.Fatal(err)
  4942  	}
  4943  
  4944  	host := cst.ts.Listener.Addr().String()
  4945  	select {
  4946  	case got := <-ch:
  4947  		if addr, ok := got.(net.Addr); !ok {
  4948  			t.Errorf("local addr value = %T; want net.Addr", got)
  4949  		} else if fmt.Sprint(addr) != host {
  4950  			t.Errorf("local addr = %v; want %v", addr, host)
  4951  		}
  4952  	case <-time.After(5 * time.Second):
  4953  		t.Error("timed out")
  4954  	}
  4955  }
  4956  
  4957  // https://golang.org/issue/15960
  4958  func TestHandlerSetTransferEncodingChunked(t *testing.T) {
  4959  	setParallel(t)
  4960  	defer afterTest(t)
  4961  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4962  		w.Header().Set("Transfer-Encoding", "chunked")
  4963  		w.Write([]byte("hello"))
  4964  	}))
  4965  	resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  4966  	const hdr = "Transfer-Encoding: chunked"
  4967  	if n := strings.Count(resp, hdr); n != 1 {
  4968  		t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
  4969  	}
  4970  }
  4971  
  4972  // https://golang.org/issue/16063
  4973  func TestHandlerSetTransferEncodingGzip(t *testing.T) {
  4974  	setParallel(t)
  4975  	defer afterTest(t)
  4976  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  4977  		w.Header().Set("Transfer-Encoding", "gzip")
  4978  		gz := gzip.NewWriter(w)
  4979  		gz.Write([]byte("hello"))
  4980  		gz.Close()
  4981  	}))
  4982  	resp := ht.rawResponse("GET / HTTP/1.1\nHost: foo")
  4983  	for _, v := range []string{"gzip", "chunked"} {
  4984  		hdr := "Transfer-Encoding: " + v
  4985  		if n := strings.Count(resp, hdr); n != 1 {
  4986  			t.Errorf("want 1 occurrence of %q in response, got %v\nresponse: %v", hdr, n, resp)
  4987  		}
  4988  	}
  4989  }
  4990  
  4991  func BenchmarkClientServer(b *testing.B) {
  4992  	b.ReportAllocs()
  4993  	b.StopTimer()
  4994  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  4995  		fmt.Fprintf(rw, "Hello world.\n")
  4996  	}))
  4997  	defer ts.Close()
  4998  	b.StartTimer()
  4999  
  5000  	for i := 0; i < b.N; i++ {
  5001  		res, err := Get(ts.URL)
  5002  		if err != nil {
  5003  			b.Fatal("Get:", err)
  5004  		}
  5005  		all, err := io.ReadAll(res.Body)
  5006  		res.Body.Close()
  5007  		if err != nil {
  5008  			b.Fatal("ReadAll:", err)
  5009  		}
  5010  		body := string(all)
  5011  		if body != "Hello world.\n" {
  5012  			b.Fatal("Got body:", body)
  5013  		}
  5014  	}
  5015  
  5016  	b.StopTimer()
  5017  }
  5018  
  5019  func BenchmarkClientServerParallel4(b *testing.B) {
  5020  	benchmarkClientServerParallel(b, 4, false)
  5021  }
  5022  
  5023  func BenchmarkClientServerParallel64(b *testing.B) {
  5024  	benchmarkClientServerParallel(b, 64, false)
  5025  }
  5026  
  5027  func BenchmarkClientServerParallelTLS4(b *testing.B) {
  5028  	benchmarkClientServerParallel(b, 4, true)
  5029  }
  5030  
  5031  func BenchmarkClientServerParallelTLS64(b *testing.B) {
  5032  	benchmarkClientServerParallel(b, 64, true)
  5033  }
  5034  
  5035  func benchmarkClientServerParallel(b *testing.B, parallelism int, useTLS bool) {
  5036  	b.ReportAllocs()
  5037  	ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  5038  		fmt.Fprintf(rw, "Hello world.\n")
  5039  	}))
  5040  	if useTLS {
  5041  		ts.StartTLS()
  5042  	} else {
  5043  		ts.Start()
  5044  	}
  5045  	defer ts.Close()
  5046  	b.ResetTimer()
  5047  	b.SetParallelism(parallelism)
  5048  	b.RunParallel(func(pb *testing.PB) {
  5049  		c := ts.Client()
  5050  		for pb.Next() {
  5051  			res, err := c.Get(ts.URL)
  5052  			if err != nil {
  5053  				b.Logf("Get: %v", err)
  5054  				continue
  5055  			}
  5056  			all, err := io.ReadAll(res.Body)
  5057  			res.Body.Close()
  5058  			if err != nil {
  5059  				b.Logf("ReadAll: %v", err)
  5060  				continue
  5061  			}
  5062  			body := string(all)
  5063  			if body != "Hello world.\n" {
  5064  				panic("Got body: " + body)
  5065  			}
  5066  		}
  5067  	})
  5068  }
  5069  
  5070  // A benchmark for profiling the server without the HTTP client code.
  5071  // The client code runs in a subprocess.
  5072  //
  5073  // For use like:
  5074  //
  5075  //	$ go test -c
  5076  //	$ ./http.test -test.run=XX -test.bench=BenchmarkServer -test.benchtime=15s -test.cpuprofile=http.prof
  5077  //	$ go tool pprof http.test http.prof
  5078  //	(pprof) web
  5079  func BenchmarkServer(b *testing.B) {
  5080  	b.ReportAllocs()
  5081  	// Child process mode;
  5082  	if url := os.Getenv("TEST_BENCH_SERVER_URL"); url != "" {
  5083  		n, err := strconv.Atoi(os.Getenv("TEST_BENCH_CLIENT_N"))
  5084  		if err != nil {
  5085  			panic(err)
  5086  		}
  5087  		for i := 0; i < n; i++ {
  5088  			res, err := Get(url)
  5089  			if err != nil {
  5090  				log.Panicf("Get: %v", err)
  5091  			}
  5092  			all, err := io.ReadAll(res.Body)
  5093  			res.Body.Close()
  5094  			if err != nil {
  5095  				log.Panicf("ReadAll: %v", err)
  5096  			}
  5097  			body := string(all)
  5098  			if body != "Hello world.\n" {
  5099  				log.Panicf("Got body: %q", body)
  5100  			}
  5101  		}
  5102  		os.Exit(0)
  5103  		return
  5104  	}
  5105  
  5106  	var res = []byte("Hello world.\n")
  5107  	b.StopTimer()
  5108  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  5109  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5110  		rw.Write(res)
  5111  	}))
  5112  	defer ts.Close()
  5113  	b.StartTimer()
  5114  
  5115  	cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkServer$")
  5116  	cmd.Env = append([]string{
  5117  		fmt.Sprintf("TEST_BENCH_CLIENT_N=%d", b.N),
  5118  		fmt.Sprintf("TEST_BENCH_SERVER_URL=%s", ts.URL),
  5119  	}, os.Environ()...)
  5120  	out, err := cmd.CombinedOutput()
  5121  	if err != nil {
  5122  		b.Errorf("Test failure: %v, with output: %s", err, out)
  5123  	}
  5124  }
  5125  
  5126  // getNoBody wraps Get but closes any Response.Body before returning the response.
  5127  func getNoBody(urlStr string) (*Response, error) {
  5128  	res, err := Get(urlStr)
  5129  	if err != nil {
  5130  		return nil, err
  5131  	}
  5132  	res.Body.Close()
  5133  	return res, nil
  5134  }
  5135  
  5136  // A benchmark for profiling the client without the HTTP server code.
  5137  // The server code runs in a subprocess.
  5138  func BenchmarkClient(b *testing.B) {
  5139  	b.ReportAllocs()
  5140  	b.StopTimer()
  5141  	defer afterTest(b)
  5142  
  5143  	var data = []byte("Hello world.\n")
  5144  	if server := os.Getenv("TEST_BENCH_SERVER"); server != "" {
  5145  		// Server process mode.
  5146  		port := os.Getenv("TEST_BENCH_SERVER_PORT") // can be set by user
  5147  		if port == "" {
  5148  			port = "0"
  5149  		}
  5150  		ln, err := net.Listen("tcp", "localhost:"+port)
  5151  		if err != nil {
  5152  			fmt.Fprintln(os.Stderr, err.Error())
  5153  			os.Exit(1)
  5154  		}
  5155  		fmt.Println(ln.Addr().String())
  5156  		HandleFunc("/", func(w ResponseWriter, r *Request) {
  5157  			r.ParseForm()
  5158  			if r.Form.Get("stop") != "" {
  5159  				os.Exit(0)
  5160  			}
  5161  			w.Header().Set("Content-Type", "text/html; charset=utf-8")
  5162  			w.Write(data)
  5163  		})
  5164  		var srv Server
  5165  		log.Fatal(srv.Serve(ln))
  5166  	}
  5167  
  5168  	// Start server process.
  5169  	cmd := exec.Command(os.Args[0], "-test.run=XXXX", "-test.bench=BenchmarkClient$")
  5170  	cmd.Env = append(os.Environ(), "TEST_BENCH_SERVER=yes")
  5171  	cmd.Stderr = os.Stderr
  5172  	stdout, err := cmd.StdoutPipe()
  5173  	if err != nil {
  5174  		b.Fatal(err)
  5175  	}
  5176  	if err := cmd.Start(); err != nil {
  5177  		b.Fatalf("subprocess failed to start: %v", err)
  5178  	}
  5179  	defer cmd.Process.Kill()
  5180  
  5181  	// Wait for the server in the child process to respond and tell us
  5182  	// its listening address, once it's started listening:
  5183  	timer := time.AfterFunc(10*time.Second, func() {
  5184  		cmd.Process.Kill()
  5185  	})
  5186  	defer timer.Stop()
  5187  	bs := bufio.NewScanner(stdout)
  5188  	if !bs.Scan() {
  5189  		b.Fatalf("failed to read listening URL from child: %v", bs.Err())
  5190  	}
  5191  	url := "http://" + strings.TrimSpace(bs.Text()) + "/"
  5192  	timer.Stop()
  5193  	if _, err := getNoBody(url); err != nil {
  5194  		b.Fatalf("initial probe of child process failed: %v", err)
  5195  	}
  5196  
  5197  	done := make(chan error)
  5198  	stop := make(chan struct{})
  5199  	defer close(stop)
  5200  	go func() {
  5201  		select {
  5202  		case <-stop:
  5203  			return
  5204  		case done <- cmd.Wait():
  5205  		}
  5206  	}()
  5207  
  5208  	// Do b.N requests to the server.
  5209  	b.StartTimer()
  5210  	for i := 0; i < b.N; i++ {
  5211  		res, err := Get(url)
  5212  		if err != nil {
  5213  			b.Fatalf("Get: %v", err)
  5214  		}
  5215  		body, err := io.ReadAll(res.Body)
  5216  		res.Body.Close()
  5217  		if err != nil {
  5218  			b.Fatalf("ReadAll: %v", err)
  5219  		}
  5220  		if !bytes.Equal(body, data) {
  5221  			b.Fatalf("Got body: %q", body)
  5222  		}
  5223  	}
  5224  	b.StopTimer()
  5225  
  5226  	// Instruct server process to stop.
  5227  	getNoBody(url + "?stop=yes")
  5228  	select {
  5229  	case err := <-done:
  5230  		if err != nil {
  5231  			b.Fatalf("subprocess failed: %v", err)
  5232  		}
  5233  	case <-time.After(5 * time.Second):
  5234  		b.Fatalf("subprocess did not stop")
  5235  	}
  5236  }
  5237  
  5238  func BenchmarkServerFakeConnNoKeepAlive(b *testing.B) {
  5239  	b.ReportAllocs()
  5240  	req := reqBytes(`GET / HTTP/1.0
  5241  Host: golang.org
  5242  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5243  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
  5244  Accept-Encoding: gzip,deflate,sdch
  5245  Accept-Language: en-US,en;q=0.8
  5246  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  5247  `)
  5248  	res := []byte("Hello world!\n")
  5249  
  5250  	conn := &testConn{
  5251  		// testConn.Close will not push into the channel
  5252  		// if it's full.
  5253  		closec: make(chan bool, 1),
  5254  	}
  5255  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5256  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5257  		rw.Write(res)
  5258  	})
  5259  	ln := new(oneConnListener)
  5260  	for i := 0; i < b.N; i++ {
  5261  		conn.readBuf.Reset()
  5262  		conn.writeBuf.Reset()
  5263  		conn.readBuf.Write(req)
  5264  		ln.conn = conn
  5265  		Serve(ln, handler)
  5266  		<-conn.closec
  5267  	}
  5268  }
  5269  
  5270  // repeatReader reads content count times, then EOFs.
  5271  type repeatReader struct {
  5272  	content []byte
  5273  	count   int
  5274  	off     int
  5275  }
  5276  
  5277  func (r *repeatReader) Read(p []byte) (n int, err error) {
  5278  	if r.count <= 0 {
  5279  		return 0, io.EOF
  5280  	}
  5281  	n = copy(p, r.content[r.off:])
  5282  	r.off += n
  5283  	if r.off == len(r.content) {
  5284  		r.count--
  5285  		r.off = 0
  5286  	}
  5287  	return
  5288  }
  5289  
  5290  func BenchmarkServerFakeConnWithKeepAlive(b *testing.B) {
  5291  	b.ReportAllocs()
  5292  
  5293  	req := reqBytes(`GET / HTTP/1.1
  5294  Host: golang.org
  5295  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
  5296  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
  5297  Accept-Encoding: gzip,deflate,sdch
  5298  Accept-Language: en-US,en;q=0.8
  5299  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  5300  `)
  5301  	res := []byte("Hello world!\n")
  5302  
  5303  	conn := &rwTestConn{
  5304  		Reader: &repeatReader{content: req, count: b.N},
  5305  		Writer: io.Discard,
  5306  		closec: make(chan bool, 1),
  5307  	}
  5308  	handled := 0
  5309  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5310  		handled++
  5311  		rw.Header().Set("Content-Type", "text/html; charset=utf-8")
  5312  		rw.Write(res)
  5313  	})
  5314  	ln := &oneConnListener{conn: conn}
  5315  	go Serve(ln, handler)
  5316  	<-conn.closec
  5317  	if b.N != handled {
  5318  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5319  	}
  5320  }
  5321  
  5322  // same as above, but representing the most simple possible request
  5323  // and handler. Notably: the handler does not call rw.Header().
  5324  func BenchmarkServerFakeConnWithKeepAliveLite(b *testing.B) {
  5325  	b.ReportAllocs()
  5326  
  5327  	req := reqBytes(`GET / HTTP/1.1
  5328  Host: golang.org
  5329  `)
  5330  	res := []byte("Hello world!\n")
  5331  
  5332  	conn := &rwTestConn{
  5333  		Reader: &repeatReader{content: req, count: b.N},
  5334  		Writer: io.Discard,
  5335  		closec: make(chan bool, 1),
  5336  	}
  5337  	handled := 0
  5338  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5339  		handled++
  5340  		rw.Write(res)
  5341  	})
  5342  	ln := &oneConnListener{conn: conn}
  5343  	go Serve(ln, handler)
  5344  	<-conn.closec
  5345  	if b.N != handled {
  5346  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5347  	}
  5348  }
  5349  
  5350  const someResponse = "<html>some response</html>"
  5351  
  5352  // A Response that's just no bigger than 2KB, the buffer-before-chunking threshold.
  5353  var response = bytes.Repeat([]byte(someResponse), 2<<10/len(someResponse))
  5354  
  5355  // Both Content-Type and Content-Length set. Should be no buffering.
  5356  func BenchmarkServerHandlerTypeLen(b *testing.B) {
  5357  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5358  		w.Header().Set("Content-Type", "text/html")
  5359  		w.Header().Set("Content-Length", strconv.Itoa(len(response)))
  5360  		w.Write(response)
  5361  	}))
  5362  }
  5363  
  5364  // A Content-Type is set, but no length. No sniffing, but will count the Content-Length.
  5365  func BenchmarkServerHandlerNoLen(b *testing.B) {
  5366  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5367  		w.Header().Set("Content-Type", "text/html")
  5368  		w.Write(response)
  5369  	}))
  5370  }
  5371  
  5372  // A Content-Length is set, but the Content-Type will be sniffed.
  5373  func BenchmarkServerHandlerNoType(b *testing.B) {
  5374  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5375  		w.Header().Set("Content-Length", strconv.Itoa(len(response)))
  5376  		w.Write(response)
  5377  	}))
  5378  }
  5379  
  5380  // Neither a Content-Type or Content-Length, so sniffed and counted.
  5381  func BenchmarkServerHandlerNoHeader(b *testing.B) {
  5382  	benchmarkHandler(b, HandlerFunc(func(w ResponseWriter, r *Request) {
  5383  		w.Write(response)
  5384  	}))
  5385  }
  5386  
  5387  func benchmarkHandler(b *testing.B, h Handler) {
  5388  	b.ReportAllocs()
  5389  	req := reqBytes(`GET / HTTP/1.1
  5390  Host: golang.org
  5391  `)
  5392  	conn := &rwTestConn{
  5393  		Reader: &repeatReader{content: req, count: b.N},
  5394  		Writer: io.Discard,
  5395  		closec: make(chan bool, 1),
  5396  	}
  5397  	handled := 0
  5398  	handler := HandlerFunc(func(rw ResponseWriter, r *Request) {
  5399  		handled++
  5400  		h.ServeHTTP(rw, r)
  5401  	})
  5402  	ln := &oneConnListener{conn: conn}
  5403  	go Serve(ln, handler)
  5404  	<-conn.closec
  5405  	if b.N != handled {
  5406  		b.Errorf("b.N=%d but handled %d", b.N, handled)
  5407  	}
  5408  }
  5409  
  5410  func BenchmarkServerHijack(b *testing.B) {
  5411  	b.ReportAllocs()
  5412  	req := reqBytes(`GET / HTTP/1.1
  5413  Host: golang.org
  5414  `)
  5415  	h := HandlerFunc(func(w ResponseWriter, r *Request) {
  5416  		conn, _, err := w.(Hijacker).Hijack()
  5417  		if err != nil {
  5418  			panic(err)
  5419  		}
  5420  		conn.Close()
  5421  	})
  5422  	conn := &rwTestConn{
  5423  		Writer: io.Discard,
  5424  		closec: make(chan bool, 1),
  5425  	}
  5426  	ln := &oneConnListener{conn: conn}
  5427  	for i := 0; i < b.N; i++ {
  5428  		conn.Reader = bytes.NewReader(req)
  5429  		ln.conn = conn
  5430  		Serve(ln, h)
  5431  		<-conn.closec
  5432  	}
  5433  }
  5434  
  5435  func BenchmarkCloseNotifier(b *testing.B) {
  5436  	b.ReportAllocs()
  5437  	b.StopTimer()
  5438  	sawClose := make(chan bool)
  5439  	ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
  5440  		<-rw.(CloseNotifier).CloseNotify()
  5441  		sawClose <- true
  5442  	}))
  5443  	defer ts.Close()
  5444  	tot := time.NewTimer(5 * time.Second)
  5445  	defer tot.Stop()
  5446  	b.StartTimer()
  5447  	for i := 0; i < b.N; i++ {
  5448  		conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5449  		if err != nil {
  5450  			b.Fatalf("error dialing: %v", err)
  5451  		}
  5452  		_, err = fmt.Fprintf(conn, "GET / HTTP/1.1\r\nConnection: keep-alive\r\nHost: foo\r\n\r\n")
  5453  		if err != nil {
  5454  			b.Fatal(err)
  5455  		}
  5456  		conn.Close()
  5457  		tot.Reset(5 * time.Second)
  5458  		select {
  5459  		case <-sawClose:
  5460  		case <-tot.C:
  5461  			b.Fatal("timeout")
  5462  		}
  5463  	}
  5464  	b.StopTimer()
  5465  }
  5466  
  5467  // Verify this doesn't race (Issue 16505)
  5468  func TestConcurrentServerServe(t *testing.T) {
  5469  	setParallel(t)
  5470  	for i := 0; i < 100; i++ {
  5471  		ln1 := &oneConnListener{conn: nil}
  5472  		ln2 := &oneConnListener{conn: nil}
  5473  		srv := Server{}
  5474  		go func() { srv.Serve(ln1) }()
  5475  		go func() { srv.Serve(ln2) }()
  5476  	}
  5477  }
  5478  
  5479  func TestServerIdleTimeout(t *testing.T) {
  5480  	if testing.Short() {
  5481  		t.Skip("skipping in short mode")
  5482  	}
  5483  	setParallel(t)
  5484  	defer afterTest(t)
  5485  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5486  		io.Copy(io.Discard, r.Body)
  5487  		io.WriteString(w, r.RemoteAddr)
  5488  	}))
  5489  	ts.Config.ReadHeaderTimeout = 1 * time.Second
  5490  	ts.Config.IdleTimeout = 2 * time.Second
  5491  	ts.Start()
  5492  	defer ts.Close()
  5493  	c := ts.Client()
  5494  
  5495  	get := func() string {
  5496  		res, err := c.Get(ts.URL)
  5497  		if err != nil {
  5498  			t.Fatal(err)
  5499  		}
  5500  		defer res.Body.Close()
  5501  		slurp, err := io.ReadAll(res.Body)
  5502  		if err != nil {
  5503  			t.Fatal(err)
  5504  		}
  5505  		return string(slurp)
  5506  	}
  5507  
  5508  	a1, a2 := get(), get()
  5509  	if a1 != a2 {
  5510  		t.Fatalf("did requests on different connections")
  5511  	}
  5512  	time.Sleep(3 * time.Second)
  5513  	a3 := get()
  5514  	if a2 == a3 {
  5515  		t.Fatal("request three unexpectedly on same connection")
  5516  	}
  5517  
  5518  	// And test that ReadHeaderTimeout still works:
  5519  	conn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5520  	if err != nil {
  5521  		t.Fatal(err)
  5522  	}
  5523  	defer conn.Close()
  5524  	conn.Write([]byte("GET / HTTP/1.1\r\nHost: foo.com\r\n"))
  5525  	time.Sleep(2 * time.Second)
  5526  	if _, err := io.CopyN(io.Discard, conn, 1); err == nil {
  5527  		t.Fatal("copy byte succeeded; want err")
  5528  	}
  5529  }
  5530  
  5531  func get(t *testing.T, c *Client, url string) string {
  5532  	res, err := c.Get(url)
  5533  	if err != nil {
  5534  		t.Fatal(err)
  5535  	}
  5536  	defer res.Body.Close()
  5537  	slurp, err := io.ReadAll(res.Body)
  5538  	if err != nil {
  5539  		t.Fatal(err)
  5540  	}
  5541  	return string(slurp)
  5542  }
  5543  
  5544  // Tests that calls to Server.SetKeepAlivesEnabled(false) closes any
  5545  // currently-open connections.
  5546  func TestServerSetKeepAlivesEnabledClosesConns(t *testing.T) {
  5547  	setParallel(t)
  5548  	defer afterTest(t)
  5549  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5550  		io.WriteString(w, r.RemoteAddr)
  5551  	}))
  5552  	defer ts.Close()
  5553  
  5554  	c := ts.Client()
  5555  	tr := c.Transport.(*Transport)
  5556  
  5557  	get := func() string { return get(t, c, ts.URL) }
  5558  
  5559  	a1, a2 := get(), get()
  5560  	if a1 != a2 {
  5561  		t.Fatal("expected first two requests on same connection")
  5562  	}
  5563  	addr := strings.TrimPrefix(ts.URL, "http://")
  5564  
  5565  	// The two requests should have used the same connection,
  5566  	// and there should not have been a second connection that
  5567  	// was created by racing dial against reuse.
  5568  	// (The first get was completed when the second get started.)
  5569  	n := tr.IdleConnCountForTesting("http", addr)
  5570  	if n != 1 {
  5571  		t.Fatalf("idle count for %q after 2 gets = %d, want 1", addr, n)
  5572  	}
  5573  
  5574  	// SetKeepAlivesEnabled should discard idle conns.
  5575  	ts.Config.SetKeepAlivesEnabled(false)
  5576  
  5577  	var idle1 int
  5578  	if !waitCondition(2*time.Second, 10*time.Millisecond, func() bool {
  5579  		idle1 = tr.IdleConnCountForTesting("http", addr)
  5580  		return idle1 == 0
  5581  	}) {
  5582  		t.Fatalf("idle count after SetKeepAlivesEnabled called = %v; want 0", idle1)
  5583  	}
  5584  
  5585  	a3 := get()
  5586  	if a3 == a2 {
  5587  		t.Fatal("expected third request on new connection")
  5588  	}
  5589  }
  5590  
  5591  func TestServerShutdown_h1(t *testing.T) {
  5592  	testServerShutdown(t, h1Mode)
  5593  }
  5594  func TestServerShutdown_h2(t *testing.T) {
  5595  	testServerShutdown(t, h2Mode)
  5596  }
  5597  
  5598  func testServerShutdown(t *testing.T, h2 bool) {
  5599  	setParallel(t)
  5600  	defer afterTest(t)
  5601  	var doShutdown func() // set later
  5602  	var doStateCount func()
  5603  	var shutdownRes = make(chan error, 1)
  5604  	var statesRes = make(chan map[ConnState]int, 1)
  5605  	var gotOnShutdown = make(chan struct{}, 1)
  5606  	handler := HandlerFunc(func(w ResponseWriter, r *Request) {
  5607  		doStateCount()
  5608  		go doShutdown()
  5609  		// Shutdown is graceful, so it should not interrupt
  5610  		// this in-flight response. Add a tiny sleep here to
  5611  		// increase the odds of a failure if shutdown has
  5612  		// bugs.
  5613  		time.Sleep(20 * time.Millisecond)
  5614  		io.WriteString(w, r.RemoteAddr)
  5615  	})
  5616  	cst := newClientServerTest(t, h2, handler, func(srv *httptest.Server) {
  5617  		srv.Config.RegisterOnShutdown(func() { gotOnShutdown <- struct{}{} })
  5618  	})
  5619  	defer cst.close()
  5620  
  5621  	doShutdown = func() {
  5622  		shutdownRes <- cst.ts.Config.Shutdown(context.Background())
  5623  	}
  5624  	doStateCount = func() {
  5625  		statesRes <- cst.ts.Config.ExportAllConnsByState()
  5626  	}
  5627  	get(t, cst.c, cst.ts.URL) // calls t.Fail on failure
  5628  
  5629  	if err := <-shutdownRes; err != nil {
  5630  		t.Fatalf("Shutdown: %v", err)
  5631  	}
  5632  	select {
  5633  	case <-gotOnShutdown:
  5634  	case <-time.After(5 * time.Second):
  5635  		t.Errorf("onShutdown callback not called, RegisterOnShutdown broken?")
  5636  	}
  5637  
  5638  	if states := <-statesRes; states[StateActive] != 1 {
  5639  		t.Errorf("connection in wrong state, %v", states)
  5640  	}
  5641  
  5642  	res, err := cst.c.Get(cst.ts.URL)
  5643  	if err == nil {
  5644  		res.Body.Close()
  5645  		t.Fatal("second request should fail. server should be shut down")
  5646  	}
  5647  }
  5648  
  5649  func TestServerShutdownStateNew(t *testing.T) {
  5650  	if testing.Short() {
  5651  		t.Skip("test takes 5-6 seconds; skipping in short mode")
  5652  	}
  5653  	setParallel(t)
  5654  	defer afterTest(t)
  5655  
  5656  	ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5657  		// nothing.
  5658  	}))
  5659  	var connAccepted sync.WaitGroup
  5660  	ts.Config.ConnState = func(conn net.Conn, state ConnState) {
  5661  		if state == StateNew {
  5662  			connAccepted.Done()
  5663  		}
  5664  	}
  5665  	ts.Start()
  5666  	defer ts.Close()
  5667  
  5668  	// Start a connection but never write to it.
  5669  	connAccepted.Add(1)
  5670  	c, err := net.Dial("tcp", ts.Listener.Addr().String())
  5671  	if err != nil {
  5672  		t.Fatal(err)
  5673  	}
  5674  	defer c.Close()
  5675  
  5676  	// Wait for the connection to be accepted by the server. Otherwise, if
  5677  	// Shutdown happens to run first, the server will be closed when
  5678  	// encountering the connection, in which case it will be rejected
  5679  	// immediately.
  5680  	connAccepted.Wait()
  5681  
  5682  	shutdownRes := make(chan error, 1)
  5683  	go func() {
  5684  		shutdownRes <- ts.Config.Shutdown(context.Background())
  5685  	}()
  5686  	readRes := make(chan error, 1)
  5687  	go func() {
  5688  		_, err := c.Read([]byte{0})
  5689  		readRes <- err
  5690  	}()
  5691  
  5692  	const expectTimeout = 5 * time.Second
  5693  	t0 := time.Now()
  5694  	select {
  5695  	case got := <-shutdownRes:
  5696  		d := time.Since(t0)
  5697  		if got != nil {
  5698  			t.Fatalf("shutdown error after %v: %v", d, err)
  5699  		}
  5700  		if d < expectTimeout/2 {
  5701  			t.Errorf("shutdown too soon after %v", d)
  5702  		}
  5703  	case <-time.After(expectTimeout * 3 / 2):
  5704  		t.Fatalf("timeout waiting for shutdown")
  5705  	}
  5706  
  5707  	// Wait for c.Read to unblock; should be already done at this point,
  5708  	// or within a few milliseconds.
  5709  	select {
  5710  	case err := <-readRes:
  5711  		if err == nil {
  5712  			t.Error("expected error from Read")
  5713  		}
  5714  	case <-time.After(2 * time.Second):
  5715  		t.Errorf("timeout waiting for Read to unblock")
  5716  	}
  5717  }
  5718  
  5719  // Issue 17878: tests that we can call Close twice.
  5720  func TestServerCloseDeadlock(t *testing.T) {
  5721  	var s Server
  5722  	s.Close()
  5723  	s.Close()
  5724  }
  5725  
  5726  // Issue 17717: tests that Server.SetKeepAlivesEnabled is respected by
  5727  // both HTTP/1 and HTTP/2.
  5728  func TestServerKeepAlivesEnabled_h1(t *testing.T) { testServerKeepAlivesEnabled(t, h1Mode) }
  5729  func TestServerKeepAlivesEnabled_h2(t *testing.T) { testServerKeepAlivesEnabled(t, h2Mode) }
  5730  func testServerKeepAlivesEnabled(t *testing.T, h2 bool) {
  5731  	if h2 {
  5732  		restore := ExportSetH2GoawayTimeout(10 * time.Millisecond)
  5733  		defer restore()
  5734  	}
  5735  	// Not parallel: messes with global variable. (http2goAwayTimeout)
  5736  	defer afterTest(t)
  5737  	cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {}))
  5738  	defer cst.close()
  5739  	srv := cst.ts.Config
  5740  	srv.SetKeepAlivesEnabled(false)
  5741  	for try := 0; try < 2; try++ {
  5742  		if !waitCondition(2*time.Second, 10*time.Millisecond, srv.ExportAllConnsIdle) {
  5743  			t.Fatalf("request %v: test server has active conns", try)
  5744  		}
  5745  		conns := 0
  5746  		var info httptrace.GotConnInfo
  5747  		ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{
  5748  			GotConn: func(v httptrace.GotConnInfo) {
  5749  				conns++
  5750  				info = v
  5751  			},
  5752  		})
  5753  		req, err := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
  5754  		if err != nil {
  5755  			t.Fatal(err)
  5756  		}
  5757  		res, err := cst.c.Do(req)
  5758  		if err != nil {
  5759  			t.Fatal(err)
  5760  		}
  5761  		res.Body.Close()
  5762  		if conns != 1 {
  5763  			t.Fatalf("request %v: got %v conns, want 1", try, conns)
  5764  		}
  5765  		if info.Reused || info.WasIdle {
  5766  			t.Fatalf("request %v: Reused=%v (want false), WasIdle=%v (want false)", try, info.Reused, info.WasIdle)
  5767  		}
  5768  	}
  5769  }
  5770  
  5771  // Issue 18447: test that the Server's ReadTimeout is stopped while
  5772  // the server's doing its 1-byte background read between requests,
  5773  // waiting for the connection to maybe close.
  5774  func TestServerCancelsReadTimeoutWhenIdle(t *testing.T) {
  5775  	setParallel(t)
  5776  	defer afterTest(t)
  5777  	runTimeSensitiveTest(t, []time.Duration{
  5778  		10 * time.Millisecond,
  5779  		50 * time.Millisecond,
  5780  		250 * time.Millisecond,
  5781  		time.Second,
  5782  		2 * time.Second,
  5783  	}, func(t *testing.T, timeout time.Duration) error {
  5784  		ts := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5785  			select {
  5786  			case <-time.After(2 * timeout):
  5787  				fmt.Fprint(w, "ok")
  5788  			case <-r.Context().Done():
  5789  				fmt.Fprint(w, r.Context().Err())
  5790  			}
  5791  		}))
  5792  		ts.Config.ReadTimeout = timeout
  5793  		ts.Start()
  5794  		defer ts.Close()
  5795  
  5796  		c := ts.Client()
  5797  
  5798  		res, err := c.Get(ts.URL)
  5799  		if err != nil {
  5800  			return fmt.Errorf("Get: %v", err)
  5801  		}
  5802  		slurp, err := io.ReadAll(res.Body)
  5803  		res.Body.Close()
  5804  		if err != nil {
  5805  			return fmt.Errorf("Body ReadAll: %v", err)
  5806  		}
  5807  		if string(slurp) != "ok" {
  5808  			return fmt.Errorf("got: %q, want ok", slurp)
  5809  		}
  5810  		return nil
  5811  	})
  5812  }
  5813  
  5814  // runTimeSensitiveTest runs test with the provided durations until one passes.
  5815  // If they all fail, t.Fatal is called with the last one's duration and error value.
  5816  func runTimeSensitiveTest(t *testing.T, durations []time.Duration, test func(t *testing.T, d time.Duration) error) {
  5817  	for i, d := range durations {
  5818  		err := test(t, d)
  5819  		if err == nil {
  5820  			return
  5821  		}
  5822  		if i == len(durations)-1 {
  5823  			t.Fatalf("failed with duration %v: %v", d, err)
  5824  		}
  5825  	}
  5826  }
  5827  
  5828  // Issue 18535: test that the Server doesn't try to do a background
  5829  // read if it's already done one.
  5830  func TestServerDuplicateBackgroundRead(t *testing.T) {
  5831  	if runtime.GOOS == "netbsd" && runtime.GOARCH == "arm" {
  5832  		testenv.SkipFlaky(t, 24826)
  5833  	}
  5834  
  5835  	setParallel(t)
  5836  	defer afterTest(t)
  5837  
  5838  	goroutines := 5
  5839  	requests := 2000
  5840  	if testing.Short() {
  5841  		goroutines = 3
  5842  		requests = 100
  5843  	}
  5844  
  5845  	hts := httptest.NewServer(HandlerFunc(NotFound))
  5846  	defer hts.Close()
  5847  
  5848  	reqBytes := []byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")
  5849  
  5850  	var wg sync.WaitGroup
  5851  	for i := 0; i < goroutines; i++ {
  5852  		wg.Add(1)
  5853  		go func() {
  5854  			defer wg.Done()
  5855  			cn, err := net.Dial("tcp", hts.Listener.Addr().String())
  5856  			if err != nil {
  5857  				t.Error(err)
  5858  				return
  5859  			}
  5860  			defer cn.Close()
  5861  
  5862  			wg.Add(1)
  5863  			go func() {
  5864  				defer wg.Done()
  5865  				io.Copy(io.Discard, cn)
  5866  			}()
  5867  
  5868  			for j := 0; j < requests; j++ {
  5869  				if t.Failed() {
  5870  					return
  5871  				}
  5872  				_, err := cn.Write(reqBytes)
  5873  				if err != nil {
  5874  					t.Error(err)
  5875  					return
  5876  				}
  5877  			}
  5878  		}()
  5879  	}
  5880  	wg.Wait()
  5881  }
  5882  
  5883  // Test that the bufio.Reader returned by Hijack includes any buffered
  5884  // byte (from the Server's backgroundRead) in its buffer. We want the
  5885  // Handler code to be able to tell that a byte is available via
  5886  // bufio.Reader.Buffered(), without resorting to Reading it
  5887  // (potentially blocking) to get at it.
  5888  func TestServerHijackGetsBackgroundByte(t *testing.T) {
  5889  	if runtime.GOOS == "plan9" {
  5890  		t.Skip("skipping test; see https://golang.org/issue/18657")
  5891  	}
  5892  	setParallel(t)
  5893  	defer afterTest(t)
  5894  	done := make(chan struct{})
  5895  	inHandler := make(chan bool, 1)
  5896  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5897  		defer close(done)
  5898  
  5899  		// Tell the client to send more data after the GET request.
  5900  		inHandler <- true
  5901  
  5902  		conn, buf, err := w.(Hijacker).Hijack()
  5903  		if err != nil {
  5904  			t.Error(err)
  5905  			return
  5906  		}
  5907  		defer conn.Close()
  5908  
  5909  		peek, err := buf.Reader.Peek(3)
  5910  		if string(peek) != "foo" || err != nil {
  5911  			t.Errorf("Peek = %q, %v; want foo, nil", peek, err)
  5912  		}
  5913  
  5914  		select {
  5915  		case <-r.Context().Done():
  5916  			t.Error("context unexpectedly canceled")
  5917  		default:
  5918  		}
  5919  	}))
  5920  	defer ts.Close()
  5921  
  5922  	cn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5923  	if err != nil {
  5924  		t.Fatal(err)
  5925  	}
  5926  	defer cn.Close()
  5927  	if _, err := cn.Write([]byte("GET / HTTP/1.1\r\nHost: e.com\r\n\r\n")); err != nil {
  5928  		t.Fatal(err)
  5929  	}
  5930  	<-inHandler
  5931  	if _, err := cn.Write([]byte("foo")); err != nil {
  5932  		t.Fatal(err)
  5933  	}
  5934  
  5935  	if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
  5936  		t.Fatal(err)
  5937  	}
  5938  	select {
  5939  	case <-done:
  5940  	case <-time.After(2 * time.Second):
  5941  		t.Error("timeout")
  5942  	}
  5943  }
  5944  
  5945  // Like TestServerHijackGetsBackgroundByte above but sending a
  5946  // immediate 1MB of data to the server to fill up the server's 4KB
  5947  // buffer.
  5948  func TestServerHijackGetsBackgroundByte_big(t *testing.T) {
  5949  	if runtime.GOOS == "plan9" {
  5950  		t.Skip("skipping test; see https://golang.org/issue/18657")
  5951  	}
  5952  	setParallel(t)
  5953  	defer afterTest(t)
  5954  	done := make(chan struct{})
  5955  	const size = 8 << 10
  5956  	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  5957  		defer close(done)
  5958  
  5959  		conn, buf, err := w.(Hijacker).Hijack()
  5960  		if err != nil {
  5961  			t.Error(err)
  5962  			return
  5963  		}
  5964  		defer conn.Close()
  5965  		slurp, err := io.ReadAll(buf.Reader)
  5966  		if err != nil {
  5967  			t.Errorf("Copy: %v", err)
  5968  		}
  5969  		allX := true
  5970  		for _, v := range slurp {
  5971  			if v != 'x' {
  5972  				allX = false
  5973  			}
  5974  		}
  5975  		if len(slurp) != size {
  5976  			t.Errorf("read %d; want %d", len(slurp), size)
  5977  		} else if !allX {
  5978  			t.Errorf("read %q; want %d 'x'", slurp, size)
  5979  		}
  5980  	}))
  5981  	defer ts.Close()
  5982  
  5983  	cn, err := net.Dial("tcp", ts.Listener.Addr().String())
  5984  	if err != nil {
  5985  		t.Fatal(err)
  5986  	}
  5987  	defer cn.Close()
  5988  	if _, err := fmt.Fprintf(cn, "GET / HTTP/1.1\r\nHost: e.com\r\n\r\n%s",
  5989  		strings.Repeat("x", size)); err != nil {
  5990  		t.Fatal(err)
  5991  	}
  5992  	if err := cn.(*net.TCPConn).CloseWrite(); err != nil {
  5993  		t.Fatal(err)
  5994  	}
  5995  
  5996  	<-done
  5997  }
  5998  
  5999  // Issue 18319: test that the Server validates the request method.
  6000  func TestServerValidatesMethod(t *testing.T) {
  6001  	tests := []struct {
  6002  		method string
  6003  		want   int
  6004  	}{
  6005  		{"GET", 200},
  6006  		{"GE(T", 400},
  6007  	}
  6008  	for _, tt := range tests {
  6009  		conn := &testConn{closec: make(chan bool, 1)}
  6010  		io.WriteString(&conn.readBuf, tt.method+" / HTTP/1.1\r\nHost: foo.example\r\n\r\n")
  6011  
  6012  		ln := &oneConnListener{conn}
  6013  		go Serve(ln, serve(200))
  6014  		<-conn.closec
  6015  		res, err := ReadResponse(bufio.NewReader(&conn.writeBuf), nil)
  6016  		if err != nil {
  6017  			t.Errorf("For %s, ReadResponse: %v", tt.method, res)
  6018  			continue
  6019  		}
  6020  		if res.StatusCode != tt.want {
  6021  			t.Errorf("For %s, Status = %d; want %d", tt.method, res.StatusCode, tt.want)
  6022  		}
  6023  	}
  6024  }
  6025  
  6026  // Listener for TestServerListenNotComparableListener.
  6027  type eofListenerNotComparable []int
  6028  
  6029  func (eofListenerNotComparable) Accept() (net.Conn, error) { return nil, io.EOF }
  6030  func (eofListenerNotComparable) Addr() net.Addr            { return nil }
  6031  func (eofListenerNotComparable) Close() error              { return nil }
  6032  
  6033  // Issue 24812: don't crash on non-comparable Listener
  6034  func TestServerListenNotComparableListener(t *testing.T) {
  6035  	var s Server
  6036  	s.Serve(make(eofListenerNotComparable, 1)) // used to panic
  6037  }
  6038  
  6039  // countCloseListener is a Listener wrapper that counts the number of Close calls.
  6040  type countCloseListener struct {
  6041  	net.Listener
  6042  	closes int32 // atomic
  6043  }
  6044  
  6045  func (p *countCloseListener) Close() error {
  6046  	var err error
  6047  	if n := atomic.AddInt32(&p.closes, 1); n == 1 && p.Listener != nil {
  6048  		err = p.Listener.Close()
  6049  	}
  6050  	return err
  6051  }
  6052  
  6053  // Issue 24803: don't call Listener.Close on Server.Shutdown.
  6054  func TestServerCloseListenerOnce(t *testing.T) {
  6055  	setParallel(t)
  6056  	defer afterTest(t)
  6057  
  6058  	ln := newLocalListener(t)
  6059  	defer ln.Close()
  6060  
  6061  	cl := &countCloseListener{Listener: ln}
  6062  	server := &Server{}
  6063  	sdone := make(chan bool, 1)
  6064  
  6065  	go func() {
  6066  		server.Serve(cl)
  6067  		sdone <- true
  6068  	}()
  6069  	time.Sleep(10 * time.Millisecond)
  6070  	server.Shutdown(context.Background())
  6071  	ln.Close()
  6072  	<-sdone
  6073  
  6074  	nclose := atomic.LoadInt32(&cl.closes)
  6075  	if nclose != 1 {
  6076  		t.Errorf("Close calls = %v; want 1", nclose)
  6077  	}
  6078  }
  6079  
  6080  // Issue 20239: don't block in Serve if Shutdown is called first.
  6081  func TestServerShutdownThenServe(t *testing.T) {
  6082  	var srv Server
  6083  	cl := &countCloseListener{Listener: nil}
  6084  	srv.Shutdown(context.Background())
  6085  	got := srv.Serve(cl)
  6086  	if got != ErrServerClosed {
  6087  		t.Errorf("Serve err = %v; want ErrServerClosed", got)
  6088  	}
  6089  	nclose := atomic.LoadInt32(&cl.closes)
  6090  	if nclose != 1 {
  6091  		t.Errorf("Close calls = %v; want 1", nclose)
  6092  	}
  6093  }
  6094  
  6095  // Issue 23351: document and test behavior of ServeMux with ports
  6096  func TestStripPortFromHost(t *testing.T) {
  6097  	mux := NewServeMux()
  6098  
  6099  	mux.HandleFunc("example.com/", func(w ResponseWriter, r *Request) {
  6100  		fmt.Fprintf(w, "OK")
  6101  	})
  6102  	mux.HandleFunc("example.com:9000/", func(w ResponseWriter, r *Request) {
  6103  		fmt.Fprintf(w, "uh-oh!")
  6104  	})
  6105  
  6106  	req := httptest.NewRequest("GET", "http://example.com:9000/", nil)
  6107  	rw := httptest.NewRecorder()
  6108  
  6109  	mux.ServeHTTP(rw, req)
  6110  
  6111  	response := rw.Body.String()
  6112  	if response != "OK" {
  6113  		t.Errorf("Response gotten was %q", response)
  6114  	}
  6115  }
  6116  
  6117  func TestServerContexts(t *testing.T) {
  6118  	setParallel(t)
  6119  	defer afterTest(t)
  6120  	type baseKey struct{}
  6121  	type connKey struct{}
  6122  	ch := make(chan context.Context, 1)
  6123  	ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  6124  		ch <- r.Context()
  6125  	}))
  6126  	ts.Config.BaseContext = func(ln net.Listener) context.Context {
  6127  		if strings.Contains(reflect.TypeOf(ln).String(), "onceClose") {
  6128  			t.Errorf("unexpected onceClose listener type %T", ln)
  6129  		}
  6130  		return context.WithValue(context.Background(), baseKey{}, "base")
  6131  	}
  6132  	ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
  6133  		if got, want := ctx.Value(baseKey{}), "base"; got != want {
  6134  			t.Errorf("in ConnContext, base context key = %#v; want %q", got, want)
  6135  		}
  6136  		return context.WithValue(ctx, connKey{}, "conn")
  6137  	}
  6138  	ts.Start()
  6139  	defer ts.Close()
  6140  	res, err := ts.Client().Get(ts.URL)
  6141  	if err != nil {
  6142  		t.Fatal(err)
  6143  	}
  6144  	res.Body.Close()
  6145  	ctx := <-ch
  6146  	if got, want := ctx.Value(baseKey{}), "base"; got != want {
  6147  		t.Errorf("base context key = %#v; want %q", got, want)
  6148  	}
  6149  	if got, want := ctx.Value(connKey{}), "conn"; got != want {
  6150  		t.Errorf("conn context key = %#v; want %q", got, want)
  6151  	}
  6152  }
  6153  
  6154  func TestServerContextsHTTP2(t *testing.T) {
  6155  	setParallel(t)
  6156  	defer afterTest(t)
  6157  	type baseKey struct{}
  6158  	type connKey struct{}
  6159  	ch := make(chan context.Context, 1)
  6160  	ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  6161  		if r.ProtoMajor != 2 {
  6162  			t.Errorf("unexpected HTTP/1.x request")
  6163  		}
  6164  		ch <- r.Context()
  6165  	}))
  6166  	ts.Config.BaseContext = func(ln net.Listener) context.Context {
  6167  		if strings.Contains(reflect.TypeOf(ln).String(), "onceClose") {
  6168  			t.Errorf("unexpected onceClose listener type %T", ln)
  6169  		}
  6170  		return context.WithValue(context.Background(), baseKey{}, "base")
  6171  	}
  6172  	ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
  6173  		if got, want := ctx.Value(baseKey{}), "base"; got != want {
  6174  			t.Errorf("in ConnContext, base context key = %#v; want %q", got, want)
  6175  		}
  6176  		return context.WithValue(ctx, connKey{}, "conn")
  6177  	}
  6178  	ts.TLS = &tls.Config{
  6179  		NextProtos: []string{"h2", "http/1.1"},
  6180  	}
  6181  	ts.StartTLS()
  6182  	defer ts.Close()
  6183  	ts.Client().Transport.(*Transport).ForceAttemptHTTP2 = true
  6184  	res, err := ts.Client().Get(ts.URL)
  6185  	if err != nil {
  6186  		t.Fatal(err)
  6187  	}
  6188  	res.Body.Close()
  6189  	ctx := <-ch
  6190  	if got, want := ctx.Value(baseKey{}), "base"; got != want {
  6191  		t.Errorf("base context key = %#v; want %q", got, want)
  6192  	}
  6193  	if got, want := ctx.Value(connKey{}), "conn"; got != want {
  6194  		t.Errorf("conn context key = %#v; want %q", got, want)
  6195  	}
  6196  }
  6197  
  6198  // Issue 35750: check ConnContext not modifying context for other connections
  6199  func TestConnContextNotModifyingAllContexts(t *testing.T) {
  6200  	setParallel(t)
  6201  	defer afterTest(t)
  6202  	type connKey struct{}
  6203  	ts := httptest.NewUnstartedServer(HandlerFunc(func(rw ResponseWriter, r *Request) {
  6204  		rw.Header().Set("Connection", "close")
  6205  	}))
  6206  	ts.Config.ConnContext = func(ctx context.Context, c net.Conn) context.Context {
  6207  		if got := ctx.Value(connKey{}); got != nil {
  6208  			t.Errorf("in ConnContext, unexpected context key = %#v", got)
  6209  		}
  6210  		return context.WithValue(ctx, connKey{}, "conn")
  6211  	}
  6212  	ts.Start()
  6213  	defer ts.Close()
  6214  
  6215  	var res *Response
  6216  	var err error
  6217  
  6218  	res, err = ts.Client().Get(ts.URL)
  6219  	if err != nil {
  6220  		t.Fatal(err)
  6221  	}
  6222  	res.Body.Close()
  6223  
  6224  	res, err = ts.Client().Get(ts.URL)
  6225  	if err != nil {
  6226  		t.Fatal(err)
  6227  	}
  6228  	res.Body.Close()
  6229  }
  6230  
  6231  // Issue 30710: ensure that as per the spec, a server responds
  6232  // with 501 Not Implemented for unsupported transfer-encodings.
  6233  func TestUnsupportedTransferEncodingsReturn501(t *testing.T) {
  6234  	cst := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  6235  		w.Write([]byte("Hello, World!"))
  6236  	}))
  6237  	defer cst.Close()
  6238  
  6239  	serverURL, err := url.Parse(cst.URL)
  6240  	if err != nil {
  6241  		t.Fatalf("Failed to parse server URL: %v", err)
  6242  	}
  6243  
  6244  	unsupportedTEs := []string{
  6245  		"fugazi",
  6246  		"foo-bar",
  6247  		"unknown",
  6248  		"\rchunked",
  6249  	}
  6250  
  6251  	for _, badTE := range unsupportedTEs {
  6252  		http1ReqBody := fmt.Sprintf(""+
  6253  			"POST / HTTP/1.1\r\nConnection: close\r\n"+
  6254  			"Host: localhost\r\nTransfer-Encoding: %s\r\n\r\n", badTE)
  6255  
  6256  		gotBody, err := fetchWireResponse(serverURL.Host, []byte(http1ReqBody))
  6257  		if err != nil {
  6258  			t.Errorf("%q. unexpected error: %v", badTE, err)
  6259  			continue
  6260  		}
  6261  
  6262  		wantBody := fmt.Sprintf("" +
  6263  			"HTTP/1.1 501 Not Implemented\r\nContent-Type: text/plain; charset=utf-8\r\n" +
  6264  			"Connection: close\r\n\r\nUnsupported transfer encoding")
  6265  
  6266  		if string(gotBody) != wantBody {
  6267  			t.Errorf("%q. body\ngot\n%q\nwant\n%q", badTE, gotBody, wantBody)
  6268  		}
  6269  	}
  6270  }
  6271  
  6272  func TestContentEncodingNoSniffing_h1(t *testing.T) {
  6273  	testContentEncodingNoSniffing(t, h1Mode)
  6274  }
  6275  
  6276  func TestContentEncodingNoSniffing_h2(t *testing.T) {
  6277  	testContentEncodingNoSniffing(t, h2Mode)
  6278  }
  6279  
  6280  // Issue 31753: don't sniff when Content-Encoding is set
  6281  func testContentEncodingNoSniffing(t *testing.T, h2 bool) {
  6282  	setParallel(t)
  6283  	defer afterTest(t)
  6284  
  6285  	type setting struct {
  6286  		name string
  6287  		body []byte
  6288  
  6289  		// setting contentEncoding as an interface instead of a string
  6290  		// directly, so as to differentiate between 3 states:
  6291  		//    unset, empty string "" and set string "foo/bar".
  6292  		contentEncoding any
  6293  		wantContentType string
  6294  	}
  6295  
  6296  	settings := []*setting{
  6297  		{
  6298  			name:            "gzip content-encoding, gzipped", // don't sniff.
  6299  			contentEncoding: "application/gzip",
  6300  			wantContentType: "",
  6301  			body: func() []byte {
  6302  				buf := new(bytes.Buffer)
  6303  				gzw := gzip.NewWriter(buf)
  6304  				gzw.Write([]byte("doctype html><p>Hello</p>"))
  6305  				gzw.Close()
  6306  				return buf.Bytes()
  6307  			}(),
  6308  		},
  6309  		{
  6310  			name:            "zlib content-encoding, zlibbed", // don't sniff.
  6311  			contentEncoding: "application/zlib",
  6312  			wantContentType: "",
  6313  			body: func() []byte {
  6314  				buf := new(bytes.Buffer)
  6315  				zw := zlib.NewWriter(buf)
  6316  				zw.Write([]byte("doctype html><p>Hello</p>"))
  6317  				zw.Close()
  6318  				return buf.Bytes()
  6319  			}(),
  6320  		},
  6321  		{
  6322  			name:            "no content-encoding", // must sniff.
  6323  			wantContentType: "application/x-gzip",
  6324  			body: func() []byte {
  6325  				buf := new(bytes.Buffer)
  6326  				gzw := gzip.NewWriter(buf)
  6327  				gzw.Write([]byte("doctype html><p>Hello</p>"))
  6328  				gzw.Close()
  6329  				return buf.Bytes()
  6330  			}(),
  6331  		},
  6332  		{
  6333  			name:            "phony content-encoding", // don't sniff.
  6334  			contentEncoding: "foo/bar",
  6335  			body:            []byte("doctype html><p>Hello</p>"),
  6336  		},
  6337  		{
  6338  			name:            "empty but set content-encoding",
  6339  			contentEncoding: "",
  6340  			wantContentType: "audio/mpeg",
  6341  			body:            []byte("ID3"),
  6342  		},
  6343  	}
  6344  
  6345  	for _, tt := range settings {
  6346  		t.Run(tt.name, func(t *testing.T) {
  6347  			cst := newClientServerTest(t, h2, HandlerFunc(func(rw ResponseWriter, r *Request) {
  6348  				if tt.contentEncoding != nil {
  6349  					rw.Header().Set("Content-Encoding", tt.contentEncoding.(string))
  6350  				}
  6351  				rw.Write(tt.body)
  6352  			}))
  6353  			defer cst.close()
  6354  
  6355  			res, err := cst.c.Get(cst.ts.URL)
  6356  			if err != nil {
  6357  				t.Fatalf("Failed to fetch URL: %v", err)
  6358  			}
  6359  			defer res.Body.Close()
  6360  
  6361  			if g, w := res.Header.Get("Content-Encoding"), tt.contentEncoding; g != w {
  6362  				if w != nil { // The case where contentEncoding was set explicitly.
  6363  					t.Errorf("Content-Encoding mismatch\n\tgot:  %q\n\twant: %q", g, w)
  6364  				} else if g != "" { // "" should be the equivalent when the contentEncoding is unset.
  6365  					t.Errorf("Unexpected Content-Encoding %q", g)
  6366  				}
  6367  			}
  6368  
  6369  			if g, w := res.Header.Get("Content-Type"), tt.wantContentType; g != w {
  6370  				t.Errorf("Content-Type mismatch\n\tgot:  %q\n\twant: %q", g, w)
  6371  			}
  6372  		})
  6373  	}
  6374  }
  6375  
  6376  // Issue 30803: ensure that TimeoutHandler logs spurious
  6377  // WriteHeader calls, for consistency with other Handlers.
  6378  func TestTimeoutHandlerSuperfluousLogs(t *testing.T) {
  6379  	if testing.Short() {
  6380  		t.Skip("skipping in short mode")
  6381  	}
  6382  
  6383  	setParallel(t)
  6384  	defer afterTest(t)
  6385  
  6386  	pc, curFile, _, _ := runtime.Caller(0)
  6387  	curFileBaseName := filepath.Base(curFile)
  6388  	testFuncName := runtime.FuncForPC(pc).Name()
  6389  
  6390  	timeoutMsg := "timed out here!"
  6391  
  6392  	tests := []struct {
  6393  		name        string
  6394  		mustTimeout bool
  6395  		wantResp    string
  6396  	}{
  6397  		{
  6398  			name:     "return before timeout",
  6399  			wantResp: "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n",
  6400  		},
  6401  		{
  6402  			name:        "return after timeout",
  6403  			mustTimeout: true,
  6404  			wantResp: fmt.Sprintf("HTTP/1.1 503 Service Unavailable\r\nContent-Length: %d\r\n\r\n%s",
  6405  				len(timeoutMsg), timeoutMsg),
  6406  		},
  6407  	}
  6408  
  6409  	for _, tt := range tests {
  6410  		tt := tt
  6411  		t.Run(tt.name, func(t *testing.T) {
  6412  			exitHandler := make(chan bool, 1)
  6413  			defer close(exitHandler)
  6414  			lastLine := make(chan int, 1)
  6415  
  6416  			sh := HandlerFunc(func(w ResponseWriter, r *Request) {
  6417  				w.WriteHeader(404)
  6418  				w.WriteHeader(404)
  6419  				w.WriteHeader(404)
  6420  				w.WriteHeader(404)
  6421  				_, _, line, _ := runtime.Caller(0)
  6422  				lastLine <- line
  6423  				<-exitHandler
  6424  			})
  6425  
  6426  			if !tt.mustTimeout {
  6427  				exitHandler <- true
  6428  			}
  6429  
  6430  			logBuf := new(bytes.Buffer)
  6431  			srvLog := log.New(logBuf, "", 0)
  6432  			// When expecting to timeout, we'll keep the duration short.
  6433  			dur := 20 * time.Millisecond
  6434  			if !tt.mustTimeout {
  6435  				// Otherwise, make it arbitrarily long to reduce the risk of flakes.
  6436  				dur = 10 * time.Second
  6437  			}
  6438  			th := TimeoutHandler(sh, dur, timeoutMsg)
  6439  			cst := newClientServerTest(t, h1Mode /* the test is protocol-agnostic */, th, optWithServerLog(srvLog))
  6440  			defer cst.close()
  6441  
  6442  			res, err := cst.c.Get(cst.ts.URL)
  6443  			if err != nil {
  6444  				t.Fatalf("Unexpected error: %v", err)
  6445  			}
  6446  
  6447  			// Deliberately removing the "Date" header since it is highly ephemeral
  6448  			// and will cause failure if we try to match it exactly.
  6449  			res.Header.Del("Date")
  6450  			res.Header.Del("Content-Type")
  6451  
  6452  			// Match the response.
  6453  			blob, _ := httputil.DumpResponse(res, true)
  6454  			if g, w := string(blob), tt.wantResp; g != w {
  6455  				t.Errorf("Response mismatch\nGot\n%q\n\nWant\n%q", g, w)
  6456  			}
  6457  
  6458  			// Given 4 w.WriteHeader calls, only the first one is valid
  6459  			// and the rest should be reported as the 3 spurious logs.
  6460  			logEntries := strings.Split(strings.TrimSpace(logBuf.String()), "\n")
  6461  			if g, w := len(logEntries), 3; g != w {
  6462  				blob, _ := json.MarshalIndent(logEntries, "", "  ")
  6463  				t.Fatalf("Server logs count mismatch\ngot %d, want %d\n\nGot\n%s\n", g, w, blob)
  6464  			}
  6465  
  6466  			lastSpuriousLine := <-lastLine
  6467  			firstSpuriousLine := lastSpuriousLine - 3
  6468  			// Now ensure that the regexes match exactly.
  6469  			//      "http: superfluous response.WriteHeader call from <fn>.func\d.\d (<curFile>:lastSpuriousLine-[1, 3]"
  6470  			for i, logEntry := range logEntries {
  6471  				wantLine := firstSpuriousLine + i
  6472  				pat := fmt.Sprintf("^http: superfluous response.WriteHeader call from %s.func\\d+.\\d+ \\(%s:%d\\)$",
  6473  					testFuncName, curFileBaseName, wantLine)
  6474  				re := regexp.MustCompile(pat)
  6475  				if !re.MatchString(logEntry) {
  6476  					t.Errorf("Log entry mismatch\n\t%s\ndoes not match\n\t%s", logEntry, pat)
  6477  				}
  6478  			}
  6479  		})
  6480  	}
  6481  }
  6482  
  6483  // fetchWireResponse is a helper for dialing to host,
  6484  // sending http1ReqBody as the payload and retrieving
  6485  // the response as it was sent on the wire.
  6486  func fetchWireResponse(host string, http1ReqBody []byte) ([]byte, error) {
  6487  	conn, err := net.Dial("tcp", host)
  6488  	if err != nil {
  6489  		return nil, err
  6490  	}
  6491  	defer conn.Close()
  6492  
  6493  	if _, err := conn.Write(http1ReqBody); err != nil {
  6494  		return nil, err
  6495  	}
  6496  	return io.ReadAll(conn)
  6497  }
  6498  
  6499  func BenchmarkResponseStatusLine(b *testing.B) {
  6500  	b.ReportAllocs()
  6501  	b.RunParallel(func(pb *testing.PB) {
  6502  		bw := bufio.NewWriter(io.Discard)
  6503  		var buf3 [3]byte
  6504  		for pb.Next() {
  6505  			Export_writeStatusLine(bw, true, 200, buf3[:])
  6506  		}
  6507  	})
  6508  }
  6509  func TestDisableKeepAliveUpgrade(t *testing.T) {
  6510  	if testing.Short() {
  6511  		t.Skip("skipping in short mode")
  6512  	}
  6513  
  6514  	setParallel(t)
  6515  	defer afterTest(t)
  6516  
  6517  	s := httptest.NewUnstartedServer(HandlerFunc(func(w ResponseWriter, r *Request) {
  6518  		w.Header().Set("Connection", "Upgrade")
  6519  		w.Header().Set("Upgrade", "someProto")
  6520  		w.WriteHeader(StatusSwitchingProtocols)
  6521  		c, buf, err := w.(Hijacker).Hijack()
  6522  		if err != nil {
  6523  			return
  6524  		}
  6525  		defer c.Close()
  6526  
  6527  		// Copy from the *bufio.ReadWriter, which may contain buffered data.
  6528  		// Copy to the net.Conn, to avoid buffering the output.
  6529  		io.Copy(c, buf)
  6530  	}))
  6531  	s.Config.SetKeepAlivesEnabled(false)
  6532  	s.Start()
  6533  	defer s.Close()
  6534  
  6535  	cl := s.Client()
  6536  	cl.Transport.(*Transport).DisableKeepAlives = true
  6537  
  6538  	resp, err := cl.Get(s.URL)
  6539  	if err != nil {
  6540  		t.Fatalf("failed to perform request: %v", err)
  6541  	}
  6542  	defer resp.Body.Close()
  6543  
  6544  	if resp.StatusCode != StatusSwitchingProtocols {
  6545  		t.Fatalf("unexpected status code: %v", resp.StatusCode)
  6546  	}
  6547  
  6548  	rwc, ok := resp.Body.(io.ReadWriteCloser)
  6549  	if !ok {
  6550  		t.Fatalf("Response.Body is not an io.ReadWriteCloser: %T", resp.Body)
  6551  	}
  6552  
  6553  	_, err = rwc.Write([]byte("hello"))
  6554  	if err != nil {
  6555  		t.Fatalf("failed to write to body: %v", err)
  6556  	}
  6557  
  6558  	b := make([]byte, 5)
  6559  	_, err = io.ReadFull(rwc, b)
  6560  	if err != nil {
  6561  		t.Fatalf("failed to read from body: %v", err)
  6562  	}
  6563  
  6564  	if string(b) != "hello" {
  6565  		t.Fatalf("unexpected value read from body:\ngot: %q\nwant: %q", b, "hello")
  6566  	}
  6567  }
  6568  
  6569  func TestMuxRedirectRelative(t *testing.T) {
  6570  	setParallel(t)
  6571  	req, err := ReadRequest(bufio.NewReader(strings.NewReader("GET http://example.com HTTP/1.1\r\nHost: test\r\n\r\n")))
  6572  	if err != nil {
  6573  		t.Errorf("%s", err)
  6574  	}
  6575  	mux := NewServeMux()
  6576  	resp := httptest.NewRecorder()
  6577  	mux.ServeHTTP(resp, req)
  6578  	if got, want := resp.Header().Get("Location"), "/"; got != want {
  6579  		t.Errorf("Location header expected %q; got %q", want, got)
  6580  	}
  6581  	if got, want := resp.Code, StatusMovedPermanently; got != want {
  6582  		t.Errorf("Expected response code %d; got %d", want, got)
  6583  	}
  6584  }
  6585  
  6586  // TestQuerySemicolon tests the behavior of semicolons in queries. See Issue 25192.
  6587  func TestQuerySemicolon(t *testing.T) {
  6588  	t.Cleanup(func() { afterTest(t) })
  6589  
  6590  	tests := []struct {
  6591  		query           string
  6592  		xNoSemicolons   string
  6593  		xWithSemicolons string
  6594  		warning         bool
  6595  	}{
  6596  		{"?a=1;x=bad&x=good", "good", "bad", true},
  6597  		{"?a=1;b=bad&x=good", "good", "good", true},
  6598  		{"?a=1%3Bx=bad&x=good%3B", "good;", "good;", false},
  6599  		{"?a=1;x=good;x=bad", "", "good", true},
  6600  	}
  6601  
  6602  	for _, tt := range tests {
  6603  		t.Run(tt.query+"/allow=false", func(t *testing.T) {
  6604  			allowSemicolons := false
  6605  			testQuerySemicolon(t, tt.query, tt.xNoSemicolons, allowSemicolons, tt.warning)
  6606  		})
  6607  		t.Run(tt.query+"/allow=true", func(t *testing.T) {
  6608  			allowSemicolons, expectWarning := true, false
  6609  			testQuerySemicolon(t, tt.query, tt.xWithSemicolons, allowSemicolons, expectWarning)
  6610  		})
  6611  	}
  6612  }
  6613  
  6614  func testQuerySemicolon(t *testing.T, query string, wantX string, allowSemicolons, expectWarning bool) {
  6615  	setParallel(t)
  6616  
  6617  	writeBackX := func(w ResponseWriter, r *Request) {
  6618  		x := r.URL.Query().Get("x")
  6619  		if expectWarning {
  6620  			if err := r.ParseForm(); err == nil || !strings.Contains(err.Error(), "semicolon") {
  6621  				t.Errorf("expected error mentioning semicolons from ParseForm, got %v", err)
  6622  			}
  6623  		} else {
  6624  			if err := r.ParseForm(); err != nil {
  6625  				t.Errorf("expected no error from ParseForm, got %v", err)
  6626  			}
  6627  		}
  6628  		if got := r.FormValue("x"); x != got {
  6629  			t.Errorf("got %q from FormValue, want %q", got, x)
  6630  		}
  6631  		fmt.Fprintf(w, "%s", x)
  6632  	}
  6633  
  6634  	h := Handler(HandlerFunc(writeBackX))
  6635  	if allowSemicolons {
  6636  		h = AllowQuerySemicolons(h)
  6637  	}
  6638  
  6639  	ts := httptest.NewUnstartedServer(h)
  6640  	logBuf := &bytes.Buffer{}
  6641  	ts.Config.ErrorLog = log.New(logBuf, "", 0)
  6642  	ts.Start()
  6643  	defer ts.Close()
  6644  
  6645  	req, _ := NewRequest("GET", ts.URL+query, nil)
  6646  	res, err := ts.Client().Do(req)
  6647  	if err != nil {
  6648  		t.Fatal(err)
  6649  	}
  6650  	slurp, _ := io.ReadAll(res.Body)
  6651  	res.Body.Close()
  6652  	if got, want := res.StatusCode, 200; got != want {
  6653  		t.Errorf("Status = %d; want = %d", got, want)
  6654  	}
  6655  	if got, want := string(slurp), wantX; got != want {
  6656  		t.Errorf("Body = %q; want = %q", got, want)
  6657  	}
  6658  
  6659  	if expectWarning {
  6660  		if !strings.Contains(logBuf.String(), "semicolon") {
  6661  			t.Errorf("got %q from ErrorLog, expected a mention of semicolons", logBuf.String())
  6662  		}
  6663  	} else {
  6664  		if strings.Contains(logBuf.String(), "semicolon") {
  6665  			t.Errorf("got %q from ErrorLog, expected no mention of semicolons", logBuf.String())
  6666  		}
  6667  	}
  6668  }
  6669  
  6670  func TestMaxBytesHandler(t *testing.T) {
  6671  	setParallel(t)
  6672  	defer afterTest(t)
  6673  
  6674  	for _, maxSize := range []int64{100, 1_000, 1_000_000} {
  6675  		for _, requestSize := range []int64{100, 1_000, 1_000_000} {
  6676  			t.Run(fmt.Sprintf("max size %d request size %d", maxSize, requestSize),
  6677  				func(t *testing.T) {
  6678  					testMaxBytesHandler(t, maxSize, requestSize)
  6679  				})
  6680  		}
  6681  	}
  6682  }
  6683  
  6684  func testMaxBytesHandler(t *testing.T, maxSize, requestSize int64) {
  6685  	var (
  6686  		handlerN   int64
  6687  		handlerErr error
  6688  	)
  6689  	echo := HandlerFunc(func(w ResponseWriter, r *Request) {
  6690  		var buf bytes.Buffer
  6691  		handlerN, handlerErr = io.Copy(&buf, r.Body)
  6692  		io.Copy(w, &buf)
  6693  	})
  6694  
  6695  	ts := httptest.NewServer(MaxBytesHandler(echo, maxSize))
  6696  	defer ts.Close()
  6697  
  6698  	c := ts.Client()
  6699  	var buf strings.Builder
  6700  	body := strings.NewReader(strings.Repeat("a", int(requestSize)))
  6701  	res, err := c.Post(ts.URL, "text/plain", body)
  6702  	if err != nil {
  6703  		t.Errorf("unexpected connection error: %v", err)
  6704  	} else {
  6705  		_, err = io.Copy(&buf, res.Body)
  6706  		res.Body.Close()
  6707  		if err != nil {
  6708  			t.Errorf("unexpected read error: %v", err)
  6709  		}
  6710  	}
  6711  	if handlerN > maxSize {
  6712  		t.Errorf("expected max request body %d; got %d", maxSize, handlerN)
  6713  	}
  6714  	if requestSize > maxSize && handlerErr == nil {
  6715  		t.Error("expected error on handler side; got nil")
  6716  	}
  6717  	if requestSize <= maxSize {
  6718  		if handlerErr != nil {
  6719  			t.Errorf("%d expected nil error on handler side; got %v", requestSize, handlerErr)
  6720  		}
  6721  		if handlerN != requestSize {
  6722  			t.Errorf("expected request of size %d; got %d", requestSize, handlerN)
  6723  		}
  6724  	}
  6725  	if buf.Len() != int(handlerN) {
  6726  		t.Errorf("expected echo of size %d; got %d", handlerN, buf.Len())
  6727  	}
  6728  }
  6729  
  6730  func TestEarlyHints(t *testing.T) {
  6731  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  6732  		h := w.Header()
  6733  		h.Add("Link", "</style.css>; rel=preload; as=style")
  6734  		h.Add("Link", "</script.js>; rel=preload; as=script")
  6735  		w.WriteHeader(StatusEarlyHints)
  6736  
  6737  		h.Add("Link", "</foo.js>; rel=preload; as=script")
  6738  		w.WriteHeader(StatusEarlyHints)
  6739  
  6740  		w.Write([]byte("stuff"))
  6741  	}))
  6742  
  6743  	got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org")
  6744  	expected := "HTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload; as=style\r\nLink: </script.js>; rel=preload; as=script\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload; as=style\r\nLink: </script.js>; rel=preload; as=script\r\nLink: </foo.js>; rel=preload; as=script\r\n\r\nHTTP/1.1 200 OK\r\nLink: </style.css>; rel=preload; as=style\r\nLink: </script.js>; rel=preload; as=script\r\nLink: </foo.js>; rel=preload; as=script\r\nDate: " // dynamic content expected
  6745  	if !strings.Contains(got, expected) {
  6746  		t.Errorf("unexpected response; got %q; should start by %q", got, expected)
  6747  	}
  6748  }
  6749  func TestProcessing(t *testing.T) {
  6750  	ht := newHandlerTest(HandlerFunc(func(w ResponseWriter, r *Request) {
  6751  		w.WriteHeader(StatusProcessing)
  6752  		w.Write([]byte("stuff"))
  6753  	}))
  6754  
  6755  	got := ht.rawResponse("GET / HTTP/1.1\nHost: golang.org")
  6756  	expected := "HTTP/1.1 102 Processing\r\n\r\nHTTP/1.1 200 OK\r\nDate: " // dynamic content expected
  6757  	if !strings.Contains(got, expected) {
  6758  		t.Errorf("unexpected response; got %q; should start by %q", got, expected)
  6759  	}
  6760  }
  6761  

View as plain text