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