github.com/megatontech/mynoteforgo@v0.0.0-20200507084910-5d0c6ea6e890/源码/net/http/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 http_test 8 9 import ( 10 "bytes" 11 "context" 12 "crypto/tls" 13 "encoding/base64" 14 "errors" 15 "fmt" 16 "io" 17 "io/ioutil" 18 "log" 19 "net" 20 . "net/http" 21 "net/http/cookiejar" 22 "net/http/httptest" 23 "net/url" 24 "reflect" 25 "strconv" 26 "strings" 27 "sync" 28 "sync/atomic" 29 "testing" 30 "time" 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 ioutil.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 := ioutil.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, _ := NewRequest("GET", ts.URL, nil) 321 req = req.WithContext(ctx) 322 _, err := c.Do(req) 323 ue, ok := err.(*url.Error) 324 if !ok { 325 t.Fatalf("got error %T; want *url.Error", err) 326 } 327 if ue.Err != context.Canceled { 328 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled) 329 } 330 } 331 332 type redirectTest struct { 333 suffix string 334 want int // response code 335 redirectBody string 336 } 337 338 func TestPostRedirects(t *testing.T) { 339 postRedirectTests := []redirectTest{ 340 {"/", 200, "first"}, 341 {"/?code=301&next=302", 200, "c301"}, 342 {"/?code=302&next=302", 200, "c302"}, 343 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348 344 {"/?code=304", 304, "c304"}, 345 {"/?code=305", 305, "c305"}, 346 {"/?code=307&next=303,308,302", 200, "c307"}, 347 {"/?code=308&next=302,301", 200, "c308"}, 348 {"/?code=404", 404, "c404"}, 349 } 350 351 wantSegments := []string{ 352 `POST / "first"`, 353 `POST /?code=301&next=302 "c301"`, 354 `GET /?code=302 ""`, 355 `GET / ""`, 356 `POST /?code=302&next=302 "c302"`, 357 `GET /?code=302 ""`, 358 `GET / ""`, 359 `POST /?code=303&next=301 "c303wc301"`, 360 `GET /?code=301 ""`, 361 `GET / ""`, 362 `POST /?code=304 "c304"`, 363 `POST /?code=305 "c305"`, 364 `POST /?code=307&next=303,308,302 "c307"`, 365 `POST /?code=303&next=308,302 "c307"`, 366 `GET /?code=308&next=302 ""`, 367 `GET /?code=302 "c307"`, 368 `GET / ""`, 369 `POST /?code=308&next=302,301 "c308"`, 370 `POST /?code=302&next=301 "c308"`, 371 `GET /?code=301 ""`, 372 `GET / ""`, 373 `POST /?code=404 "c404"`, 374 } 375 want := strings.Join(wantSegments, "\n") 376 testRedirectsByMethod(t, "POST", postRedirectTests, want) 377 } 378 379 func TestDeleteRedirects(t *testing.T) { 380 deleteRedirectTests := []redirectTest{ 381 {"/", 200, "first"}, 382 {"/?code=301&next=302,308", 200, "c301"}, 383 {"/?code=302&next=302", 200, "c302"}, 384 {"/?code=303", 200, "c303"}, 385 {"/?code=307&next=301,308,303,302,304", 304, "c307"}, 386 {"/?code=308&next=307", 200, "c308"}, 387 {"/?code=404", 404, "c404"}, 388 } 389 390 wantSegments := []string{ 391 `DELETE / "first"`, 392 `DELETE /?code=301&next=302,308 "c301"`, 393 `GET /?code=302&next=308 ""`, 394 `GET /?code=308 ""`, 395 `GET / "c301"`, 396 `DELETE /?code=302&next=302 "c302"`, 397 `GET /?code=302 ""`, 398 `GET / ""`, 399 `DELETE /?code=303 "c303"`, 400 `GET / ""`, 401 `DELETE /?code=307&next=301,308,303,302,304 "c307"`, 402 `DELETE /?code=301&next=308,303,302,304 "c307"`, 403 `GET /?code=308&next=303,302,304 ""`, 404 `GET /?code=303&next=302,304 "c307"`, 405 `GET /?code=302&next=304 ""`, 406 `GET /?code=304 ""`, 407 `DELETE /?code=308&next=307 "c308"`, 408 `DELETE /?code=307 "c308"`, 409 `DELETE / "c308"`, 410 `DELETE /?code=404 "c404"`, 411 } 412 want := strings.Join(wantSegments, "\n") 413 testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want) 414 } 415 416 func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) { 417 defer afterTest(t) 418 var log struct { 419 sync.Mutex 420 bytes.Buffer 421 } 422 var ts *httptest.Server 423 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 424 log.Lock() 425 slurp, _ := ioutil.ReadAll(r.Body) 426 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp) 427 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") { 428 fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl) 429 } 430 log.WriteByte('\n') 431 log.Unlock() 432 urlQuery := r.URL.Query() 433 if v := urlQuery.Get("code"); v != "" { 434 location := ts.URL 435 if final := urlQuery.Get("next"); final != "" { 436 splits := strings.Split(final, ",") 437 first, rest := splits[0], splits[1:] 438 location = fmt.Sprintf("%s?code=%s", location, first) 439 if len(rest) > 0 { 440 location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ",")) 441 } 442 } 443 code, _ := strconv.Atoi(v) 444 if code/100 == 3 { 445 w.Header().Set("Location", location) 446 } 447 w.WriteHeader(code) 448 } 449 })) 450 defer ts.Close() 451 452 c := ts.Client() 453 for _, tt := range table { 454 content := tt.redirectBody 455 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content)) 456 req.GetBody = func() (io.ReadCloser, error) { return ioutil.NopCloser(strings.NewReader(content)), nil } 457 res, err := c.Do(req) 458 459 if err != nil { 460 t.Fatal(err) 461 } 462 if res.StatusCode != tt.want { 463 t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want) 464 } 465 } 466 log.Lock() 467 got := log.String() 468 log.Unlock() 469 470 got = strings.TrimSpace(got) 471 want = strings.TrimSpace(want) 472 473 if got != want { 474 got, want, lines := removeCommonLines(got, want) 475 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want) 476 } 477 } 478 479 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) { 480 for { 481 nl := strings.IndexByte(a, '\n') 482 if nl < 0 { 483 return a, b, commonLines 484 } 485 line := a[:nl+1] 486 if !strings.HasPrefix(b, line) { 487 return a, b, commonLines 488 } 489 commonLines++ 490 a = a[len(line):] 491 b = b[len(line):] 492 } 493 } 494 495 func TestClientRedirectUseResponse(t *testing.T) { 496 setParallel(t) 497 defer afterTest(t) 498 const body = "Hello, world." 499 var ts *httptest.Server 500 ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 501 if strings.Contains(r.URL.Path, "/other") { 502 io.WriteString(w, "wrong body") 503 } else { 504 w.Header().Set("Location", ts.URL+"/other") 505 w.WriteHeader(StatusFound) 506 io.WriteString(w, body) 507 } 508 })) 509 defer ts.Close() 510 511 c := ts.Client() 512 c.CheckRedirect = func(req *Request, via []*Request) error { 513 if req.Response == nil { 514 t.Error("expected non-nil Request.Response") 515 } 516 return ErrUseLastResponse 517 } 518 res, err := c.Get(ts.URL) 519 if err != nil { 520 t.Fatal(err) 521 } 522 if res.StatusCode != StatusFound { 523 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound) 524 } 525 defer res.Body.Close() 526 slurp, err := ioutil.ReadAll(res.Body) 527 if err != nil { 528 t.Fatal(err) 529 } 530 if string(slurp) != body { 531 t.Errorf("body = %q; want %q", slurp, body) 532 } 533 } 534 535 // Issue 17773: don't follow a 308 (or 307) if the response doesn't 536 // have a Location header. 537 func TestClientRedirect308NoLocation(t *testing.T) { 538 setParallel(t) 539 defer afterTest(t) 540 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 541 w.Header().Set("Foo", "Bar") 542 w.WriteHeader(308) 543 })) 544 defer ts.Close() 545 c := ts.Client() 546 res, err := c.Get(ts.URL) 547 if err != nil { 548 t.Fatal(err) 549 } 550 res.Body.Close() 551 if res.StatusCode != 308 { 552 t.Errorf("status = %d; want %d", res.StatusCode, 308) 553 } 554 if got := res.Header.Get("Foo"); got != "Bar" { 555 t.Errorf("Foo header = %q; want Bar", got) 556 } 557 } 558 559 // Don't follow a 307/308 if we can't resent the request body. 560 func TestClientRedirect308NoGetBody(t *testing.T) { 561 setParallel(t) 562 defer afterTest(t) 563 const fakeURL = "https://localhost:1234/" // won't be hit 564 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 565 w.Header().Set("Location", fakeURL) 566 w.WriteHeader(308) 567 })) 568 defer ts.Close() 569 req, err := NewRequest("POST", ts.URL, strings.NewReader("some body")) 570 if err != nil { 571 t.Fatal(err) 572 } 573 c := ts.Client() 574 req.GetBody = nil // so it can't rewind. 575 res, err := c.Do(req) 576 if err != nil { 577 t.Fatal(err) 578 } 579 res.Body.Close() 580 if res.StatusCode != 308 { 581 t.Errorf("status = %d; want %d", res.StatusCode, 308) 582 } 583 if got := res.Header.Get("Location"); got != fakeURL { 584 t.Errorf("Location header = %q; want %q", got, fakeURL) 585 } 586 } 587 588 var expectedCookies = []*Cookie{ 589 {Name: "ChocolateChip", Value: "tasty"}, 590 {Name: "First", Value: "Hit"}, 591 {Name: "Second", Value: "Hit"}, 592 } 593 594 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) { 595 for _, cookie := range r.Cookies() { 596 SetCookie(w, cookie) 597 } 598 if r.URL.Path == "/" { 599 SetCookie(w, expectedCookies[1]) 600 Redirect(w, r, "/second", StatusMovedPermanently) 601 } else { 602 SetCookie(w, expectedCookies[2]) 603 w.Write([]byte("hello")) 604 } 605 }) 606 607 func TestClientSendsCookieFromJar(t *testing.T) { 608 defer afterTest(t) 609 tr := &recordingTransport{} 610 client := &Client{Transport: tr} 611 client.Jar = &TestJar{perURL: make(map[string][]*Cookie)} 612 us := "http://dummy.faketld/" 613 u, _ := url.Parse(us) 614 client.Jar.SetCookies(u, expectedCookies) 615 616 client.Get(us) // Note: doesn't hit network 617 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 618 619 client.Head(us) // Note: doesn't hit network 620 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 621 622 client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network 623 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 624 625 client.PostForm(us, url.Values{}) // Note: doesn't hit network 626 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 627 628 req, _ := NewRequest("GET", us, nil) 629 client.Do(req) // Note: doesn't hit network 630 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 631 632 req, _ = NewRequest("POST", us, nil) 633 client.Do(req) // Note: doesn't hit network 634 matchReturnedCookies(t, expectedCookies, tr.req.Cookies()) 635 } 636 637 // Just enough correctness for our redirect tests. Uses the URL.Host as the 638 // scope of all cookies. 639 type TestJar struct { 640 m sync.Mutex 641 perURL map[string][]*Cookie 642 } 643 644 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) { 645 j.m.Lock() 646 defer j.m.Unlock() 647 if j.perURL == nil { 648 j.perURL = make(map[string][]*Cookie) 649 } 650 j.perURL[u.Host] = cookies 651 } 652 653 func (j *TestJar) Cookies(u *url.URL) []*Cookie { 654 j.m.Lock() 655 defer j.m.Unlock() 656 return j.perURL[u.Host] 657 } 658 659 func TestRedirectCookiesJar(t *testing.T) { 660 setParallel(t) 661 defer afterTest(t) 662 var ts *httptest.Server 663 ts = httptest.NewServer(echoCookiesRedirectHandler) 664 defer ts.Close() 665 c := ts.Client() 666 c.Jar = new(TestJar) 667 u, _ := url.Parse(ts.URL) 668 c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]}) 669 resp, err := c.Get(ts.URL) 670 if err != nil { 671 t.Fatalf("Get: %v", err) 672 } 673 resp.Body.Close() 674 matchReturnedCookies(t, expectedCookies, resp.Cookies()) 675 } 676 677 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) { 678 if len(given) != len(expected) { 679 t.Logf("Received cookies: %v", given) 680 t.Errorf("Expected %d cookies, got %d", len(expected), len(given)) 681 } 682 for _, ec := range expected { 683 foundC := false 684 for _, c := range given { 685 if ec.Name == c.Name && ec.Value == c.Value { 686 foundC = true 687 break 688 } 689 } 690 if !foundC { 691 t.Errorf("Missing cookie %v", ec) 692 } 693 } 694 } 695 696 func TestJarCalls(t *testing.T) { 697 defer afterTest(t) 698 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 699 pathSuffix := r.RequestURI[1:] 700 if r.RequestURI == "/nosetcookie" { 701 return // don't set cookies for this path 702 } 703 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix}) 704 if r.RequestURI == "/" { 705 Redirect(w, r, "http://secondhost.fake/secondpath", 302) 706 } 707 })) 708 defer ts.Close() 709 jar := new(RecordingJar) 710 c := ts.Client() 711 c.Jar = jar 712 c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) { 713 return net.Dial("tcp", ts.Listener.Addr().String()) 714 } 715 _, err := c.Get("http://firsthost.fake/") 716 if err != nil { 717 t.Fatal(err) 718 } 719 _, err = c.Get("http://firsthost.fake/nosetcookie") 720 if err != nil { 721 t.Fatal(err) 722 } 723 got := jar.log.String() 724 want := `Cookies("http://firsthost.fake/") 725 SetCookie("http://firsthost.fake/", [name=val]) 726 Cookies("http://secondhost.fake/secondpath") 727 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath]) 728 Cookies("http://firsthost.fake/nosetcookie") 729 ` 730 if got != want { 731 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want) 732 } 733 } 734 735 // RecordingJar keeps a log of calls made to it, without 736 // tracking any cookies. 737 type RecordingJar struct { 738 mu sync.Mutex 739 log bytes.Buffer 740 } 741 742 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) { 743 j.logf("SetCookie(%q, %v)\n", u, cookies) 744 } 745 746 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie { 747 j.logf("Cookies(%q)\n", u) 748 return nil 749 } 750 751 func (j *RecordingJar) logf(format string, args ...interface{}) { 752 j.mu.Lock() 753 defer j.mu.Unlock() 754 fmt.Fprintf(&j.log, format, args...) 755 } 756 757 func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) } 758 func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) } 759 760 func testStreamingGet(t *testing.T, h2 bool) { 761 defer afterTest(t) 762 say := make(chan string) 763 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 764 w.(Flusher).Flush() 765 for str := range say { 766 w.Write([]byte(str)) 767 w.(Flusher).Flush() 768 } 769 })) 770 defer cst.close() 771 772 c := cst.c 773 res, err := c.Get(cst.ts.URL) 774 if err != nil { 775 t.Fatal(err) 776 } 777 var buf [10]byte 778 for _, str := range []string{"i", "am", "also", "known", "as", "comet"} { 779 say <- str 780 n, err := io.ReadFull(res.Body, buf[0:len(str)]) 781 if err != nil { 782 t.Fatalf("ReadFull on %q: %v", str, err) 783 } 784 if n != len(str) { 785 t.Fatalf("Receiving %q, only read %d bytes", str, n) 786 } 787 got := string(buf[0:n]) 788 if got != str { 789 t.Fatalf("Expected %q, got %q", str, got) 790 } 791 } 792 close(say) 793 _, err = io.ReadFull(res.Body, buf[0:1]) 794 if err != io.EOF { 795 t.Fatalf("at end expected EOF, got %v", err) 796 } 797 } 798 799 type writeCountingConn struct { 800 net.Conn 801 count *int 802 } 803 804 func (c *writeCountingConn) Write(p []byte) (int, error) { 805 *c.count++ 806 return c.Conn.Write(p) 807 } 808 809 // TestClientWrites verifies that client requests are buffered and we 810 // don't send a TCP packet per line of the http request + body. 811 func TestClientWrites(t *testing.T) { 812 defer afterTest(t) 813 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 814 })) 815 defer ts.Close() 816 817 writes := 0 818 dialer := func(netz string, addr string) (net.Conn, error) { 819 c, err := net.Dial(netz, addr) 820 if err == nil { 821 c = &writeCountingConn{c, &writes} 822 } 823 return c, err 824 } 825 c := ts.Client() 826 c.Transport.(*Transport).Dial = dialer 827 828 _, err := c.Get(ts.URL) 829 if err != nil { 830 t.Fatal(err) 831 } 832 if writes != 1 { 833 t.Errorf("Get request did %d Write calls, want 1", writes) 834 } 835 836 writes = 0 837 _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}}) 838 if err != nil { 839 t.Fatal(err) 840 } 841 if writes != 1 { 842 t.Errorf("Post request did %d Write calls, want 1", writes) 843 } 844 } 845 846 func TestClientInsecureTransport(t *testing.T) { 847 setParallel(t) 848 defer afterTest(t) 849 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 850 w.Write([]byte("Hello")) 851 })) 852 errc := make(chanWriter, 10) // but only expecting 1 853 ts.Config.ErrorLog = log.New(errc, "", 0) 854 defer ts.Close() 855 856 // TODO(bradfitz): add tests for skipping hostname checks too? 857 // would require a new cert for testing, and probably 858 // redundant with these tests. 859 c := ts.Client() 860 for _, insecure := range []bool{true, false} { 861 c.Transport.(*Transport).TLSClientConfig = &tls.Config{ 862 InsecureSkipVerify: insecure, 863 } 864 res, err := c.Get(ts.URL) 865 if (err == nil) != insecure { 866 t.Errorf("insecure=%v: got unexpected err=%v", insecure, err) 867 } 868 if res != nil { 869 res.Body.Close() 870 } 871 } 872 873 select { 874 case v := <-errc: 875 if !strings.Contains(v, "TLS handshake error") { 876 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v) 877 } 878 case <-time.After(5 * time.Second): 879 t.Errorf("timeout waiting for logged error") 880 } 881 882 } 883 884 func TestClientErrorWithRequestURI(t *testing.T) { 885 defer afterTest(t) 886 req, _ := NewRequest("GET", "http://localhost:1234/", nil) 887 req.RequestURI = "/this/field/is/illegal/and/should/error/" 888 _, err := DefaultClient.Do(req) 889 if err == nil { 890 t.Fatalf("expected an error") 891 } 892 if !strings.Contains(err.Error(), "RequestURI") { 893 t.Errorf("wanted error mentioning RequestURI; got error: %v", err) 894 } 895 } 896 897 func TestClientWithCorrectTLSServerName(t *testing.T) { 898 defer afterTest(t) 899 900 const serverName = "example.com" 901 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 902 if r.TLS.ServerName != serverName { 903 t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName) 904 } 905 })) 906 defer ts.Close() 907 908 c := ts.Client() 909 c.Transport.(*Transport).TLSClientConfig.ServerName = serverName 910 if _, err := c.Get(ts.URL); err != nil { 911 t.Fatalf("expected successful TLS connection, got error: %v", err) 912 } 913 } 914 915 func TestClientWithIncorrectTLSServerName(t *testing.T) { 916 defer afterTest(t) 917 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 918 defer ts.Close() 919 errc := make(chanWriter, 10) // but only expecting 1 920 ts.Config.ErrorLog = log.New(errc, "", 0) 921 922 c := ts.Client() 923 c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver" 924 _, err := c.Get(ts.URL) 925 if err == nil { 926 t.Fatalf("expected an error") 927 } 928 if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") { 929 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err) 930 } 931 select { 932 case v := <-errc: 933 if !strings.Contains(v, "TLS handshake error") { 934 t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v) 935 } 936 case <-time.After(5 * time.Second): 937 t.Errorf("timeout waiting for logged error") 938 } 939 } 940 941 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName 942 // when not empty. 943 // 944 // tls.Config.ServerName (non-empty, set to "example.com") takes 945 // precedence over "some-other-host.tld" which previously incorrectly 946 // took precedence. We don't actually connect to (or even resolve) 947 // "some-other-host.tld", though, because of the Transport.Dial hook. 948 // 949 // The httptest.Server has a cert with "example.com" as its name. 950 func TestTransportUsesTLSConfigServerName(t *testing.T) { 951 defer afterTest(t) 952 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 953 w.Write([]byte("Hello")) 954 })) 955 defer ts.Close() 956 957 c := ts.Client() 958 tr := c.Transport.(*Transport) 959 tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names 960 tr.Dial = func(netw, addr string) (net.Conn, error) { 961 return net.Dial(netw, ts.Listener.Addr().String()) 962 } 963 res, err := c.Get("https://some-other-host.tld/") 964 if err != nil { 965 t.Fatal(err) 966 } 967 res.Body.Close() 968 } 969 970 func TestResponseSetsTLSConnectionState(t *testing.T) { 971 defer afterTest(t) 972 ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) { 973 w.Write([]byte("Hello")) 974 })) 975 defer ts.Close() 976 977 c := ts.Client() 978 tr := c.Transport.(*Transport) 979 tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA} 980 tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite 981 tr.Dial = func(netw, addr string) (net.Conn, error) { 982 return net.Dial(netw, ts.Listener.Addr().String()) 983 } 984 res, err := c.Get("https://example.com/") 985 if err != nil { 986 t.Fatal(err) 987 } 988 defer res.Body.Close() 989 if res.TLS == nil { 990 t.Fatal("Response didn't set TLS Connection State.") 991 } 992 if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want { 993 t.Errorf("TLS Cipher Suite = %d; want %d", got, want) 994 } 995 } 996 997 // Check that an HTTPS client can interpret a particular TLS error 998 // to determine that the server is speaking HTTP. 999 // See golang.org/issue/11111. 1000 func TestHTTPSClientDetectsHTTPServer(t *testing.T) { 1001 defer afterTest(t) 1002 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {})) 1003 ts.Config.ErrorLog = quietLog 1004 defer ts.Close() 1005 1006 _, err := Get(strings.Replace(ts.URL, "http", "https", 1)) 1007 if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") { 1008 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got) 1009 } 1010 } 1011 1012 // Verify Response.ContentLength is populated. https://golang.org/issue/4126 1013 func TestClientHeadContentLength_h1(t *testing.T) { 1014 testClientHeadContentLength(t, h1Mode) 1015 } 1016 1017 func TestClientHeadContentLength_h2(t *testing.T) { 1018 testClientHeadContentLength(t, h2Mode) 1019 } 1020 1021 func testClientHeadContentLength(t *testing.T, h2 bool) { 1022 defer afterTest(t) 1023 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1024 if v := r.FormValue("cl"); v != "" { 1025 w.Header().Set("Content-Length", v) 1026 } 1027 })) 1028 defer cst.close() 1029 tests := []struct { 1030 suffix string 1031 want int64 1032 }{ 1033 {"/?cl=1234", 1234}, 1034 {"/?cl=0", 0}, 1035 {"", -1}, 1036 } 1037 for _, tt := range tests { 1038 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil) 1039 res, err := cst.c.Do(req) 1040 if err != nil { 1041 t.Fatal(err) 1042 } 1043 if res.ContentLength != tt.want { 1044 t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want) 1045 } 1046 bs, err := ioutil.ReadAll(res.Body) 1047 if err != nil { 1048 t.Fatal(err) 1049 } 1050 if len(bs) != 0 { 1051 t.Errorf("Unexpected content: %q", bs) 1052 } 1053 } 1054 } 1055 1056 func TestEmptyPasswordAuth(t *testing.T) { 1057 setParallel(t) 1058 defer afterTest(t) 1059 gopher := "gopher" 1060 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1061 auth := r.Header.Get("Authorization") 1062 if strings.HasPrefix(auth, "Basic ") { 1063 encoded := auth[6:] 1064 decoded, err := base64.StdEncoding.DecodeString(encoded) 1065 if err != nil { 1066 t.Fatal(err) 1067 } 1068 expected := gopher + ":" 1069 s := string(decoded) 1070 if expected != s { 1071 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected) 1072 } 1073 } else { 1074 t.Errorf("Invalid auth %q", auth) 1075 } 1076 })) 1077 defer ts.Close() 1078 req, err := NewRequest("GET", ts.URL, nil) 1079 if err != nil { 1080 t.Fatal(err) 1081 } 1082 req.URL.User = url.User(gopher) 1083 c := ts.Client() 1084 resp, err := c.Do(req) 1085 if err != nil { 1086 t.Fatal(err) 1087 } 1088 defer resp.Body.Close() 1089 } 1090 1091 func TestBasicAuth(t *testing.T) { 1092 defer afterTest(t) 1093 tr := &recordingTransport{} 1094 client := &Client{Transport: tr} 1095 1096 url := "http://My%20User:My%20Pass@dummy.faketld/" 1097 expected := "My User:My Pass" 1098 client.Get(url) 1099 1100 if tr.req.Method != "GET" { 1101 t.Errorf("got method %q, want %q", tr.req.Method, "GET") 1102 } 1103 if tr.req.URL.String() != url { 1104 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url) 1105 } 1106 if tr.req.Header == nil { 1107 t.Fatalf("expected non-nil request Header") 1108 } 1109 auth := tr.req.Header.Get("Authorization") 1110 if strings.HasPrefix(auth, "Basic ") { 1111 encoded := auth[6:] 1112 decoded, err := base64.StdEncoding.DecodeString(encoded) 1113 if err != nil { 1114 t.Fatal(err) 1115 } 1116 s := string(decoded) 1117 if expected != s { 1118 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected) 1119 } 1120 } else { 1121 t.Errorf("Invalid auth %q", auth) 1122 } 1123 } 1124 1125 func TestBasicAuthHeadersPreserved(t *testing.T) { 1126 defer afterTest(t) 1127 tr := &recordingTransport{} 1128 client := &Client{Transport: tr} 1129 1130 // If Authorization header is provided, username in URL should not override it 1131 url := "http://My%20User@dummy.faketld/" 1132 req, err := NewRequest("GET", url, nil) 1133 if err != nil { 1134 t.Fatal(err) 1135 } 1136 req.SetBasicAuth("My User", "My Pass") 1137 expected := "My User:My Pass" 1138 client.Do(req) 1139 1140 if tr.req.Method != "GET" { 1141 t.Errorf("got method %q, want %q", tr.req.Method, "GET") 1142 } 1143 if tr.req.URL.String() != url { 1144 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url) 1145 } 1146 if tr.req.Header == nil { 1147 t.Fatalf("expected non-nil request Header") 1148 } 1149 auth := tr.req.Header.Get("Authorization") 1150 if strings.HasPrefix(auth, "Basic ") { 1151 encoded := auth[6:] 1152 decoded, err := base64.StdEncoding.DecodeString(encoded) 1153 if err != nil { 1154 t.Fatal(err) 1155 } 1156 s := string(decoded) 1157 if expected != s { 1158 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected) 1159 } 1160 } else { 1161 t.Errorf("Invalid auth %q", auth) 1162 } 1163 1164 } 1165 1166 func TestStripPasswordFromError(t *testing.T) { 1167 client := &Client{Transport: &recordingTransport{}} 1168 testCases := []struct { 1169 desc string 1170 in string 1171 out string 1172 }{ 1173 { 1174 desc: "Strip password from error message", 1175 in: "http://user:password@dummy.faketld/", 1176 out: "Get http://user:***@dummy.faketld/: dummy impl", 1177 }, 1178 { 1179 desc: "Don't Strip password from domain name", 1180 in: "http://user:password@password.faketld/", 1181 out: "Get http://user:***@password.faketld/: dummy impl", 1182 }, 1183 { 1184 desc: "Don't Strip password from path", 1185 in: "http://user:password@dummy.faketld/password", 1186 out: "Get http://user:***@dummy.faketld/password: dummy impl", 1187 }, 1188 } 1189 for _, tC := range testCases { 1190 t.Run(tC.desc, func(t *testing.T) { 1191 _, err := client.Get(tC.in) 1192 if err.Error() != tC.out { 1193 t.Errorf("Unexpected output for %q: expected %q, actual %q", 1194 tC.in, tC.out, err.Error()) 1195 } 1196 }) 1197 } 1198 } 1199 1200 func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) } 1201 func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) } 1202 1203 func testClientTimeout(t *testing.T, h2 bool) { 1204 setParallel(t) 1205 defer afterTest(t) 1206 testDone := make(chan struct{}) // closed in defer below 1207 1208 sawRoot := make(chan bool, 1) 1209 sawSlow := make(chan bool, 1) 1210 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1211 if r.URL.Path == "/" { 1212 sawRoot <- true 1213 Redirect(w, r, "/slow", StatusFound) 1214 return 1215 } 1216 if r.URL.Path == "/slow" { 1217 sawSlow <- true 1218 w.Write([]byte("Hello")) 1219 w.(Flusher).Flush() 1220 <-testDone 1221 return 1222 } 1223 })) 1224 defer cst.close() 1225 defer close(testDone) // before cst.close, to unblock /slow handler 1226 1227 // 200ms should be long enough to get a normal request (the / 1228 // handler), but not so long that it makes the test slow. 1229 const timeout = 200 * time.Millisecond 1230 cst.c.Timeout = timeout 1231 1232 res, err := cst.c.Get(cst.ts.URL) 1233 if err != nil { 1234 if strings.Contains(err.Error(), "Client.Timeout") { 1235 t.Skipf("host too slow to get fast resource in %v", timeout) 1236 } 1237 t.Fatal(err) 1238 } 1239 1240 select { 1241 case <-sawRoot: 1242 // good. 1243 default: 1244 t.Fatal("handler never got / request") 1245 } 1246 1247 select { 1248 case <-sawSlow: 1249 // good. 1250 default: 1251 t.Fatal("handler never got /slow request") 1252 } 1253 1254 errc := make(chan error, 1) 1255 go func() { 1256 _, err := ioutil.ReadAll(res.Body) 1257 errc <- err 1258 res.Body.Close() 1259 }() 1260 1261 const failTime = 5 * time.Second 1262 select { 1263 case err := <-errc: 1264 if err == nil { 1265 t.Fatal("expected error from ReadAll") 1266 } 1267 ne, ok := err.(net.Error) 1268 if !ok { 1269 t.Errorf("error value from ReadAll was %T; expected some net.Error", err) 1270 } else if !ne.Timeout() { 1271 t.Errorf("net.Error.Timeout = false; want true") 1272 } 1273 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") { 1274 t.Errorf("error string = %q; missing timeout substring", got) 1275 } 1276 case <-time.After(failTime): 1277 t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout) 1278 } 1279 } 1280 1281 func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) } 1282 func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) } 1283 1284 // Client.Timeout firing before getting to the body 1285 func testClientTimeout_Headers(t *testing.T, h2 bool) { 1286 setParallel(t) 1287 defer afterTest(t) 1288 donec := make(chan bool, 1) 1289 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1290 <-donec 1291 })) 1292 defer cst.close() 1293 // Note that we use a channel send here and not a close. 1294 // The race detector doesn't know that we're waiting for a timeout 1295 // and thinks that the waitgroup inside httptest.Server is added to concurrently 1296 // with us closing it. If we timed out immediately, we could close the testserver 1297 // before we entered the handler. We're not timing out immediately and there's 1298 // no way we would be done before we entered the handler, but the race detector 1299 // doesn't know this, so synchronize explicitly. 1300 defer func() { donec <- true }() 1301 1302 cst.c.Timeout = 5 * time.Millisecond 1303 res, err := cst.c.Get(cst.ts.URL) 1304 if err == nil { 1305 res.Body.Close() 1306 t.Fatal("got response from Get; expected error") 1307 } 1308 if _, ok := err.(*url.Error); !ok { 1309 t.Fatalf("Got error of type %T; want *url.Error", err) 1310 } 1311 ne, ok := err.(net.Error) 1312 if !ok { 1313 t.Fatalf("Got error of type %T; want some net.Error", err) 1314 } 1315 if !ne.Timeout() { 1316 t.Error("net.Error.Timeout = false; want true") 1317 } 1318 if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") { 1319 t.Errorf("error string = %q; missing timeout substring", got) 1320 } 1321 } 1322 1323 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be 1324 // returned. 1325 func TestClientTimeoutCancel(t *testing.T) { 1326 setParallel(t) 1327 defer afterTest(t) 1328 1329 testDone := make(chan struct{}) 1330 ctx, cancel := context.WithCancel(context.Background()) 1331 1332 cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) { 1333 w.(Flusher).Flush() 1334 <-testDone 1335 })) 1336 defer cst.close() 1337 defer close(testDone) 1338 1339 cst.c.Timeout = 1 * time.Hour 1340 req, _ := NewRequest("GET", cst.ts.URL, nil) 1341 req.Cancel = ctx.Done() 1342 res, err := cst.c.Do(req) 1343 if err != nil { 1344 t.Fatal(err) 1345 } 1346 cancel() 1347 _, err = io.Copy(ioutil.Discard, res.Body) 1348 if err != ExportErrRequestCanceled { 1349 t.Fatalf("error = %v; want errRequestCanceled", err) 1350 } 1351 } 1352 1353 func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) } 1354 func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) } 1355 func testClientRedirectEatsBody(t *testing.T, h2 bool) { 1356 setParallel(t) 1357 defer afterTest(t) 1358 saw := make(chan string, 2) 1359 cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) { 1360 saw <- r.RemoteAddr 1361 if r.URL.Path == "/" { 1362 Redirect(w, r, "/foo", StatusFound) // which includes a body 1363 } 1364 })) 1365 defer cst.close() 1366 1367 res, err := cst.c.Get(cst.ts.URL) 1368 if err != nil { 1369 t.Fatal(err) 1370 } 1371 _, err = ioutil.ReadAll(res.Body) 1372 res.Body.Close() 1373 if err != nil { 1374 t.Fatal(err) 1375 } 1376 1377 var first string 1378 select { 1379 case first = <-saw: 1380 default: 1381 t.Fatal("server didn't see a request") 1382 } 1383 1384 var second string 1385 select { 1386 case second = <-saw: 1387 default: 1388 t.Fatal("server didn't see a second request") 1389 } 1390 1391 if first != second { 1392 t.Fatal("server saw different client ports before & after the redirect") 1393 } 1394 } 1395 1396 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF. 1397 type eofReaderFunc func() 1398 1399 func (f eofReaderFunc) Read(p []byte) (n int, err error) { 1400 f() 1401 return 0, io.EOF 1402 } 1403 1404 func TestReferer(t *testing.T) { 1405 tests := []struct { 1406 lastReq, newReq string // from -> to URLs 1407 want string 1408 }{ 1409 // don't send user: 1410 {"http://gopher@test.com", "http://link.com", "http://test.com"}, 1411 {"https://gopher@test.com", "https://link.com", "https://test.com"}, 1412 1413 // don't send a user and password: 1414 {"http://gopher:go@test.com", "http://link.com", "http://test.com"}, 1415 {"https://gopher:go@test.com", "https://link.com", "https://test.com"}, 1416 1417 // nothing to do: 1418 {"http://test.com", "http://link.com", "http://test.com"}, 1419 {"https://test.com", "https://link.com", "https://test.com"}, 1420 1421 // https to http doesn't send a referer: 1422 {"https://test.com", "http://link.com", ""}, 1423 {"https://gopher:go@test.com", "http://link.com", ""}, 1424 } 1425 for _, tt := range tests { 1426 l, err := url.Parse(tt.lastReq) 1427 if err != nil { 1428 t.Fatal(err) 1429 } 1430 n, err := url.Parse(tt.newReq) 1431 if err != nil { 1432 t.Fatal(err) 1433 } 1434 r := ExportRefererForURL(l, n) 1435 if r != tt.want { 1436 t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want) 1437 } 1438 } 1439 } 1440 1441 // issue15577Tripper returns a Response with a redirect response 1442 // header and doesn't populate its Response.Request field. 1443 type issue15577Tripper struct{} 1444 1445 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) { 1446 resp := &Response{ 1447 StatusCode: 303, 1448 Header: map[string][]string{"Location": {"http://www.example.com/"}}, 1449 Body: ioutil.NopCloser(strings.NewReader("")), 1450 } 1451 return resp, nil 1452 } 1453 1454 // Issue 15577: don't assume the roundtripper's response populates its Request field. 1455 func TestClientRedirectResponseWithoutRequest(t *testing.T) { 1456 c := &Client{ 1457 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") }, 1458 Transport: issue15577Tripper{}, 1459 } 1460 // Check that this doesn't crash: 1461 c.Get("http://dummy.tld") 1462 } 1463 1464 // Issue 4800: copy (some) headers when Client follows a redirect. 1465 func TestClientCopyHeadersOnRedirect(t *testing.T) { 1466 const ( 1467 ua = "some-agent/1.2" 1468 xfoo = "foo-val" 1469 ) 1470 var ts2URL string 1471 ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1472 want := Header{ 1473 "User-Agent": []string{ua}, 1474 "X-Foo": []string{xfoo}, 1475 "Referer": []string{ts2URL}, 1476 "Accept-Encoding": []string{"gzip"}, 1477 } 1478 if !reflect.DeepEqual(r.Header, want) { 1479 t.Errorf("Request.Header = %#v; want %#v", r.Header, want) 1480 } 1481 if t.Failed() { 1482 w.Header().Set("Result", "got errors") 1483 } else { 1484 w.Header().Set("Result", "ok") 1485 } 1486 })) 1487 defer ts1.Close() 1488 ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1489 Redirect(w, r, ts1.URL, StatusFound) 1490 })) 1491 defer ts2.Close() 1492 ts2URL = ts2.URL 1493 1494 c := ts1.Client() 1495 c.CheckRedirect = func(r *Request, via []*Request) error { 1496 want := Header{ 1497 "User-Agent": []string{ua}, 1498 "X-Foo": []string{xfoo}, 1499 "Referer": []string{ts2URL}, 1500 } 1501 if !reflect.DeepEqual(r.Header, want) { 1502 t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want) 1503 } 1504 return nil 1505 } 1506 1507 req, _ := NewRequest("GET", ts2.URL, nil) 1508 req.Header.Add("User-Agent", ua) 1509 req.Header.Add("X-Foo", xfoo) 1510 req.Header.Add("Cookie", "foo=bar") 1511 req.Header.Add("Authorization", "secretpassword") 1512 res, err := c.Do(req) 1513 if err != nil { 1514 t.Fatal(err) 1515 } 1516 defer res.Body.Close() 1517 if res.StatusCode != 200 { 1518 t.Fatal(res.Status) 1519 } 1520 if got := res.Header.Get("Result"); got != "ok" { 1521 t.Errorf("result = %q; want ok", got) 1522 } 1523 } 1524 1525 // Issue 22233: copy host when Client follows a relative redirect. 1526 func TestClientCopyHostOnRedirect(t *testing.T) { 1527 // Virtual hostname: should not receive any request. 1528 virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1529 t.Errorf("Virtual host received request %v", r.URL) 1530 w.WriteHeader(403) 1531 io.WriteString(w, "should not see this response") 1532 })) 1533 defer virtual.Close() 1534 virtualHost := strings.TrimPrefix(virtual.URL, "http://") 1535 t.Logf("Virtual host is %v", virtualHost) 1536 1537 // Actual hostname: should not receive any request. 1538 const wantBody = "response body" 1539 var tsURL string 1540 var tsHost string 1541 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1542 switch r.URL.Path { 1543 case "/": 1544 // Relative redirect. 1545 if r.Host != virtualHost { 1546 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost) 1547 w.WriteHeader(404) 1548 return 1549 } 1550 w.Header().Set("Location", "/hop") 1551 w.WriteHeader(302) 1552 case "/hop": 1553 // Absolute redirect. 1554 if r.Host != virtualHost { 1555 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost) 1556 w.WriteHeader(404) 1557 return 1558 } 1559 w.Header().Set("Location", tsURL+"/final") 1560 w.WriteHeader(302) 1561 case "/final": 1562 if r.Host != tsHost { 1563 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost) 1564 w.WriteHeader(404) 1565 return 1566 } 1567 w.WriteHeader(200) 1568 io.WriteString(w, wantBody) 1569 default: 1570 t.Errorf("Serving unexpected path %q", r.URL.Path) 1571 w.WriteHeader(404) 1572 } 1573 })) 1574 defer ts.Close() 1575 tsURL = ts.URL 1576 tsHost = strings.TrimPrefix(ts.URL, "http://") 1577 t.Logf("Server host is %v", tsHost) 1578 1579 c := ts.Client() 1580 req, _ := NewRequest("GET", ts.URL, nil) 1581 req.Host = virtualHost 1582 resp, err := c.Do(req) 1583 if err != nil { 1584 t.Fatal(err) 1585 } 1586 defer resp.Body.Close() 1587 if resp.StatusCode != 200 { 1588 t.Fatal(resp.Status) 1589 } 1590 if got, err := ioutil.ReadAll(resp.Body); err != nil || string(got) != wantBody { 1591 t.Errorf("body = %q; want %q", got, wantBody) 1592 } 1593 } 1594 1595 // Issue 17494: cookies should be altered when Client follows redirects. 1596 func TestClientAltersCookiesOnRedirect(t *testing.T) { 1597 cookieMap := func(cs []*Cookie) map[string][]string { 1598 m := make(map[string][]string) 1599 for _, c := range cs { 1600 m[c.Name] = append(m[c.Name], c.Value) 1601 } 1602 return m 1603 } 1604 1605 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1606 var want map[string][]string 1607 got := cookieMap(r.Cookies()) 1608 1609 c, _ := r.Cookie("Cycle") 1610 switch c.Value { 1611 case "0": 1612 want = map[string][]string{ 1613 "Cookie1": {"OldValue1a", "OldValue1b"}, 1614 "Cookie2": {"OldValue2"}, 1615 "Cookie3": {"OldValue3a", "OldValue3b"}, 1616 "Cookie4": {"OldValue4"}, 1617 "Cycle": {"0"}, 1618 } 1619 SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"}) 1620 SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header 1621 Redirect(w, r, "/", StatusFound) 1622 case "1": 1623 want = map[string][]string{ 1624 "Cookie1": {"OldValue1a", "OldValue1b"}, 1625 "Cookie3": {"OldValue3a", "OldValue3b"}, 1626 "Cookie4": {"OldValue4"}, 1627 "Cycle": {"1"}, 1628 } 1629 SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"}) 1630 SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header 1631 SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar 1632 Redirect(w, r, "/", StatusFound) 1633 case "2": 1634 want = map[string][]string{ 1635 "Cookie1": {"OldValue1a", "OldValue1b"}, 1636 "Cookie3": {"NewValue3"}, 1637 "Cookie4": {"NewValue4"}, 1638 "Cycle": {"2"}, 1639 } 1640 SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"}) 1641 SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar 1642 Redirect(w, r, "/", StatusFound) 1643 case "3": 1644 want = map[string][]string{ 1645 "Cookie1": {"OldValue1a", "OldValue1b"}, 1646 "Cookie3": {"NewValue3"}, 1647 "Cookie4": {"NewValue4"}, 1648 "Cookie5": {"NewValue5"}, 1649 "Cycle": {"3"}, 1650 } 1651 // Don't redirect to ensure the loop ends. 1652 default: 1653 t.Errorf("unexpected redirect cycle") 1654 return 1655 } 1656 1657 if !reflect.DeepEqual(got, want) { 1658 t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want) 1659 } 1660 })) 1661 defer ts.Close() 1662 1663 jar, _ := cookiejar.New(nil) 1664 c := ts.Client() 1665 c.Jar = jar 1666 1667 u, _ := url.Parse(ts.URL) 1668 req, _ := NewRequest("GET", ts.URL, nil) 1669 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"}) 1670 req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"}) 1671 req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"}) 1672 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"}) 1673 req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"}) 1674 jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}}) 1675 jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}}) 1676 res, err := c.Do(req) 1677 if err != nil { 1678 t.Fatal(err) 1679 } 1680 defer res.Body.Close() 1681 if res.StatusCode != 200 { 1682 t.Fatal(res.Status) 1683 } 1684 } 1685 1686 // Part of Issue 4800 1687 func TestShouldCopyHeaderOnRedirect(t *testing.T) { 1688 tests := []struct { 1689 header string 1690 initialURL string 1691 destURL string 1692 want bool 1693 }{ 1694 {"User-Agent", "http://foo.com/", "http://bar.com/", true}, 1695 {"X-Foo", "http://foo.com/", "http://bar.com/", true}, 1696 1697 // Sensitive headers: 1698 {"cookie", "http://foo.com/", "http://bar.com/", false}, 1699 {"cookie2", "http://foo.com/", "http://bar.com/", false}, 1700 {"authorization", "http://foo.com/", "http://bar.com/", false}, 1701 {"www-authenticate", "http://foo.com/", "http://bar.com/", false}, 1702 1703 // But subdomains should work: 1704 {"www-authenticate", "http://foo.com/", "http://foo.com/", true}, 1705 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true}, 1706 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false}, 1707 {"www-authenticate", "http://foo.com/", "https://foo.com/", false}, 1708 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true}, 1709 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true}, 1710 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true}, 1711 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true}, 1712 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false}, 1713 } 1714 for i, tt := range tests { 1715 u0, err := url.Parse(tt.initialURL) 1716 if err != nil { 1717 t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err) 1718 continue 1719 } 1720 u1, err := url.Parse(tt.destURL) 1721 if err != nil { 1722 t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err) 1723 continue 1724 } 1725 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1) 1726 if got != tt.want { 1727 t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v", 1728 i, tt.header, tt.initialURL, tt.destURL, got, tt.want) 1729 } 1730 } 1731 } 1732 1733 func TestClientRedirectTypes(t *testing.T) { 1734 setParallel(t) 1735 defer afterTest(t) 1736 1737 tests := [...]struct { 1738 method string 1739 serverStatus int 1740 wantMethod string // desired subsequent client method 1741 }{ 1742 0: {method: "POST", serverStatus: 301, wantMethod: "GET"}, 1743 1: {method: "POST", serverStatus: 302, wantMethod: "GET"}, 1744 2: {method: "POST", serverStatus: 303, wantMethod: "GET"}, 1745 3: {method: "POST", serverStatus: 307, wantMethod: "POST"}, 1746 4: {method: "POST", serverStatus: 308, wantMethod: "POST"}, 1747 1748 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"}, 1749 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"}, 1750 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"}, 1751 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"}, 1752 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"}, 1753 1754 10: {method: "GET", serverStatus: 301, wantMethod: "GET"}, 1755 11: {method: "GET", serverStatus: 302, wantMethod: "GET"}, 1756 12: {method: "GET", serverStatus: 303, wantMethod: "GET"}, 1757 13: {method: "GET", serverStatus: 307, wantMethod: "GET"}, 1758 14: {method: "GET", serverStatus: 308, wantMethod: "GET"}, 1759 1760 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"}, 1761 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"}, 1762 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"}, 1763 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"}, 1764 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"}, 1765 1766 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"}, 1767 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"}, 1768 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"}, 1769 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"}, 1770 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"}, 1771 1772 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"}, 1773 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"}, 1774 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"}, 1775 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"}, 1776 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"}, 1777 } 1778 1779 handlerc := make(chan HandlerFunc, 1) 1780 1781 ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) { 1782 h := <-handlerc 1783 h(rw, req) 1784 })) 1785 defer ts.Close() 1786 1787 c := ts.Client() 1788 for i, tt := range tests { 1789 handlerc <- func(w ResponseWriter, r *Request) { 1790 w.Header().Set("Location", ts.URL) 1791 w.WriteHeader(tt.serverStatus) 1792 } 1793 1794 req, err := NewRequest(tt.method, ts.URL, nil) 1795 if err != nil { 1796 t.Errorf("#%d: NewRequest: %v", i, err) 1797 continue 1798 } 1799 1800 c.CheckRedirect = func(req *Request, via []*Request) error { 1801 if got, want := req.Method, tt.wantMethod; got != want { 1802 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want) 1803 } 1804 handlerc <- func(rw ResponseWriter, req *Request) { 1805 // TODO: Check that the body is valid when we do 307 and 308 support 1806 } 1807 return nil 1808 } 1809 1810 res, err := c.Do(req) 1811 if err != nil { 1812 t.Errorf("#%d: Response: %v", i, err) 1813 continue 1814 } 1815 1816 res.Body.Close() 1817 } 1818 } 1819 1820 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError. 1821 // Its Read returns readErr and increments *readCalls atomically. 1822 // Its Close returns nil and increments *closeCalls atomically. 1823 type issue18239Body struct { 1824 readCalls *int32 1825 closeCalls *int32 1826 readErr error 1827 } 1828 1829 func (b issue18239Body) Read([]byte) (int, error) { 1830 atomic.AddInt32(b.readCalls, 1) 1831 return 0, b.readErr 1832 } 1833 1834 func (b issue18239Body) Close() error { 1835 atomic.AddInt32(b.closeCalls, 1) 1836 return nil 1837 } 1838 1839 // Issue 18239: make sure the Transport doesn't retry requests with bodies 1840 // if Request.GetBody is not defined. 1841 func TestTransportBodyReadError(t *testing.T) { 1842 setParallel(t) 1843 defer afterTest(t) 1844 ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) { 1845 if r.URL.Path == "/ping" { 1846 return 1847 } 1848 buf := make([]byte, 1) 1849 n, err := r.Body.Read(buf) 1850 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err)) 1851 })) 1852 defer ts.Close() 1853 c := ts.Client() 1854 tr := c.Transport.(*Transport) 1855 1856 // Do one initial successful request to create an idle TCP connection 1857 // for the subsequent request to reuse. (The Transport only retries 1858 // requests on reused connections.) 1859 res, err := c.Get(ts.URL + "/ping") 1860 if err != nil { 1861 t.Fatal(err) 1862 } 1863 res.Body.Close() 1864 1865 var readCallsAtomic int32 1866 var closeCallsAtomic int32 // atomic 1867 someErr := errors.New("some body read error") 1868 body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr} 1869 1870 req, err := NewRequest("POST", ts.URL, body) 1871 if err != nil { 1872 t.Fatal(err) 1873 } 1874 req = req.WithT(t) 1875 _, err = tr.RoundTrip(req) 1876 if err != someErr { 1877 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr) 1878 } 1879 1880 // And verify that our Body wasn't used multiple times, which 1881 // would indicate retries. (as it buggily was during part of 1882 // Go 1.8's dev cycle) 1883 readCalls := atomic.LoadInt32(&readCallsAtomic) 1884 closeCalls := atomic.LoadInt32(&closeCallsAtomic) 1885 if readCalls != 1 { 1886 t.Errorf("read calls = %d; want 1", readCalls) 1887 } 1888 if closeCalls != 1 { 1889 t.Errorf("close calls = %d; want 1", closeCalls) 1890 } 1891 } 1892 1893 type roundTripperWithoutCloseIdle struct{} 1894 1895 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") } 1896 1897 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func 1898 1899 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") } 1900 func (f roundTripperWithCloseIdle) CloseIdleConnections() { f() } 1901 1902 func TestClientCloseIdleConnections(t *testing.T) { 1903 c := &Client{Transport: roundTripperWithoutCloseIdle{}} 1904 c.CloseIdleConnections() // verify we don't crash at least 1905 1906 closed := false 1907 var tr RoundTripper = roundTripperWithCloseIdle(func() { 1908 closed = true 1909 }) 1910 c = &Client{Transport: tr} 1911 c.CloseIdleConnections() 1912 if !closed { 1913 t.Error("not closed") 1914 } 1915 }