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