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