github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmhttp/client_test.go (about) 1 // Copyright 2009 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 for client.go 6 7 package gmhttp_test 8 9 import ( 10 "bytes" 11 "context" 12 "encoding/base64" 13 "errors" 14 "fmt" 15 "io" 16 "log" 17 "net" 18 "net/url" 19 "reflect" 20 "strconv" 21 "strings" 22 "sync" 23 "sync/atomic" 24 "testing" 25 "time" 26 27 . "github.com/hxx258456/ccgo/gmhttp" 28 "github.com/hxx258456/ccgo/gmhttp/cookiejar" 29 "github.com/hxx258456/ccgo/gmhttp/httptest" 30 tls "github.com/hxx258456/ccgo/gmtls" 31 ) 32 33 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) { 34 w.Header().Set("Last-Modified", "sometime") 35 fmt.Fprintf(w, "User-agent: go\nDisallow: /something/") 36 }) 37 38 // pedanticReadAll works like io.ReadAll but additionally 39 // verifies that r obeys the documented io.Reader contract. 40 func pedanticReadAll(r io.Reader) (b []byte, err error) { 41 var bufa [64]byte 42 buf := bufa[:] 43 for { 44 n, err := r.Read(buf) 45 if n == 0 && err == nil { 46 return nil, fmt.Errorf("Read: n=0 with err=nil") 47 } 48 b = append(b, buf[:n]...) 49 if err == io.EOF { 50 n, err := r.Read(buf) 51 if n != 0 || err != io.EOF { 52 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err) 53 } 54 return b, nil 55 } 56 if err != nil { 57 return b, err 58 } 59 } 60 } 61 62 type chanWriter chan string 63 64 func (w chanWriter) Write(p []byte) (n int, err error) { 65 w <- string(p) 66 return len(p), nil 67 } 68 69 func TestClient(t *testing.T) { 70 setParallel(t) 71 defer afterTest(t) 72 ts := httptest.NewServer(robotsTxtHandler) 73 defer ts.Close() 74 75 c := ts.Client() 76 r, err := c.Get(ts.URL) 77 var b []byte 78 if err == nil { 79 b, err = pedanticReadAll(r.Body) 80 r.Body.Close() 81 } 82 if err != nil { 83 t.Error(err) 84 } else if s := string(b); !strings.HasPrefix(s, "User-agent:") { 85 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s) 86 } 87 } 88 89 func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) } 90 func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) } 91 92 func testClientHead(t *testing.T, h2 bool) { 93 defer afterTest(t) 94 cst := newClientServerTest(t, h2, robotsTxtHandler) 95 defer cst.close() 96 97 r, err := cst.c.Head(cst.ts.URL) 98 if err != nil { 99 t.Fatal(err) 100 } 101 if _, ok := r.Header["Last-Modified"]; !ok { 102 t.Error("Last-Modified header not found.") 103 } 104 } 105 106 type recordingTransport struct { 107 req *Request 108 } 109 110 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) { 111 t.req = req 112 return nil, errors.New("dummy impl") 113 } 114 115 func TestGetRequestFormat(t *testing.T) { 116 setParallel(t) 117 defer afterTest(t) 118 tr := &recordingTransport{} 119 client := &Client{Transport: tr} 120 url := "http://dummy.faketld/" 121 client.Get(url) // Note: doesn't hit network 122 if tr.req.Method != "GET" { 123 t.Errorf("expected method %q; got %q", "GET", tr.req.Method) 124 } 125 if tr.req.URL.String() != url { 126 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String()) 127 } 128 if tr.req.Header == nil { 129 t.Errorf("expected non-nil request Header") 130 } 131 } 132 133 func TestPostRequestFormat(t *testing.T) { 134 defer afterTest(t) 135 tr := &recordingTransport{} 136 client := &Client{Transport: tr} 137 138 url := "http://dummy.faketld/" 139 json := `{"key":"value"}` 140 b := strings.NewReader(json) 141 client.Post(url, "application/json", b) // Note: doesn't hit network 142 143 if tr.req.Method != "POST" { 144 t.Errorf("got method %q, want %q", tr.req.Method, "POST") 145 } 146 if tr.req.URL.String() != url { 147 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url) 148 } 149 if tr.req.Header == nil { 150 t.Fatalf("expected non-nil request Header") 151 } 152 if tr.req.Close { 153 t.Error("got Close true, want false") 154 } 155 if g, e := tr.req.ContentLength, int64(len(json)); g != e { 156 t.Errorf("got ContentLength %d, want %d", g, e) 157 } 158 } 159 160 func TestPostFormRequestFormat(t *testing.T) { 161 defer afterTest(t) 162 tr := &recordingTransport{} 163 client := &Client{Transport: tr} 164 165 urlStr := "http://dummy.faketld/" 166 form := make(url.Values) 167 form.Set("foo", "bar") 168 form.Add("foo", "bar2") 169 form.Set("bar", "baz") 170 client.PostForm(urlStr, form) // Note: doesn't hit network 171 172 if tr.req.Method != "POST" { 173 t.Errorf("got method %q, want %q", tr.req.Method, "POST") 174 } 175 if tr.req.URL.String() != urlStr { 176 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr) 177 } 178 if tr.req.Header == nil { 179 t.Fatalf("expected non-nil request Header") 180 } 181 if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e { 182 t.Errorf("got Content-Type %q, want %q", g, e) 183 } 184 if tr.req.Close { 185 t.Error("got Close true, want false") 186 } 187 // Depending on map iteration, body can be either of these. 188 expectedBody := "foo=bar&foo=bar2&bar=baz" 189 expectedBody1 := "bar=baz&foo=bar&foo=bar2" 190 if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e { 191 t.Errorf("got ContentLength %d, want %d", g, e) 192 } 193 bodyb, err := io.ReadAll(tr.req.Body) 194 if err != nil { 195 t.Fatalf("ReadAll on req.Body: %v", err) 196 } 197 if g := string(bodyb); g != expectedBody && g != expectedBody1 { 198 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1) 199 } 200 } 201 202 func TestClientRedirects(t *testing.T) { 203 setParallel(t) 204 defer afterTest(t) 205 var ts *httptest.Server 206 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 207 n, _ := strconv.Atoi(r.FormValue("n")) 208 // Test Referer header. (7 is arbitrary position to test at) 209 if n == 7 { 210 if g, e := r.Referer(), ts.URL+"/?n=6"; e != g { 211 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g) 212 } 213 } 214 if n < 15 { 215 Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect) 216 return 217 } 218 fmt.Fprintf(w, "n=%d", n) 219 })) 220 defer ts.Close() 221 222 c := ts.Client() 223 _, err := c.Get(ts.URL) 224 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g { 225 t.Errorf("with default client Get, expected error %q, got %q", e, g) 226 } 227 228 // HEAD request should also have the ability to follow redirects. 229 _, err = c.Head(ts.URL) 230 if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g { 231 t.Errorf("with default client Head, expected error %q, got %q", e, g) 232 } 233 234 // Do should also follow redirects. 235 greq, _ := NewRequest("GET", ts.URL, nil) 236 _, err = c.Do(greq) 237 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g { 238 t.Errorf("with default client Do, expected error %q, got %q", e, g) 239 } 240 241 // Requests with an empty Method should also redirect (Issue 12705) 242 greq.Method = "" 243 _, err = c.Do(greq) 244 if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g { 245 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g) 246 } 247 248 var checkErr error 249 var lastVia []*Request 250 var lastReq *Request 251 c.CheckRedirect = func(req *Request, via []*Request) error { 252 lastReq = req 253 lastVia = via 254 return checkErr 255 } 256 res, err := c.Get(ts.URL) 257 if err != nil { 258 t.Fatalf("Get error: %v", err) 259 } 260 res.Body.Close() 261 finalURL := res.Request.URL.String() 262 if e, g := "<nil>", fmt.Sprintf("%v", err); e != g { 263 t.Errorf("with custom client, expected error %q, got %q", e, g) 264 } 265 if !strings.HasSuffix(finalURL, "/?n=15") { 266 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL) 267 } 268 if e, g := 15, len(lastVia); e != g { 269 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g) 270 } 271 272 // Test that Request.Cancel is propagated between requests (Issue 14053) 273 creq, _ := NewRequest("HEAD", ts.URL, nil) 274 cancel := make(chan struct{}) 275 creq.Cancel = cancel 276 if _, err := c.Do(creq); err != nil { 277 t.Fatal(err) 278 } 279 if lastReq == nil { 280 t.Fatal("didn't see redirect") 281 } 282 if lastReq.Cancel != cancel { 283 t.Errorf("expected lastReq to have the cancel channel set on the initial req") 284 } 285 286 checkErr = errors.New("no redirects allowed") 287 res, err = c.Get(ts.URL) 288 if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr { 289 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err) 290 } 291 if res == nil { 292 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)") 293 } 294 res.Body.Close() 295 if res.Header.Get("Location") == "" { 296 t.Errorf("no Location header in Response") 297 } 298 } 299 300 // Tests that Client redirects' contexts are derived from the original request's context. 301 func TestClientRedirectContext(t *testing.T) { 302 setParallel(t) 303 defer afterTest(t) 304 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 305 Redirect(w, r, "/", StatusTemporaryRedirect) 306 })) 307 defer ts.Close() 308 309 ctx, cancel := context.WithCancel(context.Background()) 310 c := ts.Client() 311 c.CheckRedirect = func(req *Request, via []*Request) error { 312 cancel() 313 select { 314 case <-req.Context().Done(): 315 return nil 316 case <-time.After(5 * time.Second): 317 return errors.New("redirected request's context never expired after root request canceled") 318 } 319 } 320 req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil) 321 _, err := c.Do(req) 322 ue, ok := err.(*url.Error) 323 if !ok { 324 t.Fatalf("got error %T; want *url.Error", err) 325 } 326 if ue.Err != context.Canceled { 327 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled) 328 } 329 } 330 331 type redirectTest struct { 332 suffix string 333 want int // response code 334 redirectBody string 335 } 336 337 func TestPostRedirects(t *testing.T) { 338 postRedirectTests := []redirectTest{ 339 {"/", 200, "first"}, 340 {"/?code=301&next=302", 200, "c301"}, 341 {"/?code=302&next=302", 200, "c302"}, 342 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348 343 {"/?code=304", 304, "c304"}, 344 {"/?code=305", 305, "c305"}, 345 {"/?code=307&next=303,308,302", 200, "c307"}, 346 {"/?code=308&next=302,301", 200, "c308"}, 347 {"/?code=404", 404, "c404"}, 348 } 349 350 wantSegments := []string{ 351 `POST / "first"`, 352 `POST /?code=301&next=302 "c301"`, 353 `GET /?code=302 ""`, 354 `GET / ""`, 355 `POST /?code=302&next=302 "c302"`, 356 `GET /?code=302 ""`, 357 `GET / ""`, 358 `POST /?code=303&next=301 "c303wc301"`, 359 `GET /?code=301 ""`, 360 `GET / ""`, 361 `POST /?code=304 "c304"`, 362 `POST /?code=305 "c305"`, 363 `POST /?code=307&next=303,308,302 "c307"`, 364 `POST /?code=303&next=308,302 "c307"`, 365 `GET /?code=308&next=302 ""`, 366 `GET /?code=302 "c307"`, 367 `GET / ""`, 368 `POST /?code=308&next=302,301 "c308"`, 369 `POST /?code=302&next=301 "c308"`, 370 `GET /?code=301 ""`, 371 `GET / ""`, 372 `POST /?code=404 "c404"`, 373 } 374 want := strings.Join(wantSegments, "\n") 375 testRedirectsByMethod(t, "POST", postRedirectTests, want) 376 } 377 378 func TestDeleteRedirects(t *testing.T) { 379 deleteRedirectTests := []redirectTest{ 380 {"/", 200, "first"}, 381 {"/?code=301&next=302,308", 200, "c301"}, 382 {"/?code=302&next=302", 200, "c302"}, 383 {"/?code=303", 200, "c303"}, 384 {"/?code=307&next=301,308,303,302,304", 304, "c307"}, 385 {"/?code=308&next=307", 200, "c308"}, 386 {"/?code=404", 404, "c404"}, 387 } 388 389 wantSegments := []string{ 390 `DELETE / "first"`, 391 `DELETE /?code=301&next=302,308 "c301"`, 392 `GET /?code=302&next=308 ""`, 393 `GET /?code=308 ""`, 394 `GET / "c301"`, 395 `DELETE /?code=302&next=302 "c302"`, 396 `GET /?code=302 ""`, 397 `GET / ""`, 398 `DELETE /?code=303 "c303"`, 399 `GET / ""`, 400 `DELETE /?code=307&next=301,308,303,302,304 "c307"`, 401 `DELETE /?code=301&next=308,303,302,304 "c307"`, 402 `GET /?code=308&next=303,302,304 ""`, 403 `GET /?code=303&next=302,304 "c307"`, 404 `GET /?code=302&next=304 ""`, 405 `GET /?code=304 ""`, 406 `DELETE /?code=308&next=307 "c308"`, 407 `DELETE /?code=307 "c308"`, 408 `DELETE / "c308"`, 409 `DELETE /?code=404 "c404"`, 410 } 411 want := strings.Join(wantSegments, "\n") 412 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want) 413 } 414 415 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) { 416 defer afterTest(t) 417 var log struct { 418 sync.Mutex 419 bytes.Buffer 420 } 421 var ts *httptest.Server 422 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 423 log.Lock() 424 slurp, _ := io.ReadAll(r.Body) 425 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp) 426 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") { 427 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl) 428 } 429 log.WriteByte('\n') 430 log.Unlock() 431 urlQuery := r.URL.Query() 432 if v := urlQuery.Get("code"); v != "" { 433 location := ts.URL 434 if final := urlQuery.Get("next"); final != "" { 435 splits := strings.Split(final, ",") 436 first, rest := splits[0], splits[1:] 437 location = fmt.Sprintf("%s?code=%s", location, first) 438 if len(rest) > 0 { 439 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ",")) 440 } 441 } 442 code, _ := strconv.Atoi(v) 443 if code/100 == 3 { 444 w.Header().Set("Location", location) 445 } 446 w.WriteHeader(code) 447 } 448 })) 449 defer ts.Close() 450 451 c := ts.Client() 452 for _, tt := range table { 453 content := tt.redirectBody 454 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content)) 455 req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil } 456 res, err := c.Do(req) 457 458 if err != nil { 459 t.Fatal(err) 460 } 461 if res.StatusCode != tt.want { 462 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want) 463 } 464 } 465 log.Lock() 466 got := log.String() 467 log.Unlock() 468 469 got = strings.TrimSpace(got) 470 want = strings.TrimSpace(want) 471 472 if got != want { 473 got, want, lines := removeCommonLines(got, want) 474 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want) 475 } 476 } 477 478 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) { 479 for { 480 nl := strings.IndexByte(a, '\n') 481 if nl < 0 { 482 return a, b, commonLines 483 } 484 line := a[:nl+1] 485 if !strings.HasPrefix(b, line) { 486 return a, b, commonLines 487 } 488 commonLines++ 489 a = a[len(line):] 490 b = b[len(line):] 491 } 492 } 493 494 func TestClientRedirectUseResponse(t *testing.T) { 495 setParallel(t) 496 defer afterTest(t) 497 const body = "Hello, world." 498 var ts *httptest.Server 499 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 500 if strings.Contains(r.URL.Path, "/other") { 501 io.WriteString(w, "wrong body") 502 } else { 503 w.Header().Set("Location", ts.URL+"/other") 504 w.WriteHeader(StatusFound) 505 io.WriteString(w, body) 506 } 507 })) 508 defer ts.Close() 509 510 c := ts.Client() 511 c.CheckRedirect = func(req *Request, via []*Request) error { 512 if req.Response == nil { 513 t.Error("expected non-nil Request.Response") 514 } 515 return ErrUseLastResponse 516 } 517 res, err := c.Get(ts.URL) 518 if err != nil { 519 t.Fatal(err) 520 } 521 if res.StatusCode != StatusFound { 522 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound) 523 } 524 defer res.Body.Close() 525 slurp, err := io.ReadAll(res.Body) 526 if err != nil { 527 t.Fatal(err) 528 } 529 if string(slurp) != body { 530 t.Errorf("body = %q; want %q", slurp, body) 531 } 532 } 533 534 // Issue 17773: don't follow a 308 (or 307) if the response doesn't 535 // have a Location header. 536 func TestClientRedirect308NoLocation(t *testing.T) { 537 setParallel(t) 538 defer afterTest(t) 539 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 540 w.Header().Set("Foo", "Bar") 541 w.WriteHeader(308) 542 })) 543 defer ts.Close() 544 c := ts.Client() 545 res, err := c.Get(ts.URL) 546 if err != nil { 547 t.Fatal(err) 548 } 549 res.Body.Close() 550 if res.StatusCode != 308 { 551 t.Errorf("status = %d; want %d", res.StatusCode, 308) 552 } 553 if got := res.Header.Get("Foo"); got != "Bar" { 554 t.Errorf("Foo header = %q; want Bar", got) 555 } 556 } 557 558 // Don't follow a 307/308 if we can't resent the request body. 559 func TestClientRedirect308NoGetBody(t *testing.T) { 560 setParallel(t) 561 defer afterTest(t) 562 const fakeURL = "https://localhost:1234/" // won't be hit 563 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 564 w.Header().Set("Location", fakeURL) 565 w.WriteHeader(308) 566 })) 567 defer ts.Close() 568 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body")) 569 if err != nil { 570 t.Fatal(err) 571 } 572 c := ts.Client() 573 req.GetBody = nil // so it can't rewind. 574 res, err := c.Do(req) 575 if err != nil { 576 t.Fatal(err) 577 } 578 res.Body.Close() 579 if res.StatusCode != 308 { 580 t.Errorf("status = %d; want %d", res.StatusCode, 308) 581 } 582 if got := res.Header.Get("Location"); got != fakeURL { 583 t.Errorf("Location header = %q; want %q", got, fakeURL) 584 } 585 } 586 587 var expectedCookies = []*Cookie{ 588 {Name: "ChocolateChip", Value: "tasty"}, 589 {Name: "First", Value: "Hit"}, 590 {Name: "Second", Value: "Hit"}, 591 } 592 593 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) { 594 for _, cookie := range r.Cookies() { 595 SetCookie(w, cookie) 596 } 597 if r.URL.Path == "/" { 598 SetCookie(w, expectedCookies[1]) 599 Redirect(w, r, "/second", StatusMovedPermanently) 600 } else { 601 SetCookie(w, expectedCookies[2]) 602 w.Write([]byte("hello")) 603 } 604 }) 605 606 func TestClientSendsCookieFromJar(t *testing.T) { 607 defer afterTest(t) 608 tr := &recordingTransport{} 609 client := &Client{Transport: tr} 610 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)} 611 us := "http://dummy.faketld/" 612 u, _ := url.Parse(us) 613 client.Jar.SetCookies(u, expectedCookies) 614 615 client.Get(us) // Note: doesn't hit network 616 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 617 618 client.Head(us) // Note: doesn't hit network 619 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 620 621 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network 622 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 623 624 client.PostForm(us, url.Values{}) // Note: doesn't hit network 625 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 626 627 req, _ := NewRequest("GET", us, nil) 628 client.Do(req) // Note: doesn't hit network 629 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 630 631 req, _ = NewRequest("POST", us, nil) 632 client.Do(req) // Note: doesn't hit network 633 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 634 } 635 636 // Just enough correctness for our redirect tests. Uses the URL.Host as the 637 // scope of all cookies. 638 type TestJar struct { 639 m sync.Mutex 640 perURL map[string][]*Cookie 641 } 642 643 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) { 644 j.m.Lock() 645 defer j.m.Unlock() 646 if j.perURL == nil { 647 j.perURL = make(map[string][]*Cookie) 648 } 649 j.perURL[u.Host] = cookies 650 } 651 652 func (j *TestJar) Cookies(u *url.URL) []*Cookie { 653 j.m.Lock() 654 defer j.m.Unlock() 655 return j.perURL[u.Host] 656 } 657 658 func TestRedirectCookiesJar(t *testing.T) { 659 setParallel(t) 660 defer afterTest(t) 661 var ts *httptest.Server 662 ts = httptest.NewServer(echoCookiesRedirectHandler) 663 defer ts.Close() 664 c := ts.Client() 665 c.Jar = new(TestJar) 666 u, _ := url.Parse(ts.URL) 667 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]}) 668 resp, err := c.Get(ts.URL) 669 if err != nil { 670 t.Fatalf("Get: %v", err) 671 } 672 resp.Body.Close() 673 matchReturnedCookies(t, expectedCookies, resp.Cookies()) 674 } 675 676 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) { 677 if len(given) != len(expected) { 678 t.Logf("Received cookies: %v", given) 679 t.Errorf("Expected %d cookies, got %d", len(expected), len(given)) 680 } 681 for _, ec := range expected { 682 foundC := false 683 for _, c := range given { 684 if ec.Name == c.Name && ec.Value == c.Value { 685 foundC = true 686 break 687 } 688 } 689 if !foundC { 690 t.Errorf("Missing cookie %v", ec) 691 } 692 } 693 } 694 695 func TestJarCalls(t *testing.T) { 696 defer afterTest(t) 697 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 698 pathSuffix := r.RequestURI[1:] 699 if r.RequestURI == "/nosetcookie" { 700 return // don't set cookies for this path 701 } 702 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix}) 703 if r.RequestURI == "/" { 704 Redirect(w, r, "http://secondhost.fake/secondpath", 302) 705 } 706 })) 707 defer ts.Close() 708 jar := new(RecordingJar) 709 c := ts.Client() 710 c.Jar = jar 711 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) { 712 return net.Dial("tcp", ts.Listener.Addr().String()) 713 } 714 _, err := c.Get("http://firsthost.fake/") 715 if err != nil { 716 t.Fatal(err) 717 } 718 _, err = c.Get("http://firsthost.fake/nosetcookie") 719 if err != nil { 720 t.Fatal(err) 721 } 722 got := jar.log.String() 723 want := `Cookies("http://firsthost.fake/") 724 SetCookie("http://firsthost.fake/", [name=val]) 725 Cookies("http://secondhost.fake/secondpath") 726 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath]) 727 Cookies("http://firsthost.fake/nosetcookie") 728 ` 729 if got != want { 730 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want) 731 } 732 } 733 734 // RecordingJar keeps a log of calls made to it, without 735 // tracking any cookies. 736 type RecordingJar struct { 737 mu sync.Mutex 738 log bytes.Buffer 739 } 740 741 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) { 742 j.logf("SetCookie(%q, %v)\n", u, cookies) 743 } 744 745 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie { 746 j.logf("Cookies(%q)\n", u) 747 return nil 748 } 749 750 func (j *RecordingJar) logf(format string, args ...interface{}) { 751 j.mu.Lock() 752 defer j.mu.Unlock() 753 fmt.Fprintf(&j.log, format, args...) 754 } 755 756 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) } 757 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) } 758 759 func testStreamingGet(t *testing.T, h2 bool) { 760 defer afterTest(t) 761 say := make(chan string) 762 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 763 w.(Flusher).Flush() 764 for str := range say { 765 w.Write([]byte(str)) 766 w.(Flusher).Flush() 767 } 768 })) 769 defer cst.close() 770 771 c := cst.c 772 res, err := c.Get(cst.ts.URL) 773 if err != nil { 774 t.Fatal(err) 775 } 776 var buf [10]byte 777 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} { 778 say <- str 779 n, err := io.ReadFull(res.Body, buf[0:len(str)]) 780 if err != nil { 781 t.Fatalf("ReadFull on %q: %v", str, err) 782 } 783 if n != len(str) { 784 t.Fatalf("Receiving %q, only read %d bytes", str, n) 785 } 786 got := string(buf[0:n]) 787 if got != str { 788 t.Fatalf("Expected %q, got %q", str, got) 789 } 790 } 791 close(say) 792 _, err = io.ReadFull(res.Body, buf[0:1]) 793 if err != io.EOF { 794 t.Fatalf("at end expected EOF, got %v", err) 795 } 796 } 797 798 type writeCountingConn struct { 799 net.Conn 800 count *int 801 } 802 803 func (c *writeCountingConn) Write(p []byte) (int, error) { 804 *c.count++ 805 return c.Conn.Write(p) 806 } 807 808 // TestClientWrites verifies that client requests are buffered and we 809 // don't send a TCP packet per line of the http request + body. 810 func TestClientWrites(t *testing.T) { 811 defer afterTest(t) 812 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 813 })) 814 defer ts.Close() 815 816 writes := 0 817 dialer := func(netz string, addr string) (net.Conn, error) { 818 c, err := net.Dial(netz, addr) 819 if err == nil { 820 c = &writeCountingConn{c, &writes} 821 } 822 return c, err 823 } 824 c := ts.Client() 825 c.Transport.(*Transport).Dial = dialer 826 827 _, err := c.Get(ts.URL) 828 if err != nil { 829 t.Fatal(err) 830 } 831 if writes != 1 { 832 t.Errorf("Get request did %d Write calls, want 1", writes) 833 } 834 835 writes = 0 836 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}}) 837 if err != nil { 838 t.Fatal(err) 839 } 840 if writes != 1 { 841 t.Errorf("Post request did %d Write calls, want 1", writes) 842 } 843 } 844 845 func TestClientInsecureTransport(t *testing.T) { 846 setParallel(t) 847 defer afterTest(t) 848 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 849 w.Write([]byte("Hello")) 850 })) 851 errc := make(chanWriter, 10) // but only expecting 1 852 ts.Config.ErrorLog = log.New(errc, "", 0) 853 defer ts.Close() 854 855 // TODO(bradfitz): add tests for skipping hostname checks too? 856 // would require a new cert for testing, and probably 857 // redundant with these tests. 858 c := ts.Client() 859 for _, insecure := range []bool{true, false} { 860 c.Transport.(*Transport).TLSClientConfig = &tls.Config{ 861 InsecureSkipVerify: insecure, 862 } 863 res, err := c.Get(ts.URL) 864 if (err == nil) != insecure { 865 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err) 866 } 867 if res != nil { 868 res.Body.Close() 869 } 870 } 871 872 select { 873 case v := <-errc: 874 if !strings.Contains(v, "TLS handshake error") { 875 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v) 876 } 877 case <-time.After(5 * time.Second): 878 t.Errorf("timeout waiting for logged error") 879 } 880 881 } 882 883 func TestClientErrorWithRequestURI(t *testing.T) { 884 defer afterTest(t) 885 req, _ := NewRequest("GET", "http://localhost:1234/", nil) 886 req.RequestURI = "/this/field/is/illegal/and/should/error/" 887 _, err := DefaultClient.Do(req) 888 if err == nil { 889 t.Fatalf("expected an error") 890 } 891 if !strings.Contains(err.Error(), "RequestURI") { 892 t.Errorf("wanted error mentioning RequestURI; got error: %v", err) 893 } 894 } 895 896 func TestClientWithCorrectTLSServerName(t *testing.T) { 897 defer afterTest(t) 898 899 const serverName = "example.com" 900 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 901 if r.TLS.ServerName != serverName { 902 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName) 903 } 904 })) 905 defer ts.Close() 906 907 c := ts.Client() 908 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName 909 if _, err := c.Get(ts.URL); err != nil { 910 t.Fatalf("expected successful TLS connection, got error: %v", err) 911 } 912 } 913 914 func TestClientWithIncorrectTLSServerName(t *testing.T) { 915 defer afterTest(t) 916 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 917 defer ts.Close() 918 errc := make(chanWriter, 10) // but only expecting 1 919 ts.Config.ErrorLog = log.New(errc, "", 0) 920 921 c := ts.Client() 922 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver" 923 _, err := c.Get(ts.URL) 924 if err == nil { 925 t.Fatalf("expected an error") 926 } 927 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") { 928 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err) 929 } 930 select { 931 case v := <-errc: 932 if !strings.Contains(v, "TLS handshake error") { 933 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v) 934 } 935 case <-time.After(5 * time.Second): 936 t.Errorf("timeout waiting for logged error") 937 } 938 } 939 940 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName 941 // when not empty. 942 // 943 // tls.Config.ServerName (non-empty, set to "example.com") takes 944 // precedence over "some-other-host.tld" which previously incorrectly 945 // took precedence. We don't actually connect to (or even resolve) 946 // "some-other-host.tld", though, because of the Transport.Dial hook. 947 // 948 // The httptest.Server has a cert with "example.com" as its name. 949 func TestTransportUsesTLSConfigServerName(t *testing.T) { 950 defer afterTest(t) 951 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 952 w.Write([]byte("Hello")) 953 })) 954 defer ts.Close() 955 956 c := ts.Client() 957 tr := c.Transport.(*Transport) 958 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names 959 tr.Dial = func(netw, addr string) (net.Conn, error) { 960 return net.Dial(netw, ts.Listener.Addr().String()) 961 } 962 res, err := c.Get("https://some-other-host.tld/") 963 if err != nil { 964 t.Fatal(err) 965 } 966 res.Body.Close() 967 } 968 969 func TestResponseSetsTLSConnectionState(t *testing.T) { 970 defer afterTest(t) 971 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 972 w.Write([]byte("Hello")) 973 })) 974 defer ts.Close() 975 976 c := ts.Client() 977 tr := c.Transport.(*Transport) 978 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA} 979 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite 980 tr.Dial = func(netw, addr string) (net.Conn, error) { 981 return net.Dial(netw, ts.Listener.Addr().String()) 982 } 983 res, err := c.Get("https://example.com/") 984 if err != nil { 985 t.Fatal(err) 986 } 987 defer res.Body.Close() 988 if res.TLS == nil { 989 t.Fatal("Response didn't set TLS Connection State.") 990 } 991 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want { 992 t.Errorf("TLS Cipher Suite = %d; want %d", got, want) 993 } 994 } 995 996 // Check that an HTTPS client can interpret a particular TLS error 997 // to determine that the server is speaking HTTP. 998 // See golang.org/issue/11111. 999 func TestHTTPSClientDetectsHTTPServer(t *testing.T) { 1000 defer afterTest(t) 1001 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 1002 ts.Config.ErrorLog = quietLog 1003 defer ts.Close() 1004 1005 _, err := Get(strings.Replace(ts.URL, "http", "https", 1)) 1006 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") { 1007 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got) 1008 } 1009 } 1010 1011 // Verify Response.ContentLength is populated. https://golang.org/issue/4126 1012 func TestClientHeadContentLength_h1(t *testing.T) { 1013 testClientHeadContentLength(t, h1Mode) 1014 } 1015 1016 func TestClientHeadContentLength_h2(t *testing.T) { 1017 testClientHeadContentLength(t, h2Mode) 1018 } 1019 1020 func testClientHeadContentLength(t *testing.T, h2 bool) { 1021 defer afterTest(t) 1022 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1023 if v := r.FormValue("cl"); v != "" { 1024 w.Header().Set("Content-Length", v) 1025 } 1026 })) 1027 defer cst.close() 1028 tests := []struct { 1029 suffix string 1030 want int64 1031 }{ 1032 {"/?cl=1234", 1234}, 1033 {"/?cl=0", 0}, 1034 {"", -1}, 1035 } 1036 for _, tt := range tests { 1037 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil) 1038 res, err := cst.c.Do(req) 1039 if err != nil { 1040 t.Fatal(err) 1041 } 1042 if res.ContentLength != tt.want { 1043 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want) 1044 } 1045 bs, err := io.ReadAll(res.Body) 1046 if err != nil { 1047 t.Fatal(err) 1048 } 1049 if len(bs) != 0 { 1050 t.Errorf("Unexpected content: %q", bs) 1051 } 1052 } 1053 } 1054 1055 func TestEmptyPasswordAuth(t *testing.T) { 1056 setParallel(t) 1057 defer afterTest(t) 1058 gopher := "gopher" 1059 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1060 auth := r.Header.Get("Authorization") 1061 if strings.HasPrefix(auth, "Basic ") { 1062 encoded := auth[6:] 1063 decoded, err := base64.StdEncoding.DecodeString(encoded) 1064 if err != nil { 1065 t.Fatal(err) 1066 } 1067 expected := gopher + ":" 1068 s := string(decoded) 1069 if expected != s { 1070 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected) 1071 } 1072 } else { 1073 t.Errorf("Invalid auth %q", auth) 1074 } 1075 })) 1076 defer ts.Close() 1077 req, err := NewRequest("GET", ts.URL, nil) 1078 if err != nil { 1079 t.Fatal(err) 1080 } 1081 req.URL.User = url.User(gopher) 1082 c := ts.Client() 1083 resp, err := c.Do(req) 1084 if err != nil { 1085 t.Fatal(err) 1086 } 1087 defer resp.Body.Close() 1088 } 1089 1090 func TestBasicAuth(t *testing.T) { 1091 defer afterTest(t) 1092 tr := &recordingTransport{} 1093 client := &Client{Transport: tr} 1094 1095 url := "http://My%20User:My%20Pass@dummy.faketld/" 1096 expected := "My User:My Pass" 1097 client.Get(url) 1098 1099 if tr.req.Method != "GET" { 1100 t.Errorf("got method %q, want %q", tr.req.Method, "GET") 1101 } 1102 if tr.req.URL.String() != url { 1103 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url) 1104 } 1105 if tr.req.Header == nil { 1106 t.Fatalf("expected non-nil request Header") 1107 } 1108 auth := tr.req.Header.Get("Authorization") 1109 if strings.HasPrefix(auth, "Basic ") { 1110 encoded := auth[6:] 1111 decoded, err := base64.StdEncoding.DecodeString(encoded) 1112 if err != nil { 1113 t.Fatal(err) 1114 } 1115 s := string(decoded) 1116 if expected != s { 1117 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected) 1118 } 1119 } else { 1120 t.Errorf("Invalid auth %q", auth) 1121 } 1122 } 1123 1124 func TestBasicAuthHeadersPreserved(t *testing.T) { 1125 defer afterTest(t) 1126 tr := &recordingTransport{} 1127 client := &Client{Transport: tr} 1128 1129 // If Authorization header is provided, username in URL should not override it 1130 url := "http://My%20User@dummy.faketld/" 1131 req, err := NewRequest("GET", url, nil) 1132 if err != nil { 1133 t.Fatal(err) 1134 } 1135 req.SetBasicAuth("My User", "My Pass") 1136 expected := "My User:My Pass" 1137 client.Do(req) 1138 1139 if tr.req.Method != "GET" { 1140 t.Errorf("got method %q, want %q", tr.req.Method, "GET") 1141 } 1142 if tr.req.URL.String() != url { 1143 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url) 1144 } 1145 if tr.req.Header == nil { 1146 t.Fatalf("expected non-nil request Header") 1147 } 1148 auth := tr.req.Header.Get("Authorization") 1149 if strings.HasPrefix(auth, "Basic ") { 1150 encoded := auth[6:] 1151 decoded, err := base64.StdEncoding.DecodeString(encoded) 1152 if err != nil { 1153 t.Fatal(err) 1154 } 1155 s := string(decoded) 1156 if expected != s { 1157 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected) 1158 } 1159 } else { 1160 t.Errorf("Invalid auth %q", auth) 1161 } 1162 1163 } 1164 1165 func TestStripPasswordFromError(t *testing.T) { 1166 client := &Client{Transport: &recordingTransport{}} 1167 testCases := []struct { 1168 desc string 1169 in string 1170 out string 1171 }{ 1172 { 1173 desc: "Strip password from error message", 1174 in: "http://user:password@dummy.faketld/", 1175 out: `Get "http://user:***@dummy.faketld/": dummy impl`, 1176 }, 1177 { 1178 desc: "Don't Strip password from domain name", 1179 in: "http://user:password@password.faketld/", 1180 out: `Get "http://user:***@password.faketld/": dummy impl`, 1181 }, 1182 { 1183 desc: "Don't Strip password from path", 1184 in: "http://user:password@dummy.faketld/password", 1185 out: `Get "http://user:***@dummy.faketld/password": dummy impl`, 1186 }, 1187 { 1188 desc: "Strip escaped password", 1189 in: "http://user:pa%2Fssword@dummy.faketld/", 1190 out: `Get "http://user:***@dummy.faketld/": dummy impl`, 1191 }, 1192 } 1193 for _, tC := range testCases { 1194 t.Run(tC.desc, func(t *testing.T) { 1195 _, err := client.Get(tC.in) 1196 if err.Error() != tC.out { 1197 t.Errorf("Unexpected output for %q: expected %q, actual %q", 1198 tC.in, tC.out, err.Error()) 1199 } 1200 }) 1201 } 1202 } 1203 1204 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) } 1205 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) } 1206 1207 func testClientTimeout(t *testing.T, h2 bool) { 1208 setParallel(t) 1209 defer afterTest(t) 1210 testDone := make(chan struct{}) // closed in defer below 1211 1212 sawRoot := make(chan bool, 1) 1213 sawSlow := make(chan bool, 1) 1214 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1215 if r.URL.Path == "/" { 1216 sawRoot <- true 1217 Redirect(w, r, "/slow", StatusFound) 1218 return 1219 } 1220 if r.URL.Path == "/slow" { 1221 sawSlow <- true 1222 w.Write([]byte("Hello")) 1223 w.(Flusher).Flush() 1224 <-testDone 1225 return 1226 } 1227 })) 1228 defer cst.close() 1229 defer close(testDone) // before cst.close, to unblock /slow handler 1230 1231 // 200ms should be long enough to get a normal request (the / 1232 // handler), but not so long that it makes the test slow. 1233 const timeout = 200 * time.Millisecond 1234 cst.c.Timeout = timeout 1235 1236 res, err := cst.c.Get(cst.ts.URL) 1237 if err != nil { 1238 if strings.Contains(err.Error(), "Client.Timeout") { 1239 t.Skipf("host too slow to get fast resource in %v", timeout) 1240 } 1241 t.Fatal(err) 1242 } 1243 1244 select { 1245 case <-sawRoot: 1246 // good. 1247 default: 1248 t.Fatal("handler never got / request") 1249 } 1250 1251 select { 1252 case <-sawSlow: 1253 // good. 1254 default: 1255 t.Fatal("handler never got /slow request") 1256 } 1257 1258 errc := make(chan error, 1) 1259 go func() { 1260 _, err := io.ReadAll(res.Body) 1261 errc <- err 1262 res.Body.Close() 1263 }() 1264 1265 const failTime = 5 * time.Second 1266 select { 1267 case err := <-errc: 1268 if err == nil { 1269 t.Fatal("expected error from ReadAll") 1270 } 1271 ne, ok := err.(net.Error) 1272 if !ok { 1273 t.Errorf("error value from ReadAll was %T; expected some net.Error", err) 1274 } else if !ne.Timeout() { 1275 t.Errorf("net.Error.Timeout = false; want true") 1276 } 1277 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") { 1278 t.Errorf("error string = %q; missing timeout substring", got) 1279 } 1280 case <-time.After(failTime): 1281 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout) 1282 } 1283 } 1284 1285 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) } 1286 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) } 1287 1288 // Client.Timeout firing before getting to the body 1289 func testClientTimeout_Headers(t *testing.T, h2 bool) { 1290 setParallel(t) 1291 defer afterTest(t) 1292 donec := make(chan bool, 1) 1293 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1294 <-donec 1295 }), optQuietLog) 1296 defer cst.close() 1297 // Note that we use a channel send here and not a close. 1298 // The race detector doesn't know that we're waiting for a timeout 1299 // and thinks that the waitgroup inside httptest.Server is added to concurrently 1300 // with us closing it. If we timed out immediately, we could close the testserver 1301 // before we entered the handler. We're not timing out immediately and there's 1302 // no way we would be done before we entered the handler, but the race detector 1303 // doesn't know this, so synchronize explicitly. 1304 defer func() { donec <- true }() 1305 1306 cst.c.Timeout = 5 * time.Millisecond 1307 res, err := cst.c.Get(cst.ts.URL) 1308 if err == nil { 1309 res.Body.Close() 1310 t.Fatal("got response from Get; expected error") 1311 } 1312 if _, ok := err.(*url.Error); !ok { 1313 t.Fatalf("Got error of type %T; want *url.Error", err) 1314 } 1315 ne, ok := err.(net.Error) 1316 if !ok { 1317 t.Fatalf("Got error of type %T; want some net.Error", err) 1318 } 1319 if !ne.Timeout() { 1320 t.Error("net.Error.Timeout = false; want true") 1321 } 1322 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") { 1323 t.Errorf("error string = %q; missing timeout substring", got) 1324 } 1325 } 1326 1327 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be 1328 // returned. 1329 func TestClientTimeoutCancel(t *testing.T) { 1330 setParallel(t) 1331 defer afterTest(t) 1332 1333 testDone := make(chan struct{}) 1334 ctx, cancel := context.WithCancel(context.Background()) 1335 1336 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1337 w.(Flusher).Flush() 1338 <-testDone 1339 })) 1340 defer cst.close() 1341 defer close(testDone) 1342 1343 cst.c.Timeout = 1 * time.Hour 1344 req, _ := NewRequest("GET", cst.ts.URL, nil) 1345 req.Cancel = ctx.Done() 1346 res, err := cst.c.Do(req) 1347 if err != nil { 1348 t.Fatal(err) 1349 } 1350 cancel() 1351 _, err = io.Copy(io.Discard, res.Body) 1352 if err != ExportErrRequestCanceled { 1353 t.Fatalf("error = %v; want errRequestCanceled", err) 1354 } 1355 } 1356 1357 func TestClientTimeoutDoesNotExpire_h1(t *testing.T) { testClientTimeoutDoesNotExpire(t, h1Mode) } 1358 func TestClientTimeoutDoesNotExpire_h2(t *testing.T) { testClientTimeoutDoesNotExpire(t, h2Mode) } 1359 1360 // Issue 49366: if Client.Timeout is set but not hit, no error should be returned. 1361 func testClientTimeoutDoesNotExpire(t *testing.T, h2 bool) { 1362 setParallel(t) 1363 defer afterTest(t) 1364 1365 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1366 w.Write([]byte("body")) 1367 })) 1368 defer cst.close() 1369 1370 cst.c.Timeout = 1 * time.Hour 1371 req, _ := NewRequest("GET", cst.ts.URL, nil) 1372 res, err := cst.c.Do(req) 1373 if err != nil { 1374 t.Fatal(err) 1375 } 1376 if _, err = io.Copy(io.Discard, res.Body); err != nil { 1377 t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err) 1378 } 1379 if err = res.Body.Close(); err != nil { 1380 t.Fatalf("res.Body.Close() = %v, want nil", err) 1381 } 1382 } 1383 1384 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) } 1385 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) } 1386 func testClientRedirectEatsBody(t *testing.T, h2 bool) { 1387 setParallel(t) 1388 defer afterTest(t) 1389 saw := make(chan string, 2) 1390 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1391 saw <- r.RemoteAddr 1392 if r.URL.Path == "/" { 1393 Redirect(w, r, "/foo", StatusFound) // which includes a body 1394 } 1395 })) 1396 defer cst.close() 1397 1398 res, err := cst.c.Get(cst.ts.URL) 1399 if err != nil { 1400 t.Fatal(err) 1401 } 1402 _, err = io.ReadAll(res.Body) 1403 res.Body.Close() 1404 if err != nil { 1405 t.Fatal(err) 1406 } 1407 1408 var first string 1409 select { 1410 case first = <-saw: 1411 default: 1412 t.Fatal("server didn't see a request") 1413 } 1414 1415 var second string 1416 select { 1417 case second = <-saw: 1418 default: 1419 t.Fatal("server didn't see a second request") 1420 } 1421 1422 if first != second { 1423 t.Fatal("server saw different client ports before & after the redirect") 1424 } 1425 } 1426 1427 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF. 1428 type eofReaderFunc func() 1429 1430 func (f eofReaderFunc) Read(p []byte) (n int, err error) { 1431 f() 1432 return 0, io.EOF 1433 } 1434 1435 func TestReferer(t *testing.T) { 1436 tests := []struct { 1437 lastReq, newReq string // from -> to URLs 1438 want string 1439 }{ 1440 // don't send user: 1441 {"http://gopher@test.com", "http://link.com", "http://test.com"}, 1442 {"https://gopher@test.com", "https://link.com", "https://test.com"}, 1443 1444 // don't send a user and password: 1445 {"http://gopher:go@test.com", "http://link.com", "http://test.com"}, 1446 {"https://gopher:go@test.com", "https://link.com", "https://test.com"}, 1447 1448 // nothing to do: 1449 {"http://test.com", "http://link.com", "http://test.com"}, 1450 {"https://test.com", "https://link.com", "https://test.com"}, 1451 1452 // https to http doesn't send a referer: 1453 {"https://test.com", "http://link.com", ""}, 1454 {"https://gopher:go@test.com", "http://link.com", ""}, 1455 } 1456 for _, tt := range tests { 1457 l, err := url.Parse(tt.lastReq) 1458 if err != nil { 1459 t.Fatal(err) 1460 } 1461 n, err := url.Parse(tt.newReq) 1462 if err != nil { 1463 t.Fatal(err) 1464 } 1465 r := ExportRefererForURL(l, n) 1466 if r != tt.want { 1467 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want) 1468 } 1469 } 1470 } 1471 1472 // issue15577Tripper returns a Response with a redirect response 1473 // header and doesn't populate its Response.Request field. 1474 type issue15577Tripper struct{} 1475 1476 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) { 1477 resp := &Response{ 1478 StatusCode: 303, 1479 Header: map[string][]string{"Location": {"http://www.example.com/"}}, 1480 Body: io.NopCloser(strings.NewReader("")), 1481 } 1482 return resp, nil 1483 } 1484 1485 // Issue 15577: don't assume the roundtripper's response populates its Request field. 1486 func TestClientRedirectResponseWithoutRequest(t *testing.T) { 1487 c := &Client{ 1488 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") }, 1489 Transport: issue15577Tripper{}, 1490 } 1491 // Check that this doesn't crash: 1492 c.Get("http://dummy.tld") 1493 } 1494 1495 // Issue 4800: copy (some) headers when Client follows a redirect. 1496 func TestClientCopyHeadersOnRedirect(t *testing.T) { 1497 const ( 1498 ua = "some-agent/1.2" 1499 xfoo = "foo-val" 1500 ) 1501 var ts2URL string 1502 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1503 want := Header{ 1504 "User-Agent": []string{ua}, 1505 "X-Foo": []string{xfoo}, 1506 "Referer": []string{ts2URL}, 1507 "Accept-Encoding": []string{"gzip"}, 1508 } 1509 if !reflect.DeepEqual(r.Header, want) { 1510 t.Errorf("Request.Header = %#v; want %#v", r.Header, want) 1511 } 1512 if t.Failed() { 1513 w.Header().Set("Result", "got errors") 1514 } else { 1515 w.Header().Set("Result", "ok") 1516 } 1517 })) 1518 defer ts1.Close() 1519 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1520 Redirect(w, r, ts1.URL, StatusFound) 1521 })) 1522 defer ts2.Close() 1523 ts2URL = ts2.URL 1524 1525 c := ts1.Client() 1526 c.CheckRedirect = func(r *Request, via []*Request) error { 1527 want := Header{ 1528 "User-Agent": []string{ua}, 1529 "X-Foo": []string{xfoo}, 1530 "Referer": []string{ts2URL}, 1531 } 1532 if !reflect.DeepEqual(r.Header, want) { 1533 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want) 1534 } 1535 return nil 1536 } 1537 1538 req, _ := NewRequest("GET", ts2.URL, nil) 1539 req.Header.Add("User-Agent", ua) 1540 req.Header.Add("X-Foo", xfoo) 1541 req.Header.Add("Cookie", "foo=bar") 1542 req.Header.Add("Authorization", "secretpassword") 1543 res, err := c.Do(req) 1544 if err != nil { 1545 t.Fatal(err) 1546 } 1547 defer res.Body.Close() 1548 if res.StatusCode != 200 { 1549 t.Fatal(res.Status) 1550 } 1551 if got := res.Header.Get("Result"); got != "ok" { 1552 t.Errorf("result = %q; want ok", got) 1553 } 1554 } 1555 1556 // Issue 22233: copy host when Client follows a relative redirect. 1557 func TestClientCopyHostOnRedirect(t *testing.T) { 1558 // Virtual hostname: should not receive any request. 1559 virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1560 t.Errorf("Virtual host received request %v", r.URL) 1561 w.WriteHeader(403) 1562 io.WriteString(w, "should not see this response") 1563 })) 1564 defer virtual.Close() 1565 virtualHost := strings.TrimPrefix(virtual.URL, "http://") 1566 t.Logf("Virtual host is %v", virtualHost) 1567 1568 // Actual hostname: should not receive any request. 1569 const wantBody = "response body" 1570 var tsURL string 1571 var tsHost string 1572 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1573 switch r.URL.Path { 1574 case "/": 1575 // Relative redirect. 1576 if r.Host != virtualHost { 1577 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost) 1578 w.WriteHeader(404) 1579 return 1580 } 1581 w.Header().Set("Location", "/hop") 1582 w.WriteHeader(302) 1583 case "/hop": 1584 // Absolute redirect. 1585 if r.Host != virtualHost { 1586 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost) 1587 w.WriteHeader(404) 1588 return 1589 } 1590 w.Header().Set("Location", tsURL+"/final") 1591 w.WriteHeader(302) 1592 case "/final": 1593 if r.Host != tsHost { 1594 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost) 1595 w.WriteHeader(404) 1596 return 1597 } 1598 w.WriteHeader(200) 1599 io.WriteString(w, wantBody) 1600 default: 1601 t.Errorf("Serving unexpected path %q", r.URL.Path) 1602 w.WriteHeader(404) 1603 } 1604 })) 1605 defer ts.Close() 1606 tsURL = ts.URL 1607 tsHost = strings.TrimPrefix(ts.URL, "http://") 1608 t.Logf("Server host is %v", tsHost) 1609 1610 c := ts.Client() 1611 req, _ := NewRequest("GET", ts.URL, nil) 1612 req.Host = virtualHost 1613 resp, err := c.Do(req) 1614 if err != nil { 1615 t.Fatal(err) 1616 } 1617 defer resp.Body.Close() 1618 if resp.StatusCode != 200 { 1619 t.Fatal(resp.Status) 1620 } 1621 if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody { 1622 t.Errorf("body = %q; want %q", got, wantBody) 1623 } 1624 } 1625 1626 // Issue 17494: cookies should be altered when Client follows redirects. 1627 func TestClientAltersCookiesOnRedirect(t *testing.T) { 1628 cookieMap := func(cs []*Cookie) map[string][]string { 1629 m := make(map[string][]string) 1630 for _, c := range cs { 1631 m[c.Name] = append(m[c.Name], c.Value) 1632 } 1633 return m 1634 } 1635 1636 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1637 var want map[string][]string 1638 got := cookieMap(r.Cookies()) 1639 1640 c, _ := r.Cookie("Cycle") 1641 switch c.Value { 1642 case "0": 1643 want = map[string][]string{ 1644 "Cookie1": {"OldValue1a", "OldValue1b"}, 1645 "Cookie2": {"OldValue2"}, 1646 "Cookie3": {"OldValue3a", "OldValue3b"}, 1647 "Cookie4": {"OldValue4"}, 1648 "Cycle": {"0"}, 1649 } 1650 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"}) 1651 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header 1652 Redirect(w, r, "/", StatusFound) 1653 case "1": 1654 want = map[string][]string{ 1655 "Cookie1": {"OldValue1a", "OldValue1b"}, 1656 "Cookie3": {"OldValue3a", "OldValue3b"}, 1657 "Cookie4": {"OldValue4"}, 1658 "Cycle": {"1"}, 1659 } 1660 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"}) 1661 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header 1662 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar 1663 Redirect(w, r, "/", StatusFound) 1664 case "2": 1665 want = map[string][]string{ 1666 "Cookie1": {"OldValue1a", "OldValue1b"}, 1667 "Cookie3": {"NewValue3"}, 1668 "Cookie4": {"NewValue4"}, 1669 "Cycle": {"2"}, 1670 } 1671 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"}) 1672 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar 1673 Redirect(w, r, "/", StatusFound) 1674 case "3": 1675 want = map[string][]string{ 1676 "Cookie1": {"OldValue1a", "OldValue1b"}, 1677 "Cookie3": {"NewValue3"}, 1678 "Cookie4": {"NewValue4"}, 1679 "Cookie5": {"NewValue5"}, 1680 "Cycle": {"3"}, 1681 } 1682 // Don't redirect to ensure the loop ends. 1683 default: 1684 t.Errorf("unexpected redirect cycle") 1685 return 1686 } 1687 1688 if !reflect.DeepEqual(got, want) { 1689 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want) 1690 } 1691 })) 1692 defer ts.Close() 1693 1694 jar, _ := cookiejar.New(nil) 1695 c := ts.Client() 1696 c.Jar = jar 1697 1698 u, _ := url.Parse(ts.URL) 1699 req, _ := NewRequest("GET", ts.URL, nil) 1700 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"}) 1701 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"}) 1702 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"}) 1703 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"}) 1704 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"}) 1705 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}}) 1706 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}}) 1707 res, err := c.Do(req) 1708 if err != nil { 1709 t.Fatal(err) 1710 } 1711 defer res.Body.Close() 1712 if res.StatusCode != 200 { 1713 t.Fatal(res.Status) 1714 } 1715 } 1716 1717 // Part of Issue 4800 1718 func TestShouldCopyHeaderOnRedirect(t *testing.T) { 1719 tests := []struct { 1720 header string 1721 initialURL string 1722 destURL string 1723 want bool 1724 }{ 1725 {"User-Agent", "http://foo.com/", "http://bar.com/", true}, 1726 {"X-Foo", "http://foo.com/", "http://bar.com/", true}, 1727 1728 // Sensitive headers: 1729 {"cookie", "http://foo.com/", "http://bar.com/", false}, 1730 {"cookie2", "http://foo.com/", "http://bar.com/", false}, 1731 {"authorization", "http://foo.com/", "http://bar.com/", false}, 1732 {"www-authenticate", "http://foo.com/", "http://bar.com/", false}, 1733 1734 // But subdomains should work: 1735 {"www-authenticate", "http://foo.com/", "http://foo.com/", true}, 1736 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true}, 1737 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false}, 1738 {"www-authenticate", "http://foo.com/", "https://foo.com/", false}, 1739 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true}, 1740 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true}, 1741 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true}, 1742 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true}, 1743 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false}, 1744 } 1745 for i, tt := range tests { 1746 u0, err := url.Parse(tt.initialURL) 1747 if err != nil { 1748 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err) 1749 continue 1750 } 1751 u1, err := url.Parse(tt.destURL) 1752 if err != nil { 1753 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err) 1754 continue 1755 } 1756 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1) 1757 if got != tt.want { 1758 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v", 1759 i, tt.header, tt.initialURL, tt.destURL, got, tt.want) 1760 } 1761 } 1762 } 1763 1764 func TestClientRedirectTypes(t *testing.T) { 1765 setParallel(t) 1766 defer afterTest(t) 1767 1768 tests := [...]struct { 1769 method string 1770 serverStatus int 1771 wantMethod string // desired subsequent client method 1772 }{ 1773 0: {method: "POST", serverStatus: 301, wantMethod: "GET"}, 1774 1: {method: "POST", serverStatus: 302, wantMethod: "GET"}, 1775 2: {method: "POST", serverStatus: 303, wantMethod: "GET"}, 1776 3: {method: "POST", serverStatus: 307, wantMethod: "POST"}, 1777 4: {method: "POST", serverStatus: 308, wantMethod: "POST"}, 1778 1779 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"}, 1780 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"}, 1781 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"}, 1782 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"}, 1783 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"}, 1784 1785 10: {method: "GET", serverStatus: 301, wantMethod: "GET"}, 1786 11: {method: "GET", serverStatus: 302, wantMethod: "GET"}, 1787 12: {method: "GET", serverStatus: 303, wantMethod: "GET"}, 1788 13: {method: "GET", serverStatus: 307, wantMethod: "GET"}, 1789 14: {method: "GET", serverStatus: 308, wantMethod: "GET"}, 1790 1791 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"}, 1792 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"}, 1793 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"}, 1794 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"}, 1795 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"}, 1796 1797 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"}, 1798 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"}, 1799 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"}, 1800 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"}, 1801 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"}, 1802 1803 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"}, 1804 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"}, 1805 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"}, 1806 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"}, 1807 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"}, 1808 } 1809 1810 handlerc := make(chan HandlerFunc, 1) 1811 1812 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 1813 h := <-handlerc 1814 h(rw, req) 1815 })) 1816 defer ts.Close() 1817 1818 c := ts.Client() 1819 for i, tt := range tests { 1820 handlerc <- func(w ResponseWriter, r *Request) { 1821 w.Header().Set("Location", ts.URL) 1822 w.WriteHeader(tt.serverStatus) 1823 } 1824 1825 req, err := NewRequest(tt.method, ts.URL, nil) 1826 if err != nil { 1827 t.Errorf("#%d: NewRequest: %v", i, err) 1828 continue 1829 } 1830 1831 c.CheckRedirect = func(req *Request, via []*Request) error { 1832 if got, want := req.Method, tt.wantMethod; got != want { 1833 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want) 1834 } 1835 handlerc <- func(rw ResponseWriter, req *Request) { 1836 // TODO: Check that the body is valid when we do 307 and 308 support 1837 } 1838 return nil 1839 } 1840 1841 res, err := c.Do(req) 1842 if err != nil { 1843 t.Errorf("#%d: Response: %v", i, err) 1844 continue 1845 } 1846 1847 res.Body.Close() 1848 } 1849 } 1850 1851 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError. 1852 // Its Read returns readErr and increments *readCalls atomically. 1853 // Its Close returns nil and increments *closeCalls atomically. 1854 type issue18239Body struct { 1855 readCalls *int32 1856 closeCalls *int32 1857 readErr error 1858 } 1859 1860 func (b issue18239Body) Read([]byte) (int, error) { 1861 atomic.AddInt32(b.readCalls, 1) 1862 return 0, b.readErr 1863 } 1864 1865 func (b issue18239Body) Close() error { 1866 atomic.AddInt32(b.closeCalls, 1) 1867 return nil 1868 } 1869 1870 // Issue 18239: make sure the Transport doesn't retry requests with bodies 1871 // if Request.GetBody is not defined. 1872 func TestTransportBodyReadError(t *testing.T) { 1873 setParallel(t) 1874 defer afterTest(t) 1875 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1876 if r.URL.Path == "/ping" { 1877 return 1878 } 1879 buf := make([]byte, 1) 1880 n, err := r.Body.Read(buf) 1881 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err)) 1882 })) 1883 defer ts.Close() 1884 c := ts.Client() 1885 tr := c.Transport.(*Transport) 1886 1887 // Do one initial successful request to create an idle TCP connection 1888 // for the subsequent request to reuse. (The Transport only retries 1889 // requests on reused connections.) 1890 res, err := c.Get(ts.URL + "/ping") 1891 if err != nil { 1892 t.Fatal(err) 1893 } 1894 res.Body.Close() 1895 1896 var readCallsAtomic int32 1897 var closeCallsAtomic int32 // atomic 1898 someErr := errors.New("some body read error") 1899 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr} 1900 1901 req, err := NewRequest("POST", ts.URL, body) 1902 if err != nil { 1903 t.Fatal(err) 1904 } 1905 req = req.WithT(t) 1906 _, err = tr.RoundTrip(req) 1907 if err != someErr { 1908 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr) 1909 } 1910 1911 // And verify that our Body wasn't used multiple times, which 1912 // would indicate retries. (as it buggily was during part of 1913 // Go 1.8's dev cycle) 1914 readCalls := atomic.LoadInt32(&readCallsAtomic) 1915 closeCalls := atomic.LoadInt32(&closeCallsAtomic) 1916 if readCalls != 1 { 1917 t.Errorf("read calls = %d; want 1", readCalls) 1918 } 1919 if closeCalls != 1 { 1920 t.Errorf("close calls = %d; want 1", closeCalls) 1921 } 1922 } 1923 1924 type roundTripperWithoutCloseIdle struct{} 1925 1926 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") } 1927 1928 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func 1929 1930 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") } 1931 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() } 1932 1933 func TestClientCloseIdleConnections(t *testing.T) { 1934 c := &Client{Transport: roundTripperWithoutCloseIdle{}} 1935 c.CloseIdleConnections() // verify we don't crash at least 1936 1937 closed := false 1938 var tr RoundTripper = roundTripperWithCloseIdle(func() { 1939 closed = true 1940 }) 1941 c = &Client{Transport: tr} 1942 c.CloseIdleConnections() 1943 if !closed { 1944 t.Error("not closed") 1945 } 1946 } 1947 1948 func TestClientPropagatesTimeoutToContext(t *testing.T) { 1949 errDial := errors.New("not actually dialing") 1950 c := &Client{ 1951 Timeout: 5 * time.Second, 1952 Transport: &Transport{ 1953 DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) { 1954 deadline, ok := ctx.Deadline() 1955 if !ok { 1956 t.Error("no deadline") 1957 } else { 1958 t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10)) 1959 } 1960 return nil, errDial 1961 }, 1962 }, 1963 } 1964 c.Get("https://example.tld/") 1965 } 1966 1967 func TestClientDoCanceledVsTimeout_h1(t *testing.T) { 1968 testClientDoCanceledVsTimeout(t, h1Mode) 1969 } 1970 1971 func TestClientDoCanceledVsTimeout_h2(t *testing.T) { 1972 testClientDoCanceledVsTimeout(t, h2Mode) 1973 } 1974 1975 // Issue 33545: lock-in the behavior promised by Client.Do's 1976 // docs about request cancellation vs timing out. 1977 func testClientDoCanceledVsTimeout(t *testing.T, h2 bool) { 1978 defer afterTest(t) 1979 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1980 w.Write([]byte("Hello, World!")) 1981 })) 1982 defer cst.close() 1983 1984 cases := []string{"timeout", "canceled"} 1985 1986 for _, name := range cases { 1987 t.Run(name, func(t *testing.T) { 1988 var ctx context.Context 1989 var cancel func() 1990 if name == "timeout" { 1991 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond) 1992 } else { 1993 ctx, cancel = context.WithCancel(context.Background()) 1994 cancel() 1995 } 1996 defer cancel() 1997 1998 req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil) 1999 _, err := cst.c.Do(req) 2000 if err == nil { 2001 t.Fatal("Unexpectedly got a nil error") 2002 } 2003 2004 ue := err.(*url.Error) 2005 2006 var wantIsTimeout bool 2007 var wantErr error = context.Canceled 2008 if name == "timeout" { 2009 wantErr = context.DeadlineExceeded 2010 wantIsTimeout = true 2011 } 2012 if g, w := ue.Timeout(), wantIsTimeout; g != w { 2013 t.Fatalf("url.Timeout() = %t, want %t", g, w) 2014 } 2015 if g, w := ue.Err, wantErr; g != w { 2016 t.Errorf("url.Error.Err = %v; want %v", g, w) 2017 } 2018 }) 2019 } 2020 } 2021 2022 type nilBodyRoundTripper struct{} 2023 2024 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) { 2025 return &Response{ 2026 StatusCode: StatusOK, 2027 Status: StatusText(StatusOK), 2028 Body: nil, 2029 Request: req, 2030 }, nil 2031 } 2032 2033 func TestClientPopulatesNilResponseBody(t *testing.T) { 2034 c := &Client{Transport: nilBodyRoundTripper{}} 2035 2036 resp, err := c.Get("http://localhost/anything") 2037 if err != nil { 2038 t.Fatalf("Client.Get rejected Response with nil Body: %v", err) 2039 } 2040 2041 if resp.Body == nil { 2042 t.Fatalf("Client failed to provide a non-nil Body as documented") 2043 } 2044 defer func() { 2045 if err := resp.Body.Close(); err != nil { 2046 t.Fatalf("error from Close on substitute Response.Body: %v", err) 2047 } 2048 }() 2049 2050 if b, err := io.ReadAll(resp.Body); err != nil { 2051 t.Errorf("read error from substitute Response.Body: %v", err) 2052 } else if len(b) != 0 { 2053 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b) 2054 } 2055 } 2056 2057 // Issue 40382: Client calls Close multiple times on Request.Body. 2058 func TestClientCallsCloseOnlyOnce(t *testing.T) { 2059 setParallel(t) 2060 defer afterTest(t) 2061 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) { 2062 w.WriteHeader(StatusNoContent) 2063 })) 2064 defer cst.close() 2065 2066 // Issue occurred non-deterministically: needed to occur after a successful 2067 // write (into TCP buffer) but before end of body. 2068 for i := 0; i < 50 && !t.Failed(); i++ { 2069 body := &issue40382Body{t: t, n: 300000} 2070 req, err := NewRequest(MethodPost, cst.ts.URL, body) 2071 if err != nil { 2072 t.Fatal(err) 2073 } 2074 resp, err := cst.tr.RoundTrip(req) 2075 if err != nil { 2076 t.Fatal(err) 2077 } 2078 resp.Body.Close() 2079 } 2080 } 2081 2082 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce. 2083 // Its Read reads n bytes before returning io.EOF. 2084 // Its Close returns nil but fails the test if called more than once. 2085 type issue40382Body struct { 2086 t *testing.T 2087 n int 2088 closeCallsAtomic int32 2089 } 2090 2091 func (b *issue40382Body) Read(p []byte) (int, error) { 2092 switch { 2093 case b.n == 0: 2094 return 0, io.EOF 2095 case b.n < len(p): 2096 p = p[:b.n] 2097 fallthrough 2098 default: 2099 for i := range p { 2100 p[i] = 'x' 2101 } 2102 b.n -= len(p) 2103 return len(p), nil 2104 } 2105 } 2106 2107 func (b *issue40382Body) Close() error { 2108 if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 { 2109 b.t.Error("Body closed more than once") 2110 } 2111 return nil 2112 }