| 1 |
// Copyright 2015 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 |
// Tests that use both the client & server, in both HTTP/1 and HTTP/2 mode. |
| 6 |
|
| 7 |
package http_test |
| 8 |
|
| 9 |
import ( |
| 10 |
"bytes" |
| 11 |
"compress/gzip" |
| 12 |
"context" |
| 13 |
"crypto/rand" |
| 14 |
"crypto/sha1" |
| 15 |
"crypto/tls" |
| 16 |
"fmt" |
| 17 |
"hash" |
| 18 |
"io" |
| 19 |
"log" |
| 20 |
"maps" |
| 21 |
"net" |
| 22 |
. "net/http" |
| 23 |
"net/http/httptest" |
| 24 |
"net/http/httptrace" |
| 25 |
"net/http/httputil" |
| 26 |
"net/textproto" |
| 27 |
"net/url" |
| 28 |
"os" |
| 29 |
"reflect" |
| 30 |
"runtime" |
| 31 |
"slices" |
| 32 |
"strings" |
| 33 |
"sync" |
| 34 |
"sync/atomic" |
| 35 |
"testing" |
| 36 |
"testing/synctest" |
| 37 |
"time" |
| 38 |
) |
| 39 |
|
| 40 |
type testMode string |
| 41 |
|
| 42 |
const ( |
| 43 |
http1Mode = testMode("h1") // HTTP/1.1 |
| 44 |
https1Mode = testMode("https1") // HTTPS/1.1 |
| 45 |
http2Mode = testMode("h2") // HTTP/2 |
| 46 |
http2UnencryptedMode = testMode("h2unencrypted") // HTTP/2 |
| 47 |
) |
| 48 |
|
| 49 |
type ( |
| 50 |
testAddMode []testMode // default, plus these |
| 51 |
testSkipMode []testMode // default, minus these |
| 52 |
) |
| 53 |
|
| 54 |
func (m testMode) Scheme() string { |
| 55 |
switch m { |
| 56 |
case http1Mode, http2UnencryptedMode: |
| 57 |
return "http" |
| 58 |
case https1Mode, http2Mode: |
| 59 |
return "https" |
| 60 |
} |
| 61 |
panic("unknown testMode") |
| 62 |
} |
| 63 |
|
| 64 |
type testNotParallelOpt struct{} |
| 65 |
|
| 66 |
var ( |
| 67 |
testNotParallel = testNotParallelOpt{} |
| 68 |
) |
| 69 |
|
| 70 |
type TBRun[T any] interface { |
| 71 |
testing.TB |
| 72 |
Run(string, func(T)) bool |
| 73 |
} |
| 74 |
|
| 75 |
// run runs a client/server test in a variety of test configurations. |
| 76 |
// |
| 77 |
// Tests execute in HTTP/1.1 and HTTP/2 modes by default. |
| 78 |
// To run in a different set of configurations, pass a []testMode option. |
| 79 |
// |
| 80 |
// Tests call t.Parallel() by default. |
| 81 |
// To disable parallel execution, pass the testNotParallel option. |
| 82 |
func run[T TBRun[T]](t T, f func(t T, mode testMode), opts ...any) { |
| 83 |
t.Helper() |
| 84 |
modes := []testMode{http1Mode, http2Mode} |
| 85 |
parallel := true |
| 86 |
for _, opt := range opts { |
| 87 |
switch opt := opt.(type) { |
| 88 |
case testAddMode: |
| 89 |
for _, m := range opt { |
| 90 |
if !slices.Contains(modes, m) { |
| 91 |
modes = append(modes, m) |
| 92 |
} |
| 93 |
} |
| 94 |
case testSkipMode: |
| 95 |
modes = slices.DeleteFunc(modes, func(m testMode) bool { |
| 96 |
return slices.Contains(opt, m) |
| 97 |
}) |
| 98 |
case []testMode: |
| 99 |
modes = opt |
| 100 |
case testNotParallelOpt: |
| 101 |
parallel = false |
| 102 |
default: |
| 103 |
t.Fatalf("unknown option type %T", opt) |
| 104 |
} |
| 105 |
} |
| 106 |
if t, ok := any(t).(*testing.T); ok && parallel { |
| 107 |
setParallel(t) |
| 108 |
} |
| 109 |
for _, mode := range modes { |
| 110 |
t.Run(string(mode), func(t T) { |
| 111 |
t.Helper() |
| 112 |
if t, ok := any(t).(*testing.T); ok && parallel { |
| 113 |
setParallel(t) |
| 114 |
} |
| 115 |
t.Cleanup(func() { |
| 116 |
afterTest(t) |
| 117 |
}) |
| 118 |
f(t, mode) |
| 119 |
}) |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
// runSynctest is run combined with synctest.Run. |
| 124 |
// |
| 125 |
// The TB passed to f arranges for cleanup functions to be run in the synctest bubble. |
| 126 |
func runSynctest(t *testing.T, f func(t *testing.T, mode testMode), opts ...any) { |
| 127 |
run(t, func(t *testing.T, mode testMode) { |
| 128 |
synctest.Test(t, func(t *testing.T) { |
| 129 |
f(t, mode) |
| 130 |
}) |
| 131 |
}, opts...) |
| 132 |
} |
| 133 |
|
| 134 |
type clientServerTest struct { |
| 135 |
t testing.TB |
| 136 |
h2 bool |
| 137 |
h Handler |
| 138 |
ts *httptest.Server |
| 139 |
tr *Transport |
| 140 |
c *Client |
| 141 |
li *fakeNetListener |
| 142 |
} |
| 143 |
|
| 144 |
func (t *clientServerTest) close() { |
| 145 |
t.tr.CloseIdleConnections() |
| 146 |
t.ts.Close() |
| 147 |
} |
| 148 |
|
| 149 |
func (t *clientServerTest) getURL(u string) string { |
| 150 |
res, err := t.c.Get(u) |
| 151 |
if err != nil { |
| 152 |
t.t.Fatal(err) |
| 153 |
} |
| 154 |
defer res.Body.Close() |
| 155 |
slurp, err := io.ReadAll(res.Body) |
| 156 |
if err != nil { |
| 157 |
t.t.Fatal(err) |
| 158 |
} |
| 159 |
return string(slurp) |
| 160 |
} |
| 161 |
|
| 162 |
func (t *clientServerTest) scheme() string { |
| 163 |
if t.h2 { |
| 164 |
return "https" |
| 165 |
} |
| 166 |
return "http" |
| 167 |
} |
| 168 |
|
| 169 |
var optQuietLog = func(ts *httptest.Server) { |
| 170 |
ts.Config.ErrorLog = quietLog |
| 171 |
} |
| 172 |
|
| 173 |
func optWithServerLog(lg *log.Logger) func(*httptest.Server) { |
| 174 |
return func(ts *httptest.Server) { |
| 175 |
ts.Config.ErrorLog = lg |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
var optFakeNet = new(struct{}) |
| 180 |
|
| 181 |
// newClientServerTest creates and starts an httptest.Server. |
| 182 |
// |
| 183 |
// The mode parameter selects the implementation to test: |
| 184 |
// HTTP/1, HTTP/2, etc. Tests using newClientServerTest should use |
| 185 |
// the 'run' function, which will start a subtests for each tested mode. |
| 186 |
// |
| 187 |
// The vararg opts parameter can include functions to configure the |
| 188 |
// test server or transport. |
| 189 |
// |
| 190 |
// func(*httptest.Server) // run before starting the server |
| 191 |
// func(*http.Transport) |
| 192 |
// |
| 193 |
// The optFakeNet option configures the server and client to use a fake network implementation, |
| 194 |
// suitable for use in testing/synctest tests. |
| 195 |
func newClientServerTest(t testing.TB, mode testMode, h Handler, opts ...any) *clientServerTest { |
| 196 |
if mode == http2Mode || mode == http2UnencryptedMode { |
| 197 |
CondSkipHTTP2(t) |
| 198 |
} |
| 199 |
cst := &clientServerTest{ |
| 200 |
t: t, |
| 201 |
h2: mode == http2Mode, |
| 202 |
h: h, |
| 203 |
} |
| 204 |
|
| 205 |
var transportFuncs []func(*Transport) |
| 206 |
|
| 207 |
if idx := slices.Index(opts, any(optFakeNet)); idx >= 0 { |
| 208 |
opts = slices.Delete(opts, idx, idx+1) |
| 209 |
cst.li = fakeNetListen() |
| 210 |
cst.ts = &httptest.Server{ |
| 211 |
Config: &Server{Handler: h}, |
| 212 |
Listener: cst.li, |
| 213 |
} |
| 214 |
transportFuncs = append(transportFuncs, func(tr *Transport) { |
| 215 |
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 216 |
return cst.li.connect(), nil |
| 217 |
} |
| 218 |
}) |
| 219 |
} else { |
| 220 |
cst.ts = httptest.NewUnstartedServer(h) |
| 221 |
} |
| 222 |
|
| 223 |
if mode == http2UnencryptedMode { |
| 224 |
p := &Protocols{} |
| 225 |
p.SetUnencryptedHTTP2(true) |
| 226 |
cst.ts.Config.Protocols = p |
| 227 |
} |
| 228 |
|
| 229 |
for _, opt := range opts { |
| 230 |
switch opt := opt.(type) { |
| 231 |
case func(*Transport): |
| 232 |
transportFuncs = append(transportFuncs, opt) |
| 233 |
case func(*httptest.Server): |
| 234 |
opt(cst.ts) |
| 235 |
case func(*Server): |
| 236 |
opt(cst.ts.Config) |
| 237 |
default: |
| 238 |
t.Fatalf("unhandled option type %T", opt) |
| 239 |
} |
| 240 |
} |
| 241 |
|
| 242 |
if cst.ts.Config.ErrorLog == nil { |
| 243 |
cst.ts.Config.ErrorLog = log.New(testLogWriter{t}, "", 0) |
| 244 |
} |
| 245 |
|
| 246 |
switch mode { |
| 247 |
case http1Mode: |
| 248 |
cst.ts.Start() |
| 249 |
case https1Mode: |
| 250 |
cst.ts.StartTLS() |
| 251 |
case http2UnencryptedMode: |
| 252 |
ExportHttp2ConfigureServer(cst.ts.Config, nil) |
| 253 |
cst.ts.Start() |
| 254 |
case http2Mode: |
| 255 |
ExportHttp2ConfigureServer(cst.ts.Config, nil) |
| 256 |
cst.ts.TLS = cst.ts.Config.TLSConfig |
| 257 |
cst.ts.StartTLS() |
| 258 |
default: |
| 259 |
t.Fatalf("unknown test mode %v", mode) |
| 260 |
} |
| 261 |
cst.c = cst.ts.Client() |
| 262 |
cst.tr = cst.c.Transport.(*Transport) |
| 263 |
if mode == http2Mode || mode == http2UnencryptedMode { |
| 264 |
if err := ExportHttp2ConfigureTransport(cst.tr); err != nil { |
| 265 |
t.Fatal(err) |
| 266 |
} |
| 267 |
} |
| 268 |
for _, f := range transportFuncs { |
| 269 |
f(cst.tr) |
| 270 |
} |
| 271 |
|
| 272 |
if mode == http2UnencryptedMode { |
| 273 |
p := &Protocols{} |
| 274 |
p.SetUnencryptedHTTP2(true) |
| 275 |
cst.tr.Protocols = p |
| 276 |
} |
| 277 |
|
| 278 |
t.Cleanup(func() { |
| 279 |
cst.close() |
| 280 |
}) |
| 281 |
return cst |
| 282 |
} |
| 283 |
|
| 284 |
type testLogWriter struct { |
| 285 |
t testing.TB |
| 286 |
} |
| 287 |
|
| 288 |
func (w testLogWriter) Write(b []byte) (int, error) { |
| 289 |
w.t.Logf("server log: %v", strings.TrimSpace(string(b))) |
| 290 |
return len(b), nil |
| 291 |
} |
| 292 |
|
| 293 |
// Testing the newClientServerTest helper itself. |
| 294 |
func TestNewClientServerTest(t *testing.T) { |
| 295 |
modes := []testMode{http1Mode, https1Mode, http2Mode} |
| 296 |
t.Run("realnet", func(t *testing.T) { |
| 297 |
run(t, func(t *testing.T, mode testMode) { |
| 298 |
testNewClientServerTest(t, mode) |
| 299 |
}, modes) |
| 300 |
}) |
| 301 |
t.Run("synctest", func(t *testing.T) { |
| 302 |
runSynctest(t, func(t *testing.T, mode testMode) { |
| 303 |
testNewClientServerTest(t, mode, optFakeNet) |
| 304 |
}, modes) |
| 305 |
}) |
| 306 |
} |
| 307 |
func testNewClientServerTest(t *testing.T, mode testMode, opts ...any) { |
| 308 |
var got struct { |
| 309 |
sync.Mutex |
| 310 |
proto string |
| 311 |
hasTLS bool |
| 312 |
} |
| 313 |
h := HandlerFunc(func(w ResponseWriter, r *Request) { |
| 314 |
got.Lock() |
| 315 |
defer got.Unlock() |
| 316 |
got.proto = r.Proto |
| 317 |
got.hasTLS = r.TLS != nil |
| 318 |
}) |
| 319 |
cst := newClientServerTest(t, mode, h, opts...) |
| 320 |
if _, err := cst.c.Head(cst.ts.URL); err != nil { |
| 321 |
t.Fatal(err) |
| 322 |
} |
| 323 |
var wantProto string |
| 324 |
var wantTLS bool |
| 325 |
switch mode { |
| 326 |
case http1Mode: |
| 327 |
wantProto = "HTTP/1.1" |
| 328 |
wantTLS = false |
| 329 |
case https1Mode: |
| 330 |
wantProto = "HTTP/1.1" |
| 331 |
wantTLS = true |
| 332 |
case http2Mode: |
| 333 |
wantProto = "HTTP/2.0" |
| 334 |
wantTLS = true |
| 335 |
} |
| 336 |
if got.proto != wantProto { |
| 337 |
t.Errorf("req.Proto = %q, want %q", got.proto, wantProto) |
| 338 |
} |
| 339 |
if got.hasTLS != wantTLS { |
| 340 |
t.Errorf("req.TLS set: %v, want %v", got.hasTLS, wantTLS) |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
func TestChunkedResponseHeaders(t *testing.T) { run(t, testChunkedResponseHeaders) } |
| 345 |
func testChunkedResponseHeaders(t *testing.T, mode testMode) { |
| 346 |
log.SetOutput(io.Discard) // is noisy otherwise |
| 347 |
defer log.SetOutput(os.Stderr) |
| 348 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 349 |
w.Header().Set("Content-Length", "intentional gibberish") // we check that this is deleted |
| 350 |
w.(Flusher).Flush() |
| 351 |
fmt.Fprintf(w, "I am a chunked response.") |
| 352 |
})) |
| 353 |
|
| 354 |
res, err := cst.c.Get(cst.ts.URL) |
| 355 |
if err != nil { |
| 356 |
t.Fatalf("Get error: %v", err) |
| 357 |
} |
| 358 |
defer res.Body.Close() |
| 359 |
if g, e := res.ContentLength, int64(-1); g != e { |
| 360 |
t.Errorf("expected ContentLength of %d; got %d", e, g) |
| 361 |
} |
| 362 |
wantTE := []string{"chunked"} |
| 363 |
if mode == http2Mode { |
| 364 |
wantTE = nil |
| 365 |
} |
| 366 |
if !slices.Equal(res.TransferEncoding, wantTE) { |
| 367 |
t.Errorf("TransferEncoding = %v; want %v", res.TransferEncoding, wantTE) |
| 368 |
} |
| 369 |
if got, haveCL := res.Header["Content-Length"]; haveCL { |
| 370 |
t.Errorf("Unexpected Content-Length: %q", got) |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
type reqFunc func(c *Client, url string) (*Response, error) |
| 375 |
|
| 376 |
// h12Compare is a test that compares HTTP/1 and HTTP/2 behavior |
| 377 |
// against each other. |
| 378 |
type h12Compare struct { |
| 379 |
Handler func(ResponseWriter, *Request) // required |
| 380 |
ReqFunc reqFunc // optional |
| 381 |
CheckResponse func(proto string, res *Response) // optional |
| 382 |
EarlyCheckResponse func(proto string, res *Response) // optional; pre-normalize |
| 383 |
Opts []any |
| 384 |
} |
| 385 |
|
| 386 |
func (tt h12Compare) reqFunc() reqFunc { |
| 387 |
if tt.ReqFunc == nil { |
| 388 |
return (*Client).Get |
| 389 |
} |
| 390 |
return tt.ReqFunc |
| 391 |
} |
| 392 |
|
| 393 |
func (tt h12Compare) run(t *testing.T) { |
| 394 |
setParallel(t) |
| 395 |
cst1 := newClientServerTest(t, http1Mode, HandlerFunc(tt.Handler), tt.Opts...) |
| 396 |
defer cst1.close() |
| 397 |
cst2 := newClientServerTest(t, http2Mode, HandlerFunc(tt.Handler), tt.Opts...) |
| 398 |
defer cst2.close() |
| 399 |
|
| 400 |
res1, err := tt.reqFunc()(cst1.c, cst1.ts.URL) |
| 401 |
if err != nil { |
| 402 |
t.Errorf("HTTP/1 request: %v", err) |
| 403 |
return |
| 404 |
} |
| 405 |
res2, err := tt.reqFunc()(cst2.c, cst2.ts.URL) |
| 406 |
if err != nil { |
| 407 |
t.Errorf("HTTP/2 request: %v", err) |
| 408 |
return |
| 409 |
} |
| 410 |
|
| 411 |
if fn := tt.EarlyCheckResponse; fn != nil { |
| 412 |
fn("HTTP/1.1", res1) |
| 413 |
fn("HTTP/2.0", res2) |
| 414 |
} |
| 415 |
|
| 416 |
tt.normalizeRes(t, res1, "HTTP/1.1") |
| 417 |
tt.normalizeRes(t, res2, "HTTP/2.0") |
| 418 |
res1body, res2body := res1.Body, res2.Body |
| 419 |
|
| 420 |
eres1 := mostlyCopy(res1) |
| 421 |
eres2 := mostlyCopy(res2) |
| 422 |
if !reflect.DeepEqual(eres1, eres2) { |
| 423 |
t.Errorf("Response headers to handler differed:\nhttp/1 (%v):\n\t%#v\nhttp/2 (%v):\n\t%#v", |
| 424 |
cst1.ts.URL, eres1, cst2.ts.URL, eres2) |
| 425 |
} |
| 426 |
if !reflect.DeepEqual(res1body, res2body) { |
| 427 |
t.Errorf("Response bodies to handler differed.\nhttp1: %v\nhttp2: %v\n", res1body, res2body) |
| 428 |
} |
| 429 |
if fn := tt.CheckResponse; fn != nil { |
| 430 |
res1.Body, res2.Body = res1body, res2body |
| 431 |
fn("HTTP/1.1", res1) |
| 432 |
fn("HTTP/2.0", res2) |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
func mostlyCopy(r *Response) *Response { |
| 437 |
c := *r |
| 438 |
c.Body = nil |
| 439 |
c.TransferEncoding = nil |
| 440 |
c.TLS = nil |
| 441 |
c.Request = nil |
| 442 |
return &c |
| 443 |
} |
| 444 |
|
| 445 |
type slurpResult struct { |
| 446 |
io.ReadCloser |
| 447 |
body []byte |
| 448 |
err error |
| 449 |
} |
| 450 |
|
| 451 |
func (sr slurpResult) String() string { return fmt.Sprintf("body %q; err %v", sr.body, sr.err) } |
| 452 |
|
| 453 |
func (tt h12Compare) normalizeRes(t *testing.T, res *Response, wantProto string) { |
| 454 |
if res.Proto == wantProto || res.Proto == "HTTP/IGNORE" { |
| 455 |
res.Proto, res.ProtoMajor, res.ProtoMinor = "", 0, 0 |
| 456 |
} else { |
| 457 |
t.Errorf("got %q response; want %q", res.Proto, wantProto) |
| 458 |
} |
| 459 |
slurp, err := io.ReadAll(res.Body) |
| 460 |
|
| 461 |
res.Body.Close() |
| 462 |
res.Body = slurpResult{ |
| 463 |
ReadCloser: io.NopCloser(bytes.NewReader(slurp)), |
| 464 |
body: slurp, |
| 465 |
err: err, |
| 466 |
} |
| 467 |
for i, v := range res.Header["Date"] { |
| 468 |
res.Header["Date"][i] = strings.Repeat("x", len(v)) |
| 469 |
} |
| 470 |
if res.Request == nil { |
| 471 |
t.Errorf("for %s, no request", wantProto) |
| 472 |
} |
| 473 |
if (res.TLS != nil) != (wantProto == "HTTP/2.0") { |
| 474 |
t.Errorf("TLS set = %v; want %v", res.TLS != nil, res.TLS == nil) |
| 475 |
} |
| 476 |
} |
| 477 |
|
| 478 |
// Issue 13532 |
| 479 |
func TestH12_HeadContentLengthNoBody(t *testing.T) { |
| 480 |
h12Compare{ |
| 481 |
ReqFunc: (*Client).Head, |
| 482 |
Handler: func(w ResponseWriter, r *Request) { |
| 483 |
}, |
| 484 |
}.run(t) |
| 485 |
} |
| 486 |
|
| 487 |
func TestH12_HeadContentLengthSmallBody(t *testing.T) { |
| 488 |
h12Compare{ |
| 489 |
ReqFunc: (*Client).Head, |
| 490 |
Handler: func(w ResponseWriter, r *Request) { |
| 491 |
io.WriteString(w, "small") |
| 492 |
}, |
| 493 |
}.run(t) |
| 494 |
} |
| 495 |
|
| 496 |
func TestH12_HeadContentLengthLargeBody(t *testing.T) { |
| 497 |
h12Compare{ |
| 498 |
ReqFunc: (*Client).Head, |
| 499 |
Handler: func(w ResponseWriter, r *Request) { |
| 500 |
chunk := strings.Repeat("x", 512<<10) |
| 501 |
for i := 0; i < 10; i++ { |
| 502 |
io.WriteString(w, chunk) |
| 503 |
} |
| 504 |
}, |
| 505 |
}.run(t) |
| 506 |
} |
| 507 |
|
| 508 |
func TestH12_200NoBody(t *testing.T) { |
| 509 |
h12Compare{Handler: func(w ResponseWriter, r *Request) {}}.run(t) |
| 510 |
} |
| 511 |
|
| 512 |
func TestH2_204NoBody(t *testing.T) { testH12_noBody(t, 204) } |
| 513 |
func TestH2_304NoBody(t *testing.T) { testH12_noBody(t, 304) } |
| 514 |
func TestH2_404NoBody(t *testing.T) { testH12_noBody(t, 404) } |
| 515 |
|
| 516 |
func testH12_noBody(t *testing.T, status int) { |
| 517 |
h12Compare{Handler: func(w ResponseWriter, r *Request) { |
| 518 |
w.WriteHeader(status) |
| 519 |
}}.run(t) |
| 520 |
} |
| 521 |
|
| 522 |
func TestH12_SmallBody(t *testing.T) { |
| 523 |
h12Compare{Handler: func(w ResponseWriter, r *Request) { |
| 524 |
io.WriteString(w, "small body") |
| 525 |
}}.run(t) |
| 526 |
} |
| 527 |
|
| 528 |
func TestH12_ExplicitContentLength(t *testing.T) { |
| 529 |
h12Compare{Handler: func(w ResponseWriter, r *Request) { |
| 530 |
w.Header().Set("Content-Length", "3") |
| 531 |
io.WriteString(w, "foo") |
| 532 |
}}.run(t) |
| 533 |
} |
| 534 |
|
| 535 |
func TestH12_FlushBeforeBody(t *testing.T) { |
| 536 |
h12Compare{Handler: func(w ResponseWriter, r *Request) { |
| 537 |
w.(Flusher).Flush() |
| 538 |
io.WriteString(w, "foo") |
| 539 |
}}.run(t) |
| 540 |
} |
| 541 |
|
| 542 |
func TestH12_FlushMidBody(t *testing.T) { |
| 543 |
h12Compare{Handler: func(w ResponseWriter, r *Request) { |
| 544 |
io.WriteString(w, "foo") |
| 545 |
w.(Flusher).Flush() |
| 546 |
io.WriteString(w, "bar") |
| 547 |
}}.run(t) |
| 548 |
} |
| 549 |
|
| 550 |
func TestH12_Head_ExplicitLen(t *testing.T) { |
| 551 |
h12Compare{ |
| 552 |
ReqFunc: (*Client).Head, |
| 553 |
Handler: func(w ResponseWriter, r *Request) { |
| 554 |
if r.Method != "HEAD" { |
| 555 |
t.Errorf("unexpected method %q", r.Method) |
| 556 |
} |
| 557 |
w.Header().Set("Content-Length", "1235") |
| 558 |
}, |
| 559 |
}.run(t) |
| 560 |
} |
| 561 |
|
| 562 |
func TestH12_Head_ImplicitLen(t *testing.T) { |
| 563 |
h12Compare{ |
| 564 |
ReqFunc: (*Client).Head, |
| 565 |
Handler: func(w ResponseWriter, r *Request) { |
| 566 |
if r.Method != "HEAD" { |
| 567 |
t.Errorf("unexpected method %q", r.Method) |
| 568 |
} |
| 569 |
io.WriteString(w, "foo") |
| 570 |
}, |
| 571 |
}.run(t) |
| 572 |
} |
| 573 |
|
| 574 |
func TestH12_HandlerWritesTooLittle(t *testing.T) { |
| 575 |
h12Compare{ |
| 576 |
Handler: func(w ResponseWriter, r *Request) { |
| 577 |
w.Header().Set("Content-Length", "3") |
| 578 |
io.WriteString(w, "12") // one byte short |
| 579 |
}, |
| 580 |
CheckResponse: func(proto string, res *Response) { |
| 581 |
sr, ok := res.Body.(slurpResult) |
| 582 |
if !ok { |
| 583 |
t.Errorf("%s body is %T; want slurpResult", proto, res.Body) |
| 584 |
return |
| 585 |
} |
| 586 |
if sr.err != io.ErrUnexpectedEOF { |
| 587 |
t.Errorf("%s read error = %v; want io.ErrUnexpectedEOF", proto, sr.err) |
| 588 |
} |
| 589 |
if string(sr.body) != "12" { |
| 590 |
t.Errorf("%s body = %q; want %q", proto, sr.body, "12") |
| 591 |
} |
| 592 |
}, |
| 593 |
}.run(t) |
| 594 |
} |
| 595 |
|
| 596 |
// Tests that the HTTP/1 and HTTP/2 servers prevent handlers from |
| 597 |
// writing more than they declared. This test does not test whether |
| 598 |
// the transport deals with too much data, though, since the server |
| 599 |
// doesn't make it possible to send bogus data. For those tests, see |
| 600 |
// transport_test.go (for HTTP/1) or x/net/http2/transport_test.go |
| 601 |
// (for HTTP/2). |
| 602 |
func TestHandlerWritesTooMuch(t *testing.T) { run(t, testHandlerWritesTooMuch) } |
| 603 |
func testHandlerWritesTooMuch(t *testing.T, mode testMode) { |
| 604 |
wantBody := []byte("123") |
| 605 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 606 |
rc := NewResponseController(w) |
| 607 |
w.Header().Set("Content-Length", fmt.Sprintf("%v", len(wantBody))) |
| 608 |
rc.Flush() |
| 609 |
w.Write(wantBody) |
| 610 |
rc.Flush() |
| 611 |
n, err := io.WriteString(w, "x") // too many |
| 612 |
if err == nil { |
| 613 |
err = rc.Flush() |
| 614 |
} |
| 615 |
// TODO: Check that this is ErrContentLength, not just any error. |
| 616 |
if err == nil { |
| 617 |
t.Errorf("for proto %q, final write = %v, %v; want _, some error", r.Proto, n, err) |
| 618 |
} |
| 619 |
})) |
| 620 |
|
| 621 |
res, err := cst.c.Get(cst.ts.URL) |
| 622 |
if err != nil { |
| 623 |
t.Fatal(err) |
| 624 |
} |
| 625 |
defer res.Body.Close() |
| 626 |
|
| 627 |
gotBody, _ := io.ReadAll(res.Body) |
| 628 |
if !bytes.Equal(gotBody, wantBody) { |
| 629 |
t.Fatalf("got response body: %q; want %q", gotBody, wantBody) |
| 630 |
} |
| 631 |
} |
| 632 |
|
| 633 |
// Verify that both our HTTP/1 and HTTP/2 request and auto-decompress gzip. |
| 634 |
// Some hosts send gzip even if you don't ask for it; see golang.org/issue/13298 |
| 635 |
func TestH12_AutoGzip(t *testing.T) { |
| 636 |
h12Compare{ |
| 637 |
Handler: func(w ResponseWriter, r *Request) { |
| 638 |
if ae := r.Header.Get("Accept-Encoding"); ae != "gzip" { |
| 639 |
t.Errorf("%s Accept-Encoding = %q; want gzip", r.Proto, ae) |
| 640 |
} |
| 641 |
w.Header().Set("Content-Encoding", "gzip") |
| 642 |
gz := gzip.NewWriter(w) |
| 643 |
io.WriteString(gz, "I am some gzipped content. Go go go go go go go go go go go go should compress well.") |
| 644 |
gz.Close() |
| 645 |
}, |
| 646 |
}.run(t) |
| 647 |
} |
| 648 |
|
| 649 |
func TestH12_AutoGzip_Disabled(t *testing.T) { |
| 650 |
h12Compare{ |
| 651 |
Opts: []any{ |
| 652 |
func(tr *Transport) { tr.DisableCompression = true }, |
| 653 |
}, |
| 654 |
Handler: func(w ResponseWriter, r *Request) { |
| 655 |
fmt.Fprintf(w, "%q", r.Header["Accept-Encoding"]) |
| 656 |
if ae := r.Header.Get("Accept-Encoding"); ae != "" { |
| 657 |
t.Errorf("%s Accept-Encoding = %q; want empty", r.Proto, ae) |
| 658 |
} |
| 659 |
}, |
| 660 |
}.run(t) |
| 661 |
} |
| 662 |
|
| 663 |
// Test304Responses verifies that 304s don't declare that they're |
| 664 |
// chunking in their response headers and aren't allowed to produce |
| 665 |
// output. |
| 666 |
func Test304Responses(t *testing.T) { run(t, test304Responses) } |
| 667 |
func test304Responses(t *testing.T, mode testMode) { |
| 668 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 669 |
w.WriteHeader(StatusNotModified) |
| 670 |
_, err := w.Write([]byte("illegal body")) |
| 671 |
if err != ErrBodyNotAllowed { |
| 672 |
t.Errorf("on Write, expected ErrBodyNotAllowed, got %v", err) |
| 673 |
} |
| 674 |
})) |
| 675 |
defer cst.close() |
| 676 |
res, err := cst.c.Get(cst.ts.URL) |
| 677 |
if err != nil { |
| 678 |
t.Fatal(err) |
| 679 |
} |
| 680 |
if len(res.TransferEncoding) > 0 { |
| 681 |
t.Errorf("expected no TransferEncoding; got %v", res.TransferEncoding) |
| 682 |
} |
| 683 |
body, err := io.ReadAll(res.Body) |
| 684 |
if err != nil { |
| 685 |
t.Error(err) |
| 686 |
} |
| 687 |
if len(body) > 0 { |
| 688 |
t.Errorf("got unexpected body %q", string(body)) |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
func TestH12_ServerEmptyContentLength(t *testing.T) { |
| 693 |
h12Compare{ |
| 694 |
Handler: func(w ResponseWriter, r *Request) { |
| 695 |
w.Header()["Content-Type"] = []string{""} |
| 696 |
io.WriteString(w, "<html><body>hi</body></html>") |
| 697 |
}, |
| 698 |
}.run(t) |
| 699 |
} |
| 700 |
|
| 701 |
func TestH12_RequestContentLength_Known_NonZero(t *testing.T) { |
| 702 |
h12requestContentLength(t, func() io.Reader { return strings.NewReader("FOUR") }, 4) |
| 703 |
} |
| 704 |
|
| 705 |
func TestH12_RequestContentLength_Known_Zero(t *testing.T) { |
| 706 |
h12requestContentLength(t, func() io.Reader { return nil }, 0) |
| 707 |
} |
| 708 |
|
| 709 |
func TestH12_RequestContentLength_Unknown(t *testing.T) { |
| 710 |
h12requestContentLength(t, func() io.Reader { return struct{ io.Reader }{strings.NewReader("Stuff")} }, -1) |
| 711 |
} |
| 712 |
|
| 713 |
func h12requestContentLength(t *testing.T, bodyfn func() io.Reader, wantLen int64) { |
| 714 |
h12Compare{ |
| 715 |
Handler: func(w ResponseWriter, r *Request) { |
| 716 |
w.Header().Set("Got-Length", fmt.Sprint(r.ContentLength)) |
| 717 |
fmt.Fprintf(w, "Req.ContentLength=%v", r.ContentLength) |
| 718 |
}, |
| 719 |
ReqFunc: func(c *Client, url string) (*Response, error) { |
| 720 |
return c.Post(url, "text/plain", bodyfn()) |
| 721 |
}, |
| 722 |
CheckResponse: func(proto string, res *Response) { |
| 723 |
if got, want := res.Header.Get("Got-Length"), fmt.Sprint(wantLen); got != want { |
| 724 |
t.Errorf("Proto %q got length %q; want %q", proto, got, want) |
| 725 |
} |
| 726 |
}, |
| 727 |
}.run(t) |
| 728 |
} |
| 729 |
|
| 730 |
// Tests that closing the Request.Cancel channel also while still |
| 731 |
// reading the response body. Issue 13159. |
| 732 |
func TestCancelRequestMidBody(t *testing.T) { run(t, testCancelRequestMidBody) } |
| 733 |
func testCancelRequestMidBody(t *testing.T, mode testMode) { |
| 734 |
unblock := make(chan bool) |
| 735 |
didFlush := make(chan bool, 1) |
| 736 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 737 |
io.WriteString(w, "Hello") |
| 738 |
w.(Flusher).Flush() |
| 739 |
didFlush <- true |
| 740 |
<-unblock |
| 741 |
io.WriteString(w, ", world.") |
| 742 |
})) |
| 743 |
defer close(unblock) |
| 744 |
|
| 745 |
req, _ := NewRequest("GET", cst.ts.URL, nil) |
| 746 |
cancel := make(chan struct{}) |
| 747 |
req.Cancel = cancel |
| 748 |
|
| 749 |
res, err := cst.c.Do(req) |
| 750 |
if err != nil { |
| 751 |
t.Fatal(err) |
| 752 |
} |
| 753 |
defer res.Body.Close() |
| 754 |
<-didFlush |
| 755 |
|
| 756 |
// Read a bit before we cancel. (Issue 13626) |
| 757 |
// We should have "Hello" at least sitting there. |
| 758 |
firstRead := make([]byte, 10) |
| 759 |
n, err := res.Body.Read(firstRead) |
| 760 |
if err != nil { |
| 761 |
t.Fatal(err) |
| 762 |
} |
| 763 |
firstRead = firstRead[:n] |
| 764 |
|
| 765 |
close(cancel) |
| 766 |
|
| 767 |
rest, err := io.ReadAll(res.Body) |
| 768 |
all := string(firstRead) + string(rest) |
| 769 |
if all != "Hello" { |
| 770 |
t.Errorf("Read %q (%q + %q); want Hello", all, firstRead, rest) |
| 771 |
} |
| 772 |
if err != ExportErrRequestCanceled { |
| 773 |
t.Errorf("ReadAll error = %v; want %v", err, ExportErrRequestCanceled) |
| 774 |
} |
| 775 |
} |
| 776 |
|
| 777 |
// Tests that clients can send trailers to a server and that the server can read them. |
| 778 |
func TestTrailersClientToServer(t *testing.T) { run(t, testTrailersClientToServer) } |
| 779 |
func testTrailersClientToServer(t *testing.T, mode testMode) { |
| 780 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 781 |
slurp, err := io.ReadAll(r.Body) |
| 782 |
if err != nil { |
| 783 |
t.Errorf("Server reading request body: %v", err) |
| 784 |
} |
| 785 |
if string(slurp) != "foo" { |
| 786 |
t.Errorf("Server read request body %q; want foo", slurp) |
| 787 |
} |
| 788 |
if r.Trailer == nil { |
| 789 |
io.WriteString(w, "nil Trailer") |
| 790 |
} else { |
| 791 |
decl := slices.Sorted(maps.Keys(r.Trailer)) |
| 792 |
fmt.Fprintf(w, "decl: %v, vals: %s, %s", |
| 793 |
decl, |
| 794 |
r.Trailer.Get("Client-Trailer-A"), |
| 795 |
r.Trailer.Get("Client-Trailer-B")) |
| 796 |
} |
| 797 |
})) |
| 798 |
|
| 799 |
var req *Request |
| 800 |
req, _ = NewRequest("POST", cst.ts.URL, io.MultiReader( |
| 801 |
eofReaderFunc(func() { |
| 802 |
req.Trailer["Client-Trailer-A"] = []string{"valuea"} |
| 803 |
}), |
| 804 |
strings.NewReader("foo"), |
| 805 |
eofReaderFunc(func() { |
| 806 |
req.Trailer["Client-Trailer-B"] = []string{"valueb"} |
| 807 |
}), |
| 808 |
)) |
| 809 |
req.Trailer = Header{ |
| 810 |
"Client-Trailer-A": nil, // to be set later |
| 811 |
"Client-Trailer-B": nil, // to be set later |
| 812 |
} |
| 813 |
req.ContentLength = -1 |
| 814 |
res, err := cst.c.Do(req) |
| 815 |
if err != nil { |
| 816 |
t.Fatal(err) |
| 817 |
} |
| 818 |
if err := wantBody(res, err, "decl: [Client-Trailer-A Client-Trailer-B], vals: valuea, valueb"); err != nil { |
| 819 |
t.Error(err) |
| 820 |
} |
| 821 |
} |
| 822 |
|
| 823 |
// Tests that servers send trailers to a client and that the client can read them. |
| 824 |
func TestTrailersServerToClient(t *testing.T) { |
| 825 |
run(t, func(t *testing.T, mode testMode) { |
| 826 |
testTrailersServerToClient(t, mode, false) |
| 827 |
}) |
| 828 |
} |
| 829 |
func TestTrailersServerToClientFlush(t *testing.T) { |
| 830 |
run(t, func(t *testing.T, mode testMode) { |
| 831 |
testTrailersServerToClient(t, mode, true) |
| 832 |
}) |
| 833 |
} |
| 834 |
|
| 835 |
func testTrailersServerToClient(t *testing.T, mode testMode, flush bool) { |
| 836 |
const body = "Some body" |
| 837 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 838 |
w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B") |
| 839 |
w.Header().Add("Trailer", "Server-Trailer-C") |
| 840 |
|
| 841 |
io.WriteString(w, body) |
| 842 |
if flush { |
| 843 |
w.(Flusher).Flush() |
| 844 |
} |
| 845 |
|
| 846 |
// How handlers set Trailers: declare it ahead of time |
| 847 |
// with the Trailer header, and then mutate the |
| 848 |
// Header() of those values later, after the response |
| 849 |
// has been written (we wrote to w above). |
| 850 |
w.Header().Set("Server-Trailer-A", "valuea") |
| 851 |
w.Header().Set("Server-Trailer-C", "valuec") // skipping B |
| 852 |
w.Header().Set("Server-Trailer-NotDeclared", "should be omitted") |
| 853 |
})) |
| 854 |
|
| 855 |
res, err := cst.c.Get(cst.ts.URL) |
| 856 |
if err != nil { |
| 857 |
t.Fatal(err) |
| 858 |
} |
| 859 |
|
| 860 |
wantHeader := Header{ |
| 861 |
"Content-Type": {"text/plain; charset=utf-8"}, |
| 862 |
} |
| 863 |
wantLen := -1 |
| 864 |
if mode == http2Mode && !flush { |
| 865 |
// In HTTP/1.1, any use of trailers forces HTTP/1.1 |
| 866 |
// chunking and a flush at the first write. That's |
| 867 |
// unnecessary with HTTP/2's framing, so the server |
| 868 |
// is able to calculate the length while still sending |
| 869 |
// trailers afterwards. |
| 870 |
wantLen = len(body) |
| 871 |
wantHeader["Content-Length"] = []string{fmt.Sprint(wantLen)} |
| 872 |
} |
| 873 |
if res.ContentLength != int64(wantLen) { |
| 874 |
t.Errorf("ContentLength = %v; want %v", res.ContentLength, wantLen) |
| 875 |
} |
| 876 |
|
| 877 |
delete(res.Header, "Date") // irrelevant for test |
| 878 |
if !reflect.DeepEqual(res.Header, wantHeader) { |
| 879 |
t.Errorf("Header = %v; want %v", res.Header, wantHeader) |
| 880 |
} |
| 881 |
|
| 882 |
if got, want := res.Trailer, (Header{ |
| 883 |
"Server-Trailer-A": nil, |
| 884 |
"Server-Trailer-B": nil, |
| 885 |
"Server-Trailer-C": nil, |
| 886 |
}); !reflect.DeepEqual(got, want) { |
| 887 |
t.Errorf("Trailer before body read = %v; want %v", got, want) |
| 888 |
} |
| 889 |
|
| 890 |
if err := wantBody(res, nil, body); err != nil { |
| 891 |
t.Fatal(err) |
| 892 |
} |
| 893 |
|
| 894 |
if got, want := res.Trailer, (Header{ |
| 895 |
"Server-Trailer-A": {"valuea"}, |
| 896 |
"Server-Trailer-B": nil, |
| 897 |
"Server-Trailer-C": {"valuec"}, |
| 898 |
}); !reflect.DeepEqual(got, want) { |
| 899 |
t.Errorf("Trailer after body read = %v; want %v", got, want) |
| 900 |
} |
| 901 |
} |
| 902 |
|
| 903 |
// Don't allow a Body.Read after Body.Close. Issue 13648. |
| 904 |
func TestResponseBodyReadAfterClose(t *testing.T) { run(t, testResponseBodyReadAfterClose) } |
| 905 |
func testResponseBodyReadAfterClose(t *testing.T, mode testMode) { |
| 906 |
const body = "Some body" |
| 907 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 908 |
io.WriteString(w, body) |
| 909 |
})) |
| 910 |
res, err := cst.c.Get(cst.ts.URL) |
| 911 |
if err != nil { |
| 912 |
t.Fatal(err) |
| 913 |
} |
| 914 |
res.Body.Close() |
| 915 |
data, err := io.ReadAll(res.Body) |
| 916 |
if len(data) != 0 || err == nil { |
| 917 |
t.Fatalf("ReadAll returned %q, %v; want error", data, err) |
| 918 |
} |
| 919 |
} |
| 920 |
|
| 921 |
func TestConcurrentReadWriteReqBody(t *testing.T) { run(t, testConcurrentReadWriteReqBody) } |
| 922 |
func testConcurrentReadWriteReqBody(t *testing.T, mode testMode) { |
| 923 |
const reqBody = "some request body" |
| 924 |
const resBody = "some response body" |
| 925 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 926 |
var wg sync.WaitGroup |
| 927 |
wg.Add(2) |
| 928 |
didRead := make(chan bool, 1) |
| 929 |
// Read in one goroutine. |
| 930 |
go func() { |
| 931 |
defer wg.Done() |
| 932 |
data, err := io.ReadAll(r.Body) |
| 933 |
if string(data) != reqBody { |
| 934 |
t.Errorf("Handler read %q; want %q", data, reqBody) |
| 935 |
} |
| 936 |
if err != nil { |
| 937 |
t.Errorf("Handler Read: %v", err) |
| 938 |
} |
| 939 |
didRead <- true |
| 940 |
}() |
| 941 |
// Write in another goroutine. |
| 942 |
go func() { |
| 943 |
defer wg.Done() |
| 944 |
if mode != http2Mode { |
| 945 |
// our HTTP/1 implementation intentionally |
| 946 |
// doesn't permit writes during read (mostly |
| 947 |
// due to it being undefined); if that is ever |
| 948 |
// relaxed, change this. |
| 949 |
<-didRead |
| 950 |
} |
| 951 |
io.WriteString(w, resBody) |
| 952 |
}() |
| 953 |
wg.Wait() |
| 954 |
})) |
| 955 |
req, _ := NewRequest("POST", cst.ts.URL, strings.NewReader(reqBody)) |
| 956 |
req.Header.Add("Expect", "100-continue") // just to complicate things |
| 957 |
res, err := cst.c.Do(req) |
| 958 |
if err != nil { |
| 959 |
t.Fatal(err) |
| 960 |
} |
| 961 |
data, err := io.ReadAll(res.Body) |
| 962 |
defer res.Body.Close() |
| 963 |
if err != nil { |
| 964 |
t.Fatal(err) |
| 965 |
} |
| 966 |
if string(data) != resBody { |
| 967 |
t.Errorf("read %q; want %q", data, resBody) |
| 968 |
} |
| 969 |
} |
| 970 |
|
| 971 |
func TestConnectRequest(t *testing.T) { run(t, testConnectRequest) } |
| 972 |
func testConnectRequest(t *testing.T, mode testMode) { |
| 973 |
gotc := make(chan *Request, 1) |
| 974 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 975 |
gotc <- r |
| 976 |
})) |
| 977 |
|
| 978 |
u, err := url.Parse(cst.ts.URL) |
| 979 |
if err != nil { |
| 980 |
t.Fatal(err) |
| 981 |
} |
| 982 |
|
| 983 |
tests := []struct { |
| 984 |
req *Request |
| 985 |
want string |
| 986 |
}{ |
| 987 |
{ |
| 988 |
req: &Request{ |
| 989 |
Method: "CONNECT", |
| 990 |
Header: Header{}, |
| 991 |
URL: u, |
| 992 |
}, |
| 993 |
want: u.Host, |
| 994 |
}, |
| 995 |
{ |
| 996 |
req: &Request{ |
| 997 |
Method: "CONNECT", |
| 998 |
Header: Header{}, |
| 999 |
URL: u, |
| 1000 |
Host: "example.com:123", |
| 1001 |
}, |
| 1002 |
want: "example.com:123", |
| 1003 |
}, |
| 1004 |
} |
| 1005 |
|
| 1006 |
for i, tt := range tests { |
| 1007 |
res, err := cst.c.Do(tt.req) |
| 1008 |
if err != nil { |
| 1009 |
t.Errorf("%d. RoundTrip = %v", i, err) |
| 1010 |
continue |
| 1011 |
} |
| 1012 |
res.Body.Close() |
| 1013 |
req := <-gotc |
| 1014 |
if req.Method != "CONNECT" { |
| 1015 |
t.Errorf("method = %q; want CONNECT", req.Method) |
| 1016 |
} |
| 1017 |
if req.Host != tt.want { |
| 1018 |
t.Errorf("Host = %q; want %q", req.Host, tt.want) |
| 1019 |
} |
| 1020 |
if req.URL.Host != tt.want { |
| 1021 |
t.Errorf("URL.Host = %q; want %q", req.URL.Host, tt.want) |
| 1022 |
} |
| 1023 |
} |
| 1024 |
} |
| 1025 |
|
| 1026 |
func TestTransportUserAgent(t *testing.T) { run(t, testTransportUserAgent) } |
| 1027 |
func testTransportUserAgent(t *testing.T, mode testMode) { |
| 1028 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1029 |
fmt.Fprintf(w, "%q", r.Header["User-Agent"]) |
| 1030 |
})) |
| 1031 |
|
| 1032 |
either := func(a, b string) string { |
| 1033 |
if mode == http2Mode { |
| 1034 |
return b |
| 1035 |
} |
| 1036 |
return a |
| 1037 |
} |
| 1038 |
|
| 1039 |
tests := []struct { |
| 1040 |
setup func(*Request) |
| 1041 |
want string |
| 1042 |
}{ |
| 1043 |
{ |
| 1044 |
func(r *Request) {}, |
| 1045 |
either(`["Go-http-client/1.1"]`, `["Go-http-client/2.0"]`), |
| 1046 |
}, |
| 1047 |
{ |
| 1048 |
func(r *Request) { r.Header.Set("User-Agent", "foo/1.2.3") }, |
| 1049 |
`["foo/1.2.3"]`, |
| 1050 |
}, |
| 1051 |
{ |
| 1052 |
func(r *Request) { r.Header["User-Agent"] = []string{"single", "or", "multiple"} }, |
| 1053 |
`["single"]`, |
| 1054 |
}, |
| 1055 |
{ |
| 1056 |
func(r *Request) { r.Header.Set("User-Agent", "") }, |
| 1057 |
`[]`, |
| 1058 |
}, |
| 1059 |
{ |
| 1060 |
func(r *Request) { r.Header["User-Agent"] = nil }, |
| 1061 |
`[]`, |
| 1062 |
}, |
| 1063 |
} |
| 1064 |
for i, tt := range tests { |
| 1065 |
req, _ := NewRequest("GET", cst.ts.URL, nil) |
| 1066 |
tt.setup(req) |
| 1067 |
res, err := cst.c.Do(req) |
| 1068 |
if err != nil { |
| 1069 |
t.Errorf("%d. RoundTrip = %v", i, err) |
| 1070 |
continue |
| 1071 |
} |
| 1072 |
slurp, err := io.ReadAll(res.Body) |
| 1073 |
res.Body.Close() |
| 1074 |
if err != nil { |
| 1075 |
t.Errorf("%d. read body = %v", i, err) |
| 1076 |
continue |
| 1077 |
} |
| 1078 |
if string(slurp) != tt.want { |
| 1079 |
t.Errorf("%d. body mismatch.\n got: %s\nwant: %s\n", i, slurp, tt.want) |
| 1080 |
} |
| 1081 |
} |
| 1082 |
} |
| 1083 |
|
| 1084 |
func TestStarRequestMethod(t *testing.T) { |
| 1085 |
for _, method := range []string{"FOO", "OPTIONS"} { |
| 1086 |
t.Run(method, func(t *testing.T) { |
| 1087 |
run(t, func(t *testing.T, mode testMode) { |
| 1088 |
testStarRequest(t, method, mode) |
| 1089 |
}) |
| 1090 |
}) |
| 1091 |
} |
| 1092 |
} |
| 1093 |
func testStarRequest(t *testing.T, method string, mode testMode) { |
| 1094 |
gotc := make(chan *Request, 1) |
| 1095 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1096 |
w.Header().Set("foo", "bar") |
| 1097 |
gotc <- r |
| 1098 |
w.(Flusher).Flush() |
| 1099 |
})) |
| 1100 |
|
| 1101 |
u, err := url.Parse(cst.ts.URL) |
| 1102 |
if err != nil { |
| 1103 |
t.Fatal(err) |
| 1104 |
} |
| 1105 |
u.Path = "*" |
| 1106 |
|
| 1107 |
req := &Request{ |
| 1108 |
Method: method, |
| 1109 |
Header: Header{}, |
| 1110 |
URL: u, |
| 1111 |
} |
| 1112 |
|
| 1113 |
res, err := cst.c.Do(req) |
| 1114 |
if err != nil { |
| 1115 |
t.Fatalf("RoundTrip = %v", err) |
| 1116 |
} |
| 1117 |
res.Body.Close() |
| 1118 |
|
| 1119 |
wantFoo := "bar" |
| 1120 |
wantLen := int64(-1) |
| 1121 |
if method == "OPTIONS" { |
| 1122 |
wantFoo = "" |
| 1123 |
wantLen = 0 |
| 1124 |
} |
| 1125 |
if res.StatusCode != 200 { |
| 1126 |
t.Errorf("status code = %v; want %d", res.Status, 200) |
| 1127 |
} |
| 1128 |
if res.ContentLength != wantLen { |
| 1129 |
t.Errorf("content length = %v; want %d", res.ContentLength, wantLen) |
| 1130 |
} |
| 1131 |
if got := res.Header.Get("foo"); got != wantFoo { |
| 1132 |
t.Errorf("response \"foo\" header = %q; want %q", got, wantFoo) |
| 1133 |
} |
| 1134 |
select { |
| 1135 |
case req = <-gotc: |
| 1136 |
default: |
| 1137 |
req = nil |
| 1138 |
} |
| 1139 |
if req == nil { |
| 1140 |
if method != "OPTIONS" { |
| 1141 |
t.Fatalf("handler never got request") |
| 1142 |
} |
| 1143 |
return |
| 1144 |
} |
| 1145 |
if req.Method != method { |
| 1146 |
t.Errorf("method = %q; want %q", req.Method, method) |
| 1147 |
} |
| 1148 |
if req.URL.Path != "*" { |
| 1149 |
t.Errorf("URL.Path = %q; want *", req.URL.Path) |
| 1150 |
} |
| 1151 |
if req.RequestURI != "*" { |
| 1152 |
t.Errorf("RequestURI = %q; want *", req.RequestURI) |
| 1153 |
} |
| 1154 |
} |
| 1155 |
|
| 1156 |
// Issue 13957 |
| 1157 |
func TestTransportDiscardsUnneededConns(t *testing.T) { |
| 1158 |
run(t, testTransportDiscardsUnneededConns, []testMode{http2Mode}) |
| 1159 |
} |
| 1160 |
func testTransportDiscardsUnneededConns(t *testing.T, mode testMode) { |
| 1161 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1162 |
fmt.Fprintf(w, "Hello, %v", r.RemoteAddr) |
| 1163 |
})) |
| 1164 |
defer cst.close() |
| 1165 |
|
| 1166 |
var numOpen, numClose int32 // atomic |
| 1167 |
|
| 1168 |
tlsConfig := &tls.Config{InsecureSkipVerify: true} |
| 1169 |
tr := &Transport{ |
| 1170 |
TLSClientConfig: tlsConfig, |
| 1171 |
DialTLS: func(_, addr string) (net.Conn, error) { |
| 1172 |
time.Sleep(10 * time.Millisecond) |
| 1173 |
rc, err := net.Dial("tcp", addr) |
| 1174 |
if err != nil { |
| 1175 |
return nil, err |
| 1176 |
} |
| 1177 |
atomic.AddInt32(&numOpen, 1) |
| 1178 |
c := noteCloseConn{rc, func() { atomic.AddInt32(&numClose, 1) }} |
| 1179 |
return tls.Client(c, tlsConfig), nil |
| 1180 |
}, |
| 1181 |
} |
| 1182 |
if err := ExportHttp2ConfigureTransport(tr); err != nil { |
| 1183 |
t.Fatal(err) |
| 1184 |
} |
| 1185 |
defer tr.CloseIdleConnections() |
| 1186 |
|
| 1187 |
c := &Client{Transport: tr} |
| 1188 |
|
| 1189 |
const N = 10 |
| 1190 |
gotBody := make(chan string, N) |
| 1191 |
var wg sync.WaitGroup |
| 1192 |
for i := 0; i < N; i++ { |
| 1193 |
wg.Add(1) |
| 1194 |
go func() { |
| 1195 |
defer wg.Done() |
| 1196 |
resp, err := c.Get(cst.ts.URL) |
| 1197 |
if err != nil { |
| 1198 |
// Try to work around spurious connection reset on loaded system. |
| 1199 |
// See golang.org/issue/33585 and golang.org/issue/36797. |
| 1200 |
time.Sleep(10 * time.Millisecond) |
| 1201 |
resp, err = c.Get(cst.ts.URL) |
| 1202 |
if err != nil { |
| 1203 |
t.Errorf("Get: %v", err) |
| 1204 |
return |
| 1205 |
} |
| 1206 |
} |
| 1207 |
defer resp.Body.Close() |
| 1208 |
slurp, err := io.ReadAll(resp.Body) |
| 1209 |
if err != nil { |
| 1210 |
t.Error(err) |
| 1211 |
} |
| 1212 |
gotBody <- string(slurp) |
| 1213 |
}() |
| 1214 |
} |
| 1215 |
wg.Wait() |
| 1216 |
close(gotBody) |
| 1217 |
|
| 1218 |
var last string |
| 1219 |
for got := range gotBody { |
| 1220 |
if last == "" { |
| 1221 |
last = got |
| 1222 |
continue |
| 1223 |
} |
| 1224 |
if got != last { |
| 1225 |
t.Errorf("Response body changed: %q -> %q", last, got) |
| 1226 |
} |
| 1227 |
} |
| 1228 |
|
| 1229 |
var open, close int32 |
| 1230 |
for i := 0; i < 150; i++ { |
| 1231 |
open, close = atomic.LoadInt32(&numOpen), atomic.LoadInt32(&numClose) |
| 1232 |
if open < 1 { |
| 1233 |
t.Fatalf("open = %d; want at least", open) |
| 1234 |
} |
| 1235 |
if close == open-1 { |
| 1236 |
// Success |
| 1237 |
return |
| 1238 |
} |
| 1239 |
time.Sleep(10 * time.Millisecond) |
| 1240 |
} |
| 1241 |
t.Errorf("%d connections opened, %d closed; want %d to close", open, close, open-1) |
| 1242 |
} |
| 1243 |
|
| 1244 |
// tests that Transport doesn't retain a pointer to the provided request. |
| 1245 |
func TestTransportGCRequest(t *testing.T) { |
| 1246 |
run(t, func(t *testing.T, mode testMode) { |
| 1247 |
t.Run("Body", func(t *testing.T) { testTransportGCRequest(t, mode, true) }) |
| 1248 |
t.Run("NoBody", func(t *testing.T) { testTransportGCRequest(t, mode, false) }) |
| 1249 |
}) |
| 1250 |
} |
| 1251 |
func testTransportGCRequest(t *testing.T, mode testMode, body bool) { |
| 1252 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1253 |
io.ReadAll(r.Body) |
| 1254 |
if body { |
| 1255 |
io.WriteString(w, "Hello.") |
| 1256 |
} |
| 1257 |
})) |
| 1258 |
|
| 1259 |
didGC := make(chan struct{}) |
| 1260 |
(func() { |
| 1261 |
body := strings.NewReader("some body") |
| 1262 |
req, _ := NewRequest("POST", cst.ts.URL, body) |
| 1263 |
runtime.AddCleanup(req, func(ch chan struct{}) { close(ch) }, didGC) |
| 1264 |
res, err := cst.c.Do(req) |
| 1265 |
if err != nil { |
| 1266 |
t.Fatal(err) |
| 1267 |
} |
| 1268 |
if _, err := io.ReadAll(res.Body); err != nil { |
| 1269 |
t.Fatal(err) |
| 1270 |
} |
| 1271 |
if err := res.Body.Close(); err != nil { |
| 1272 |
t.Fatal(err) |
| 1273 |
} |
| 1274 |
})() |
| 1275 |
for { |
| 1276 |
select { |
| 1277 |
case <-didGC: |
| 1278 |
return |
| 1279 |
case <-time.After(1 * time.Millisecond): |
| 1280 |
runtime.GC() |
| 1281 |
} |
| 1282 |
} |
| 1283 |
} |
| 1284 |
|
| 1285 |
func TestTransportRejectsInvalidHeaders(t *testing.T) { run(t, testTransportRejectsInvalidHeaders) } |
| 1286 |
func testTransportRejectsInvalidHeaders(t *testing.T, mode testMode) { |
| 1287 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1288 |
fmt.Fprintf(w, "Handler saw headers: %q", r.Header) |
| 1289 |
}), optQuietLog) |
| 1290 |
cst.tr.DisableKeepAlives = true |
| 1291 |
|
| 1292 |
tests := []struct { |
| 1293 |
key, val string |
| 1294 |
ok bool |
| 1295 |
}{ |
| 1296 |
{"Foo", "capital-key", true}, // verify h2 allows capital keys |
| 1297 |
{"Foo", "foo\x00bar", false}, // \x00 byte in value not allowed |
| 1298 |
{"Foo", "two\nlines", false}, // \n byte in value not allowed |
| 1299 |
{"bogus\nkey", "v", false}, // \n byte also not allowed in key |
| 1300 |
{"A space", "v", false}, // spaces in keys not allowed |
| 1301 |
{"имя", "v", false}, // key must be ascii |
| 1302 |
{"name", "валю", true}, // value may be non-ascii |
| 1303 |
{"", "v", false}, // key must be non-empty |
| 1304 |
{"k", "", true}, // value may be empty |
| 1305 |
} |
| 1306 |
for _, tt := range tests { |
| 1307 |
dialedc := make(chan bool, 1) |
| 1308 |
cst.tr.Dial = func(netw, addr string) (net.Conn, error) { |
| 1309 |
dialedc <- true |
| 1310 |
return net.Dial(netw, addr) |
| 1311 |
} |
| 1312 |
req, _ := NewRequest("GET", cst.ts.URL, nil) |
| 1313 |
req.Header[tt.key] = []string{tt.val} |
| 1314 |
res, err := cst.c.Do(req) |
| 1315 |
var body []byte |
| 1316 |
if err == nil { |
| 1317 |
body, _ = io.ReadAll(res.Body) |
| 1318 |
res.Body.Close() |
| 1319 |
} |
| 1320 |
var dialed bool |
| 1321 |
select { |
| 1322 |
case <-dialedc: |
| 1323 |
dialed = true |
| 1324 |
default: |
| 1325 |
} |
| 1326 |
|
| 1327 |
if !tt.ok && dialed { |
| 1328 |
t.Errorf("For key %q, value %q, transport dialed. Expected local failure. Response was: (%v, %v)\nServer replied with: %s", tt.key, tt.val, res, err, body) |
| 1329 |
} else if (err == nil) != tt.ok { |
| 1330 |
t.Errorf("For key %q, value %q; got err = %v; want ok=%v", tt.key, tt.val, err, tt.ok) |
| 1331 |
} |
| 1332 |
} |
| 1333 |
} |
| 1334 |
|
| 1335 |
func TestInterruptWithPanic(t *testing.T) { |
| 1336 |
run(t, func(t *testing.T, mode testMode) { |
| 1337 |
t.Run("boom", func(t *testing.T) { testInterruptWithPanic(t, mode, "boom") }) |
| 1338 |
t.Run("nil", func(t *testing.T) { t.Setenv("GODEBUG", "panicnil=1"); testInterruptWithPanic(t, mode, nil) }) |
| 1339 |
t.Run("ErrAbortHandler", func(t *testing.T) { testInterruptWithPanic(t, mode, ErrAbortHandler) }) |
| 1340 |
}, testNotParallel) |
| 1341 |
} |
| 1342 |
func testInterruptWithPanic(t *testing.T, mode testMode, panicValue any) { |
| 1343 |
const msg = "hello" |
| 1344 |
|
| 1345 |
testDone := make(chan struct{}) |
| 1346 |
defer close(testDone) |
| 1347 |
|
| 1348 |
var errorLog lockedBytesBuffer |
| 1349 |
gotHeaders := make(chan bool, 1) |
| 1350 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1351 |
io.WriteString(w, msg) |
| 1352 |
w.(Flusher).Flush() |
| 1353 |
|
| 1354 |
select { |
| 1355 |
case <-gotHeaders: |
| 1356 |
case <-testDone: |
| 1357 |
} |
| 1358 |
panic(panicValue) |
| 1359 |
}), func(ts *httptest.Server) { |
| 1360 |
ts.Config.ErrorLog = log.New(&errorLog, "", 0) |
| 1361 |
}) |
| 1362 |
res, err := cst.c.Get(cst.ts.URL) |
| 1363 |
if err != nil { |
| 1364 |
t.Fatal(err) |
| 1365 |
} |
| 1366 |
gotHeaders <- true |
| 1367 |
defer res.Body.Close() |
| 1368 |
slurp, err := io.ReadAll(res.Body) |
| 1369 |
if string(slurp) != msg { |
| 1370 |
t.Errorf("client read %q; want %q", slurp, msg) |
| 1371 |
} |
| 1372 |
if err == nil { |
| 1373 |
t.Errorf("client read all successfully; want some error") |
| 1374 |
} |
| 1375 |
logOutput := func() string { |
| 1376 |
errorLog.Lock() |
| 1377 |
defer errorLog.Unlock() |
| 1378 |
return errorLog.String() |
| 1379 |
} |
| 1380 |
wantStackLogged := panicValue != nil && panicValue != ErrAbortHandler |
| 1381 |
|
| 1382 |
waitCondition(t, 10*time.Millisecond, func(d time.Duration) bool { |
| 1383 |
gotLog := logOutput() |
| 1384 |
if !wantStackLogged { |
| 1385 |
if gotLog == "" { |
| 1386 |
return true |
| 1387 |
} |
| 1388 |
t.Fatalf("want no log output; got: %s", gotLog) |
| 1389 |
} |
| 1390 |
if gotLog == "" { |
| 1391 |
if d > 0 { |
| 1392 |
t.Logf("wanted a stack trace logged; got nothing after %v", d) |
| 1393 |
} |
| 1394 |
return false |
| 1395 |
} |
| 1396 |
if !strings.Contains(gotLog, "created by ") && strings.Count(gotLog, "\n") < 6 { |
| 1397 |
if d > 0 { |
| 1398 |
t.Logf("output doesn't look like a panic stack trace after %v. Got: %s", d, gotLog) |
| 1399 |
} |
| 1400 |
return false |
| 1401 |
} |
| 1402 |
return true |
| 1403 |
}) |
| 1404 |
} |
| 1405 |
|
| 1406 |
type lockedBytesBuffer struct { |
| 1407 |
sync.Mutex |
| 1408 |
bytes.Buffer |
| 1409 |
} |
| 1410 |
|
| 1411 |
func (b *lockedBytesBuffer) Write(p []byte) (int, error) { |
| 1412 |
b.Lock() |
| 1413 |
defer b.Unlock() |
| 1414 |
return b.Buffer.Write(p) |
| 1415 |
} |
| 1416 |
|
| 1417 |
// Issue 15366 |
| 1418 |
func TestH12_AutoGzipWithDumpResponse(t *testing.T) { |
| 1419 |
h12Compare{ |
| 1420 |
Handler: func(w ResponseWriter, r *Request) { |
| 1421 |
h := w.Header() |
| 1422 |
h.Set("Content-Encoding", "gzip") |
| 1423 |
h.Set("Content-Length", "23") |
| 1424 |
io.WriteString(w, "\x1f\x8b\b\x00\x00\x00\x00\x00\x00\x00s\xf3\xf7\a\x00\xab'\xd4\x1a\x03\x00\x00\x00") |
| 1425 |
}, |
| 1426 |
EarlyCheckResponse: func(proto string, res *Response) { |
| 1427 |
if !res.Uncompressed { |
| 1428 |
t.Errorf("%s: expected Uncompressed to be set", proto) |
| 1429 |
} |
| 1430 |
dump, err := httputil.DumpResponse(res, true) |
| 1431 |
if err != nil { |
| 1432 |
t.Errorf("%s: DumpResponse: %v", proto, err) |
| 1433 |
return |
| 1434 |
} |
| 1435 |
if strings.Contains(string(dump), "Connection: close") { |
| 1436 |
t.Errorf("%s: should not see \"Connection: close\" in dump; got:\n%s", proto, dump) |
| 1437 |
} |
| 1438 |
if !strings.Contains(string(dump), "FOO") { |
| 1439 |
t.Errorf("%s: should see \"FOO\" in response; got:\n%s", proto, dump) |
| 1440 |
} |
| 1441 |
}, |
| 1442 |
}.run(t) |
| 1443 |
} |
| 1444 |
|
| 1445 |
// Issue 14607 |
| 1446 |
func TestCloseIdleConnections(t *testing.T) { run(t, testCloseIdleConnections) } |
| 1447 |
func testCloseIdleConnections(t *testing.T, mode testMode) { |
| 1448 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1449 |
w.Header().Set("X-Addr", r.RemoteAddr) |
| 1450 |
})) |
| 1451 |
get := func() string { |
| 1452 |
res, err := cst.c.Get(cst.ts.URL) |
| 1453 |
if err != nil { |
| 1454 |
t.Fatal(err) |
| 1455 |
} |
| 1456 |
res.Body.Close() |
| 1457 |
v := res.Header.Get("X-Addr") |
| 1458 |
if v == "" { |
| 1459 |
t.Fatal("didn't get X-Addr") |
| 1460 |
} |
| 1461 |
return v |
| 1462 |
} |
| 1463 |
a1 := get() |
| 1464 |
cst.tr.CloseIdleConnections() |
| 1465 |
a2 := get() |
| 1466 |
if a1 == a2 { |
| 1467 |
t.Errorf("didn't close connection") |
| 1468 |
} |
| 1469 |
} |
| 1470 |
|
| 1471 |
type noteCloseConn struct { |
| 1472 |
net.Conn |
| 1473 |
closeFunc func() |
| 1474 |
} |
| 1475 |
|
| 1476 |
func (x noteCloseConn) Close() error { |
| 1477 |
x.closeFunc() |
| 1478 |
return x.Conn.Close() |
| 1479 |
} |
| 1480 |
|
| 1481 |
type testErrorReader struct{ t *testing.T } |
| 1482 |
|
| 1483 |
func (r testErrorReader) Read(p []byte) (n int, err error) { |
| 1484 |
r.t.Error("unexpected Read call") |
| 1485 |
return 0, io.EOF |
| 1486 |
} |
| 1487 |
|
| 1488 |
func TestNoSniffExpectRequestBody(t *testing.T) { run(t, testNoSniffExpectRequestBody) } |
| 1489 |
func testNoSniffExpectRequestBody(t *testing.T, mode testMode) { |
| 1490 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1491 |
w.WriteHeader(StatusUnauthorized) |
| 1492 |
})) |
| 1493 |
|
| 1494 |
// Set ExpectContinueTimeout non-zero so RoundTrip won't try to write it. |
| 1495 |
cst.tr.ExpectContinueTimeout = 10 * time.Second |
| 1496 |
|
| 1497 |
req, err := NewRequest("POST", cst.ts.URL, testErrorReader{t}) |
| 1498 |
if err != nil { |
| 1499 |
t.Fatal(err) |
| 1500 |
} |
| 1501 |
req.ContentLength = 0 // so transport is tempted to sniff it |
| 1502 |
req.Header.Set("Expect", "100-continue") |
| 1503 |
res, err := cst.tr.RoundTrip(req) |
| 1504 |
if err != nil { |
| 1505 |
t.Fatal(err) |
| 1506 |
} |
| 1507 |
defer res.Body.Close() |
| 1508 |
if res.StatusCode != StatusUnauthorized { |
| 1509 |
t.Errorf("status code = %v; want %v", res.StatusCode, StatusUnauthorized) |
| 1510 |
} |
| 1511 |
} |
| 1512 |
|
| 1513 |
func TestServerUndeclaredTrailers(t *testing.T) { run(t, testServerUndeclaredTrailers) } |
| 1514 |
func testServerUndeclaredTrailers(t *testing.T, mode testMode) { |
| 1515 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1516 |
w.Header().Set("Foo", "Bar") |
| 1517 |
w.Header().Set("Trailer:Foo", "Baz") |
| 1518 |
w.(Flusher).Flush() |
| 1519 |
w.Header().Add("Trailer:Foo", "Baz2") |
| 1520 |
w.Header().Set("Trailer:Bar", "Quux") |
| 1521 |
})) |
| 1522 |
res, err := cst.c.Get(cst.ts.URL) |
| 1523 |
if err != nil { |
| 1524 |
t.Fatal(err) |
| 1525 |
} |
| 1526 |
if _, err := io.Copy(io.Discard, res.Body); err != nil { |
| 1527 |
t.Fatal(err) |
| 1528 |
} |
| 1529 |
res.Body.Close() |
| 1530 |
delete(res.Header, "Date") |
| 1531 |
delete(res.Header, "Content-Type") |
| 1532 |
|
| 1533 |
if want := (Header{"Foo": {"Bar"}}); !reflect.DeepEqual(res.Header, want) { |
| 1534 |
t.Errorf("Header = %#v; want %#v", res.Header, want) |
| 1535 |
} |
| 1536 |
if want := (Header{"Foo": {"Baz", "Baz2"}, "Bar": {"Quux"}}); !reflect.DeepEqual(res.Trailer, want) { |
| 1537 |
t.Errorf("Trailer = %#v; want %#v", res.Trailer, want) |
| 1538 |
} |
| 1539 |
} |
| 1540 |
|
| 1541 |
func TestBadResponseAfterReadingBody(t *testing.T) { |
| 1542 |
run(t, testBadResponseAfterReadingBody, []testMode{http1Mode}) |
| 1543 |
} |
| 1544 |
func testBadResponseAfterReadingBody(t *testing.T, mode testMode) { |
| 1545 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1546 |
_, err := io.Copy(io.Discard, r.Body) |
| 1547 |
if err != nil { |
| 1548 |
t.Fatal(err) |
| 1549 |
} |
| 1550 |
c, _, err := w.(Hijacker).Hijack() |
| 1551 |
if err != nil { |
| 1552 |
t.Fatal(err) |
| 1553 |
} |
| 1554 |
defer c.Close() |
| 1555 |
fmt.Fprintln(c, "some bogus crap") |
| 1556 |
})) |
| 1557 |
|
| 1558 |
closes := 0 |
| 1559 |
res, err := cst.c.Post(cst.ts.URL, "text/plain", countCloseReader{&closes, strings.NewReader("hello")}) |
| 1560 |
if err == nil { |
| 1561 |
res.Body.Close() |
| 1562 |
t.Fatal("expected an error to be returned from Post") |
| 1563 |
} |
| 1564 |
if closes != 1 { |
| 1565 |
t.Errorf("closes = %d; want 1", closes) |
| 1566 |
} |
| 1567 |
} |
| 1568 |
|
| 1569 |
func TestWriteHeader0(t *testing.T) { run(t, testWriteHeader0) } |
| 1570 |
func testWriteHeader0(t *testing.T, mode testMode) { |
| 1571 |
gotpanic := make(chan bool, 1) |
| 1572 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1573 |
defer close(gotpanic) |
| 1574 |
defer func() { |
| 1575 |
if e := recover(); e != nil { |
| 1576 |
got := fmt.Sprintf("%T, %v", e, e) |
| 1577 |
want := "string, invalid WriteHeader code 0" |
| 1578 |
if got != want { |
| 1579 |
t.Errorf("unexpected panic value:\n got: %v\nwant: %v\n", got, want) |
| 1580 |
} |
| 1581 |
gotpanic <- true |
| 1582 |
|
| 1583 |
// Set an explicit 503. This also tests that the WriteHeader call panics |
| 1584 |
// before it recorded that an explicit value was set and that bogus |
| 1585 |
// value wasn't stuck. |
| 1586 |
w.WriteHeader(503) |
| 1587 |
} |
| 1588 |
}() |
| 1589 |
w.WriteHeader(0) |
| 1590 |
})) |
| 1591 |
res, err := cst.c.Get(cst.ts.URL) |
| 1592 |
if err != nil { |
| 1593 |
t.Fatal(err) |
| 1594 |
} |
| 1595 |
if res.StatusCode != 503 { |
| 1596 |
t.Errorf("Response: %v %q; want 503", res.StatusCode, res.Status) |
| 1597 |
} |
| 1598 |
if !<-gotpanic { |
| 1599 |
t.Error("expected panic in handler") |
| 1600 |
} |
| 1601 |
} |
| 1602 |
|
| 1603 |
// Issue 23010: don't be super strict checking WriteHeader's code if |
| 1604 |
// it's not even valid to call WriteHeader then anyway. |
| 1605 |
func TestWriteHeaderNoCodeCheck(t *testing.T) { |
| 1606 |
run(t, func(t *testing.T, mode testMode) { |
| 1607 |
testWriteHeaderAfterWrite(t, mode, false) |
| 1608 |
}) |
| 1609 |
} |
| 1610 |
func TestWriteHeaderNoCodeCheck_h1hijack(t *testing.T) { |
| 1611 |
testWriteHeaderAfterWrite(t, http1Mode, true) |
| 1612 |
} |
| 1613 |
func testWriteHeaderAfterWrite(t *testing.T, mode testMode, hijack bool) { |
| 1614 |
var errorLog lockedBytesBuffer |
| 1615 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1616 |
if hijack { |
| 1617 |
conn, _, _ := w.(Hijacker).Hijack() |
| 1618 |
defer conn.Close() |
| 1619 |
conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 6\r\n\r\nfoo")) |
| 1620 |
w.WriteHeader(0) // verify this doesn't panic if there's already output; Issue 23010 |
| 1621 |
conn.Write([]byte("bar")) |
| 1622 |
return |
| 1623 |
} |
| 1624 |
io.WriteString(w, "foo") |
| 1625 |
w.(Flusher).Flush() |
| 1626 |
w.WriteHeader(0) // verify this doesn't panic if there's already output; Issue 23010 |
| 1627 |
io.WriteString(w, "bar") |
| 1628 |
}), func(ts *httptest.Server) { |
| 1629 |
ts.Config.ErrorLog = log.New(&errorLog, "", 0) |
| 1630 |
}) |
| 1631 |
res, err := cst.c.Get(cst.ts.URL) |
| 1632 |
if err != nil { |
| 1633 |
t.Fatal(err) |
| 1634 |
} |
| 1635 |
defer res.Body.Close() |
| 1636 |
body, err := io.ReadAll(res.Body) |
| 1637 |
if err != nil { |
| 1638 |
t.Fatal(err) |
| 1639 |
} |
| 1640 |
if got, want := string(body), "foobar"; got != want { |
| 1641 |
t.Errorf("got = %q; want %q", got, want) |
| 1642 |
} |
| 1643 |
|
| 1644 |
// Also check the stderr output: |
| 1645 |
if mode == http2Mode { |
| 1646 |
// TODO: also emit this log message for HTTP/2? |
| 1647 |
// We historically haven't, so don't check. |
| 1648 |
return |
| 1649 |
} |
| 1650 |
gotLog := strings.TrimSpace(errorLog.String()) |
| 1651 |
wantLog := "http: superfluous response.WriteHeader call from net/http_test.testWriteHeaderAfterWrite.func1 (clientserver_test.go:" |
| 1652 |
if hijack { |
| 1653 |
wantLog = "http: response.WriteHeader on hijacked connection from net/http_test.testWriteHeaderAfterWrite.func1 (clientserver_test.go:" |
| 1654 |
} |
| 1655 |
if !strings.HasPrefix(gotLog, wantLog) { |
| 1656 |
t.Errorf("stderr output = %q; want %q", gotLog, wantLog) |
| 1657 |
} |
| 1658 |
} |
| 1659 |
|
| 1660 |
func TestBidiStreamReverseProxy(t *testing.T) { |
| 1661 |
run(t, testBidiStreamReverseProxy, []testMode{http2Mode}) |
| 1662 |
} |
| 1663 |
func testBidiStreamReverseProxy(t *testing.T, mode testMode) { |
| 1664 |
backend := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1665 |
if _, err := io.Copy(w, r.Body); err != nil { |
| 1666 |
log.Printf("bidi backend copy: %v", err) |
| 1667 |
} |
| 1668 |
})) |
| 1669 |
|
| 1670 |
backURL, err := url.Parse(backend.ts.URL) |
| 1671 |
if err != nil { |
| 1672 |
t.Fatal(err) |
| 1673 |
} |
| 1674 |
rp := httputil.NewSingleHostReverseProxy(backURL) |
| 1675 |
rp.Transport = backend.tr |
| 1676 |
proxy := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1677 |
rp.ServeHTTP(w, r) |
| 1678 |
})) |
| 1679 |
|
| 1680 |
bodyRes := make(chan any, 1) // error or hash.Hash |
| 1681 |
pr, pw := io.Pipe() |
| 1682 |
req, _ := NewRequest("PUT", proxy.ts.URL, pr) |
| 1683 |
const size = 4 << 20 |
| 1684 |
go func() { |
| 1685 |
h := sha1.New() |
| 1686 |
_, err := io.CopyN(io.MultiWriter(h, pw), rand.Reader, size) |
| 1687 |
go pw.Close() |
| 1688 |
if err != nil { |
| 1689 |
t.Errorf("body copy: %v", err) |
| 1690 |
bodyRes <- err |
| 1691 |
} else { |
| 1692 |
bodyRes <- h |
| 1693 |
} |
| 1694 |
}() |
| 1695 |
res, err := backend.c.Do(req) |
| 1696 |
if err != nil { |
| 1697 |
t.Fatal(err) |
| 1698 |
} |
| 1699 |
defer res.Body.Close() |
| 1700 |
hgot := sha1.New() |
| 1701 |
n, err := io.Copy(hgot, res.Body) |
| 1702 |
if err != nil { |
| 1703 |
t.Fatal(err) |
| 1704 |
} |
| 1705 |
if n != size { |
| 1706 |
t.Fatalf("got %d bytes; want %d", n, size) |
| 1707 |
} |
| 1708 |
select { |
| 1709 |
case v := <-bodyRes: |
| 1710 |
switch v := v.(type) { |
| 1711 |
default: |
| 1712 |
t.Fatalf("body copy: %v", err) |
| 1713 |
case hash.Hash: |
| 1714 |
if !bytes.Equal(v.Sum(nil), hgot.Sum(nil)) { |
| 1715 |
t.Errorf("written bytes didn't match received bytes") |
| 1716 |
} |
| 1717 |
} |
| 1718 |
case <-time.After(10 * time.Second): |
| 1719 |
t.Fatal("timeout") |
| 1720 |
} |
| 1721 |
|
| 1722 |
} |
| 1723 |
|
| 1724 |
// Always use HTTP/1.1 for WebSocket upgrades. |
| 1725 |
func TestH12_WebSocketUpgrade(t *testing.T) { |
| 1726 |
h12Compare{ |
| 1727 |
Handler: func(w ResponseWriter, r *Request) { |
| 1728 |
h := w.Header() |
| 1729 |
h.Set("Foo", "bar") |
| 1730 |
}, |
| 1731 |
ReqFunc: func(c *Client, url string) (*Response, error) { |
| 1732 |
req, _ := NewRequest("GET", url, nil) |
| 1733 |
req.Header.Set("Connection", "Upgrade") |
| 1734 |
req.Header.Set("Upgrade", "WebSocket") |
| 1735 |
return c.Do(req) |
| 1736 |
}, |
| 1737 |
EarlyCheckResponse: func(proto string, res *Response) { |
| 1738 |
if res.Proto != "HTTP/1.1" { |
| 1739 |
t.Errorf("%s: expected HTTP/1.1, got %q", proto, res.Proto) |
| 1740 |
} |
| 1741 |
res.Proto = "HTTP/IGNORE" // skip later checks that Proto must be 1.1 vs 2.0 |
| 1742 |
}, |
| 1743 |
}.run(t) |
| 1744 |
} |
| 1745 |
|
| 1746 |
func TestIdentityTransferEncoding(t *testing.T) { run(t, testIdentityTransferEncoding) } |
| 1747 |
func testIdentityTransferEncoding(t *testing.T, mode testMode) { |
| 1748 |
const body = "body" |
| 1749 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1750 |
gotBody, _ := io.ReadAll(r.Body) |
| 1751 |
if got, want := string(gotBody), body; got != want { |
| 1752 |
t.Errorf("got request body = %q; want %q", got, want) |
| 1753 |
} |
| 1754 |
w.Header().Set("Transfer-Encoding", "identity") |
| 1755 |
w.WriteHeader(StatusOK) |
| 1756 |
w.(Flusher).Flush() |
| 1757 |
io.WriteString(w, body) |
| 1758 |
})) |
| 1759 |
req, _ := NewRequest("GET", cst.ts.URL, strings.NewReader(body)) |
| 1760 |
res, err := cst.c.Do(req) |
| 1761 |
if err != nil { |
| 1762 |
t.Fatal(err) |
| 1763 |
} |
| 1764 |
defer res.Body.Close() |
| 1765 |
gotBody, err := io.ReadAll(res.Body) |
| 1766 |
if err != nil { |
| 1767 |
t.Fatal(err) |
| 1768 |
} |
| 1769 |
if got, want := string(gotBody), body; got != want { |
| 1770 |
t.Errorf("got response body = %q; want %q", got, want) |
| 1771 |
} |
| 1772 |
} |
| 1773 |
|
| 1774 |
func TestEarlyHintsRequest(t *testing.T) { run(t, testEarlyHintsRequest) } |
| 1775 |
func testEarlyHintsRequest(t *testing.T, mode testMode) { |
| 1776 |
var wg sync.WaitGroup |
| 1777 |
wg.Add(1) |
| 1778 |
cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) { |
| 1779 |
h := w.Header() |
| 1780 |
|
| 1781 |
h.Add("Content-Length", "123") // must be ignored |
| 1782 |
h.Add("Link", "</style.css>; rel=preload; as=style") |
| 1783 |
h.Add("Link", "</script.js>; rel=preload; as=script") |
| 1784 |
w.WriteHeader(StatusEarlyHints) |
| 1785 |
|
| 1786 |
wg.Wait() |
| 1787 |
|
| 1788 |
h.Add("Link", "</foo.js>; rel=preload; as=script") |
| 1789 |
w.WriteHeader(StatusEarlyHints) |
| 1790 |
|
| 1791 |
w.Write([]byte("Hello")) |
| 1792 |
})) |
| 1793 |
|
| 1794 |
checkLinkHeaders := func(t *testing.T, expected, got []string) { |
| 1795 |
t.Helper() |
| 1796 |
|
| 1797 |
if len(expected) != len(got) { |
| 1798 |
t.Errorf("got %d expected %d", len(got), len(expected)) |
| 1799 |
} |
| 1800 |
|
| 1801 |
for i := range expected { |
| 1802 |
if expected[i] != got[i] { |
| 1803 |
t.Errorf("got %q expected %q", got[i], expected[i]) |
| 1804 |
} |
| 1805 |
} |
| 1806 |
} |
| 1807 |
|
| 1808 |
checkExcludedHeaders := func(t *testing.T, header textproto.MIMEHeader) { |
| 1809 |
t.Helper() |
| 1810 |
|
| 1811 |
for _, h := range []string{"Content-Length", "Transfer-Encoding"} { |
| 1812 |
if v, ok := header[h]; ok { |
| 1813 |
t.Errorf("%s is %q; must not be sent", h, v) |
| 1814 |
} |
| 1815 |
} |
| 1816 |
} |
| 1817 |
|
| 1818 |
var respCounter uint8 |
| 1819 |
trace := &httptrace.ClientTrace{ |
| 1820 |
Got1xxResponse: func(code int, header textproto.MIMEHeader) error { |
| 1821 |
switch respCounter { |
| 1822 |
case 0: |
| 1823 |
checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script"}, header["Link"]) |
| 1824 |
checkExcludedHeaders(t, header) |
| 1825 |
|
| 1826 |
wg.Done() |
| 1827 |
case 1: |
| 1828 |
checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script", "</foo.js>; rel=preload; as=script"}, header["Link"]) |
| 1829 |
checkExcludedHeaders(t, header) |
| 1830 |
|
| 1831 |
default: |
| 1832 |
t.Error("Unexpected 1xx response") |
| 1833 |
} |
| 1834 |
|
| 1835 |
respCounter++ |
| 1836 |
|
| 1837 |
return nil |
| 1838 |
}, |
| 1839 |
} |
| 1840 |
req, _ := NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), "GET", cst.ts.URL, nil) |
| 1841 |
|
| 1842 |
res, err := cst.c.Do(req) |
| 1843 |
if err != nil { |
| 1844 |
t.Fatal(err) |
| 1845 |
} |
| 1846 |
defer res.Body.Close() |
| 1847 |
|
| 1848 |
checkLinkHeaders(t, []string{"</style.css>; rel=preload; as=style", "</script.js>; rel=preload; as=script", "</foo.js>; rel=preload; as=script"}, res.Header["Link"]) |
| 1849 |
if cl := res.Header.Get("Content-Length"); cl != "123" { |
| 1850 |
t.Errorf("Content-Length is %q; want 123", cl) |
| 1851 |
} |
| 1852 |
|
| 1853 |
body, _ := io.ReadAll(res.Body) |
| 1854 |
if string(body) != "Hello" { |
| 1855 |
t.Errorf("Read body %q; want Hello", body) |
| 1856 |
} |
| 1857 |
} |