Home | History | Annotate | Download | only in http
      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 	"crypto/tls"
     12 	"crypto/x509"
     13 	"encoding/base64"
     14 	"errors"
     15 	"fmt"
     16 	"io"
     17 	"io/ioutil"
     18 	"log"
     19 	"net"
     20 	. "net/http"
     21 	"net/http/httptest"
     22 	"net/url"
     23 	"reflect"
     24 	"sort"
     25 	"strconv"
     26 	"strings"
     27 	"sync"
     28 	"testing"
     29 	"time"
     30 )
     31 
     32 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
     33 	w.Header().Set("Last-Modified", "sometime")
     34 	fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
     35 })
     36 
     37 // pedanticReadAll works like ioutil.ReadAll but additionally
     38 // verifies that r obeys the documented io.Reader contract.
     39 func pedanticReadAll(r io.Reader) (b []byte, err error) {
     40 	var bufa [64]byte
     41 	buf := bufa[:]
     42 	for {
     43 		n, err := r.Read(buf)
     44 		if n == 0 && err == nil {
     45 			return nil, fmt.Errorf("Read: n=0 with err=nil")
     46 		}
     47 		b = append(b, buf[:n]...)
     48 		if err == io.EOF {
     49 			n, err := r.Read(buf)
     50 			if n != 0 || err != io.EOF {
     51 				return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
     52 			}
     53 			return b, nil
     54 		}
     55 		if err != nil {
     56 			return b, err
     57 		}
     58 	}
     59 }
     60 
     61 type chanWriter chan string
     62 
     63 func (w chanWriter) Write(p []byte) (n int, err error) {
     64 	w <- string(p)
     65 	return len(p), nil
     66 }
     67 
     68 func TestClient(t *testing.T) {
     69 	defer afterTest(t)
     70 	ts := httptest.NewServer(robotsTxtHandler)
     71 	defer ts.Close()
     72 
     73 	r, err := Get(ts.URL)
     74 	var b []byte
     75 	if err == nil {
     76 		b, err = pedanticReadAll(r.Body)
     77 		r.Body.Close()
     78 	}
     79 	if err != nil {
     80 		t.Error(err)
     81 	} else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
     82 		t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
     83 	}
     84 }
     85 
     86 func TestClientHead(t *testing.T) {
     87 	defer afterTest(t)
     88 	ts := httptest.NewServer(robotsTxtHandler)
     89 	defer ts.Close()
     90 
     91 	r, err := Head(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 	defer afterTest(t)
    111 	tr := &recordingTransport{}
    112 	client := &Client{Transport: tr}
    113 	url := "http://dummy.faketld/"
    114 	client.Get(url) // Note: doesn't hit network
    115 	if tr.req.Method != "GET" {
    116 		t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
    117 	}
    118 	if tr.req.URL.String() != url {
    119 		t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
    120 	}
    121 	if tr.req.Header == nil {
    122 		t.Errorf("expected non-nil request Header")
    123 	}
    124 }
    125 
    126 func TestPostRequestFormat(t *testing.T) {
    127 	defer afterTest(t)
    128 	tr := &recordingTransport{}
    129 	client := &Client{Transport: tr}
    130 
    131 	url := "http://dummy.faketld/"
    132 	json := `{"key":"value"}`
    133 	b := strings.NewReader(json)
    134 	client.Post(url, "application/json", b) // Note: doesn't hit network
    135 
    136 	if tr.req.Method != "POST" {
    137 		t.Errorf("got method %q, want %q", tr.req.Method, "POST")
    138 	}
    139 	if tr.req.URL.String() != url {
    140 		t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
    141 	}
    142 	if tr.req.Header == nil {
    143 		t.Fatalf("expected non-nil request Header")
    144 	}
    145 	if tr.req.Close {
    146 		t.Error("got Close true, want false")
    147 	}
    148 	if g, e := tr.req.ContentLength, int64(len(json)); g != e {
    149 		t.Errorf("got ContentLength %d, want %d", g, e)
    150 	}
    151 }
    152 
    153 func TestPostFormRequestFormat(t *testing.T) {
    154 	defer afterTest(t)
    155 	tr := &recordingTransport{}
    156 	client := &Client{Transport: tr}
    157 
    158 	urlStr := "http://dummy.faketld/"
    159 	form := make(url.Values)
    160 	form.Set("foo", "bar")
    161 	form.Add("foo", "bar2")
    162 	form.Set("bar", "baz")
    163 	client.PostForm(urlStr, form) // Note: doesn't hit network
    164 
    165 	if tr.req.Method != "POST" {
    166 		t.Errorf("got method %q, want %q", tr.req.Method, "POST")
    167 	}
    168 	if tr.req.URL.String() != urlStr {
    169 		t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
    170 	}
    171 	if tr.req.Header == nil {
    172 		t.Fatalf("expected non-nil request Header")
    173 	}
    174 	if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
    175 		t.Errorf("got Content-Type %q, want %q", g, e)
    176 	}
    177 	if tr.req.Close {
    178 		t.Error("got Close true, want false")
    179 	}
    180 	// Depending on map iteration, body can be either of these.
    181 	expectedBody := "foo=bar&foo=bar2&bar=baz"
    182 	expectedBody1 := "bar=baz&foo=bar&foo=bar2"
    183 	if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
    184 		t.Errorf("got ContentLength %d, want %d", g, e)
    185 	}
    186 	bodyb, err := ioutil.ReadAll(tr.req.Body)
    187 	if err != nil {
    188 		t.Fatalf("ReadAll on req.Body: %v", err)
    189 	}
    190 	if g := string(bodyb); g != expectedBody && g != expectedBody1 {
    191 		t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
    192 	}
    193 }
    194 
    195 func TestClientRedirects(t *testing.T) {
    196 	defer afterTest(t)
    197 	var ts *httptest.Server
    198 	ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    199 		n, _ := strconv.Atoi(r.FormValue("n"))
    200 		// Test Referer header. (7 is arbitrary position to test at)
    201 		if n == 7 {
    202 			if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
    203 				t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
    204 			}
    205 		}
    206 		if n < 15 {
    207 			Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusFound)
    208 			return
    209 		}
    210 		fmt.Fprintf(w, "n=%d", n)
    211 	}))
    212 	defer ts.Close()
    213 
    214 	c := &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 	// HEAD request should also have the ability to follow redirects.
    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 	// Do should also follow redirects.
    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 	var checkErr error
    234 	var lastVia []*Request
    235 	c = &Client{CheckRedirect: func(_ *Request, via []*Request) error {
    236 		lastVia = via
    237 		return checkErr
    238 	}}
    239 	res, err := c.Get(ts.URL)
    240 	if err != nil {
    241 		t.Fatalf("Get error: %v", err)
    242 	}
    243 	res.Body.Close()
    244 	finalUrl := res.Request.URL.String()
    245 	if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
    246 		t.Errorf("with custom client, expected error %q, got %q", e, g)
    247 	}
    248 	if !strings.HasSuffix(finalUrl, "/?n=15") {
    249 		t.Errorf("expected final url to end in /?n=15; got url %q", finalUrl)
    250 	}
    251 	if e, g := 15, len(lastVia); e != g {
    252 		t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
    253 	}
    254 
    255 	checkErr = errors.New("no redirects allowed")
    256 	res, err = c.Get(ts.URL)
    257 	if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
    258 		t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
    259 	}
    260 	if res == nil {
    261 		t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
    262 	}
    263 	res.Body.Close()
    264 	if res.Header.Get("Location") == "" {
    265 		t.Errorf("no Location header in Response")
    266 	}
    267 }
    268 
    269 func TestPostRedirects(t *testing.T) {
    270 	defer afterTest(t)
    271 	var log struct {
    272 		sync.Mutex
    273 		bytes.Buffer
    274 	}
    275 	var ts *httptest.Server
    276 	ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    277 		log.Lock()
    278 		fmt.Fprintf(&log.Buffer, "%s %s ", r.Method, r.RequestURI)
    279 		log.Unlock()
    280 		if v := r.URL.Query().Get("code"); v != "" {
    281 			code, _ := strconv.Atoi(v)
    282 			if code/100 == 3 {
    283 				w.Header().Set("Location", ts.URL)
    284 			}
    285 			w.WriteHeader(code)
    286 		}
    287 	}))
    288 	defer ts.Close()
    289 	tests := []struct {
    290 		suffix string
    291 		want   int // response code
    292 	}{
    293 		{"/", 200},
    294 		{"/?code=301", 301},
    295 		{"/?code=302", 200},
    296 		{"/?code=303", 200},
    297 		{"/?code=404", 404},
    298 	}
    299 	for _, tt := range tests {
    300 		res, err := Post(ts.URL+tt.suffix, "text/plain", strings.NewReader("Some content"))
    301 		if err != nil {
    302 			t.Fatal(err)
    303 		}
    304 		if res.StatusCode != tt.want {
    305 			t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
    306 		}
    307 	}
    308 	log.Lock()
    309 	got := log.String()
    310 	log.Unlock()
    311 	want := "POST / POST /?code=301 POST /?code=302 GET / POST /?code=303 GET / POST /?code=404 "
    312 	if got != want {
    313 		t.Errorf("Log differs.\n Got: %q\nWant: %q", got, want)
    314 	}
    315 }
    316 
    317 var expectedCookies = []*Cookie{
    318 	{Name: "ChocolateChip", Value: "tasty"},
    319 	{Name: "First", Value: "Hit"},
    320 	{Name: "Second", Value: "Hit"},
    321 }
    322 
    323 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
    324 	for _, cookie := range r.Cookies() {
    325 		SetCookie(w, cookie)
    326 	}
    327 	if r.URL.Path == "/" {
    328 		SetCookie(w, expectedCookies[1])
    329 		Redirect(w, r, "/second", StatusMovedPermanently)
    330 	} else {
    331 		SetCookie(w, expectedCookies[2])
    332 		w.Write([]byte("hello"))
    333 	}
    334 })
    335 
    336 func TestClientSendsCookieFromJar(t *testing.T) {
    337 	defer afterTest(t)
    338 	tr := &recordingTransport{}
    339 	client := &Client{Transport: tr}
    340 	client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
    341 	us := "http://dummy.faketld/"
    342 	u, _ := url.Parse(us)
    343 	client.Jar.SetCookies(u, expectedCookies)
    344 
    345 	client.Get(us) // Note: doesn't hit network
    346 	matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
    347 
    348 	client.Head(us) // Note: doesn't hit network
    349 	matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
    350 
    351 	client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
    352 	matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
    353 
    354 	client.PostForm(us, url.Values{}) // Note: doesn't hit network
    355 	matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
    356 
    357 	req, _ := NewRequest("GET", us, nil)
    358 	client.Do(req) // Note: doesn't hit network
    359 	matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
    360 
    361 	req, _ = NewRequest("POST", us, nil)
    362 	client.Do(req) // Note: doesn't hit network
    363 	matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
    364 }
    365 
    366 // Just enough correctness for our redirect tests. Uses the URL.Host as the
    367 // scope of all cookies.
    368 type TestJar struct {
    369 	m      sync.Mutex
    370 	perURL map[string][]*Cookie
    371 }
    372 
    373 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
    374 	j.m.Lock()
    375 	defer j.m.Unlock()
    376 	if j.perURL == nil {
    377 		j.perURL = make(map[string][]*Cookie)
    378 	}
    379 	j.perURL[u.Host] = cookies
    380 }
    381 
    382 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
    383 	j.m.Lock()
    384 	defer j.m.Unlock()
    385 	return j.perURL[u.Host]
    386 }
    387 
    388 func TestRedirectCookiesJar(t *testing.T) {
    389 	defer afterTest(t)
    390 	var ts *httptest.Server
    391 	ts = httptest.NewServer(echoCookiesRedirectHandler)
    392 	defer ts.Close()
    393 	c := &Client{
    394 		Jar: new(TestJar),
    395 	}
    396 	u, _ := url.Parse(ts.URL)
    397 	c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
    398 	resp, err := c.Get(ts.URL)
    399 	if err != nil {
    400 		t.Fatalf("Get: %v", err)
    401 	}
    402 	resp.Body.Close()
    403 	matchReturnedCookies(t, expectedCookies, resp.Cookies())
    404 }
    405 
    406 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
    407 	if len(given) != len(expected) {
    408 		t.Logf("Received cookies: %v", given)
    409 		t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
    410 	}
    411 	for _, ec := range expected {
    412 		foundC := false
    413 		for _, c := range given {
    414 			if ec.Name == c.Name && ec.Value == c.Value {
    415 				foundC = true
    416 				break
    417 			}
    418 		}
    419 		if !foundC {
    420 			t.Errorf("Missing cookie %v", ec)
    421 		}
    422 	}
    423 }
    424 
    425 func TestJarCalls(t *testing.T) {
    426 	defer afterTest(t)
    427 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    428 		pathSuffix := r.RequestURI[1:]
    429 		if r.RequestURI == "/nosetcookie" {
    430 			return // don't set cookies for this path
    431 		}
    432 		SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
    433 		if r.RequestURI == "/" {
    434 			Redirect(w, r, "http://secondhost.fake/secondpath", 302)
    435 		}
    436 	}))
    437 	defer ts.Close()
    438 	jar := new(RecordingJar)
    439 	c := &Client{
    440 		Jar: jar,
    441 		Transport: &Transport{
    442 			Dial: func(_ string, _ string) (net.Conn, error) {
    443 				return net.Dial("tcp", ts.Listener.Addr().String())
    444 			},
    445 		},
    446 	}
    447 	_, err := c.Get("http://firsthost.fake/")
    448 	if err != nil {
    449 		t.Fatal(err)
    450 	}
    451 	_, err = c.Get("http://firsthost.fake/nosetcookie")
    452 	if err != nil {
    453 		t.Fatal(err)
    454 	}
    455 	got := jar.log.String()
    456 	want := `Cookies("http://firsthost.fake/")
    457 SetCookie("http://firsthost.fake/", [name=val])
    458 Cookies("http://secondhost.fake/secondpath")
    459 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
    460 Cookies("http://firsthost.fake/nosetcookie")
    461 `
    462 	if got != want {
    463 		t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
    464 	}
    465 }
    466 
    467 // RecordingJar keeps a log of calls made to it, without
    468 // tracking any cookies.
    469 type RecordingJar struct {
    470 	mu  sync.Mutex
    471 	log bytes.Buffer
    472 }
    473 
    474 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
    475 	j.logf("SetCookie(%q, %v)\n", u, cookies)
    476 }
    477 
    478 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
    479 	j.logf("Cookies(%q)\n", u)
    480 	return nil
    481 }
    482 
    483 func (j *RecordingJar) logf(format string, args ...interface{}) {
    484 	j.mu.Lock()
    485 	defer j.mu.Unlock()
    486 	fmt.Fprintf(&j.log, format, args...)
    487 }
    488 
    489 func TestStreamingGet(t *testing.T) {
    490 	defer afterTest(t)
    491 	say := make(chan string)
    492 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    493 		w.(Flusher).Flush()
    494 		for str := range say {
    495 			w.Write([]byte(str))
    496 			w.(Flusher).Flush()
    497 		}
    498 	}))
    499 	defer ts.Close()
    500 
    501 	c := &Client{}
    502 	res, err := c.Get(ts.URL)
    503 	if err != nil {
    504 		t.Fatal(err)
    505 	}
    506 	var buf [10]byte
    507 	for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
    508 		say <- str
    509 		n, err := io.ReadFull(res.Body, buf[0:len(str)])
    510 		if err != nil {
    511 			t.Fatalf("ReadFull on %q: %v", str, err)
    512 		}
    513 		if n != len(str) {
    514 			t.Fatalf("Receiving %q, only read %d bytes", str, n)
    515 		}
    516 		got := string(buf[0:n])
    517 		if got != str {
    518 			t.Fatalf("Expected %q, got %q", str, got)
    519 		}
    520 	}
    521 	close(say)
    522 	_, err = io.ReadFull(res.Body, buf[0:1])
    523 	if err != io.EOF {
    524 		t.Fatalf("at end expected EOF, got %v", err)
    525 	}
    526 }
    527 
    528 type writeCountingConn struct {
    529 	net.Conn
    530 	count *int
    531 }
    532 
    533 func (c *writeCountingConn) Write(p []byte) (int, error) {
    534 	*c.count++
    535 	return c.Conn.Write(p)
    536 }
    537 
    538 // TestClientWrites verifies that client requests are buffered and we
    539 // don't send a TCP packet per line of the http request + body.
    540 func TestClientWrites(t *testing.T) {
    541 	defer afterTest(t)
    542 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    543 	}))
    544 	defer ts.Close()
    545 
    546 	writes := 0
    547 	dialer := func(netz string, addr string) (net.Conn, error) {
    548 		c, err := net.Dial(netz, addr)
    549 		if err == nil {
    550 			c = &writeCountingConn{c, &writes}
    551 		}
    552 		return c, err
    553 	}
    554 	c := &Client{Transport: &Transport{Dial: dialer}}
    555 
    556 	_, err := c.Get(ts.URL)
    557 	if err != nil {
    558 		t.Fatal(err)
    559 	}
    560 	if writes != 1 {
    561 		t.Errorf("Get request did %d Write calls, want 1", writes)
    562 	}
    563 
    564 	writes = 0
    565 	_, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
    566 	if err != nil {
    567 		t.Fatal(err)
    568 	}
    569 	if writes != 1 {
    570 		t.Errorf("Post request did %d Write calls, want 1", writes)
    571 	}
    572 }
    573 
    574 func TestClientInsecureTransport(t *testing.T) {
    575 	defer afterTest(t)
    576 	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    577 		w.Write([]byte("Hello"))
    578 	}))
    579 	errc := make(chanWriter, 10) // but only expecting 1
    580 	ts.Config.ErrorLog = log.New(errc, "", 0)
    581 	defer ts.Close()
    582 
    583 	// TODO(bradfitz): add tests for skipping hostname checks too?
    584 	// would require a new cert for testing, and probably
    585 	// redundant with these tests.
    586 	for _, insecure := range []bool{true, false} {
    587 		tr := &Transport{
    588 			TLSClientConfig: &tls.Config{
    589 				InsecureSkipVerify: insecure,
    590 			},
    591 		}
    592 		defer tr.CloseIdleConnections()
    593 		c := &Client{Transport: tr}
    594 		res, err := c.Get(ts.URL)
    595 		if (err == nil) != insecure {
    596 			t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
    597 		}
    598 		if res != nil {
    599 			res.Body.Close()
    600 		}
    601 	}
    602 
    603 	select {
    604 	case v := <-errc:
    605 		if !strings.Contains(v, "TLS handshake error") {
    606 			t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
    607 		}
    608 	case <-time.After(5 * time.Second):
    609 		t.Errorf("timeout waiting for logged error")
    610 	}
    611 
    612 }
    613 
    614 func TestClientErrorWithRequestURI(t *testing.T) {
    615 	defer afterTest(t)
    616 	req, _ := NewRequest("GET", "http://localhost:1234/", nil)
    617 	req.RequestURI = "/this/field/is/illegal/and/should/error/"
    618 	_, err := DefaultClient.Do(req)
    619 	if err == nil {
    620 		t.Fatalf("expected an error")
    621 	}
    622 	if !strings.Contains(err.Error(), "RequestURI") {
    623 		t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
    624 	}
    625 }
    626 
    627 func newTLSTransport(t *testing.T, ts *httptest.Server) *Transport {
    628 	certs := x509.NewCertPool()
    629 	for _, c := range ts.TLS.Certificates {
    630 		roots, err := x509.ParseCertificates(c.Certificate[len(c.Certificate)-1])
    631 		if err != nil {
    632 			t.Fatalf("error parsing server's root cert: %v", err)
    633 		}
    634 		for _, root := range roots {
    635 			certs.AddCert(root)
    636 		}
    637 	}
    638 	return &Transport{
    639 		TLSClientConfig: &tls.Config{RootCAs: certs},
    640 	}
    641 }
    642 
    643 func TestClientWithCorrectTLSServerName(t *testing.T) {
    644 	defer afterTest(t)
    645 	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    646 		if r.TLS.ServerName != "127.0.0.1" {
    647 			t.Errorf("expected client to set ServerName 127.0.0.1, got: %q", r.TLS.ServerName)
    648 		}
    649 	}))
    650 	defer ts.Close()
    651 
    652 	c := &Client{Transport: newTLSTransport(t, ts)}
    653 	if _, err := c.Get(ts.URL); err != nil {
    654 		t.Fatalf("expected successful TLS connection, got error: %v", err)
    655 	}
    656 }
    657 
    658 func TestClientWithIncorrectTLSServerName(t *testing.T) {
    659 	defer afterTest(t)
    660 	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
    661 	defer ts.Close()
    662 	errc := make(chanWriter, 10) // but only expecting 1
    663 	ts.Config.ErrorLog = log.New(errc, "", 0)
    664 
    665 	trans := newTLSTransport(t, ts)
    666 	trans.TLSClientConfig.ServerName = "badserver"
    667 	c := &Client{Transport: trans}
    668 	_, err := c.Get(ts.URL)
    669 	if err == nil {
    670 		t.Fatalf("expected an error")
    671 	}
    672 	if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
    673 		t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
    674 	}
    675 	select {
    676 	case v := <-errc:
    677 		if !strings.Contains(v, "TLS handshake error") {
    678 			t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
    679 		}
    680 	case <-time.After(5 * time.Second):
    681 		t.Errorf("timeout waiting for logged error")
    682 	}
    683 }
    684 
    685 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
    686 // when not empty.
    687 //
    688 // tls.Config.ServerName (non-empty, set to "example.com") takes
    689 // precedence over "some-other-host.tld" which previously incorrectly
    690 // took precedence. We don't actually connect to (or even resolve)
    691 // "some-other-host.tld", though, because of the Transport.Dial hook.
    692 //
    693 // The httptest.Server has a cert with "example.com" as its name.
    694 func TestTransportUsesTLSConfigServerName(t *testing.T) {
    695 	defer afterTest(t)
    696 	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    697 		w.Write([]byte("Hello"))
    698 	}))
    699 	defer ts.Close()
    700 
    701 	tr := newTLSTransport(t, ts)
    702 	tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
    703 	tr.Dial = func(netw, addr string) (net.Conn, error) {
    704 		return net.Dial(netw, ts.Listener.Addr().String())
    705 	}
    706 	defer tr.CloseIdleConnections()
    707 	c := &Client{Transport: tr}
    708 	res, err := c.Get("https://some-other-host.tld/")
    709 	if err != nil {
    710 		t.Fatal(err)
    711 	}
    712 	res.Body.Close()
    713 }
    714 
    715 func TestResponseSetsTLSConnectionState(t *testing.T) {
    716 	defer afterTest(t)
    717 	ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    718 		w.Write([]byte("Hello"))
    719 	}))
    720 	defer ts.Close()
    721 
    722 	tr := newTLSTransport(t, ts)
    723 	tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
    724 	tr.Dial = func(netw, addr string) (net.Conn, error) {
    725 		return net.Dial(netw, ts.Listener.Addr().String())
    726 	}
    727 	defer tr.CloseIdleConnections()
    728 	c := &Client{Transport: tr}
    729 	res, err := c.Get("https://example.com/")
    730 	if err != nil {
    731 		t.Fatal(err)
    732 	}
    733 	defer res.Body.Close()
    734 	if res.TLS == nil {
    735 		t.Fatal("Response didn't set TLS Connection State.")
    736 	}
    737 	if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
    738 		t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
    739 	}
    740 }
    741 
    742 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
    743 func TestClientHeadContentLength(t *testing.T) {
    744 	defer afterTest(t)
    745 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    746 		if v := r.FormValue("cl"); v != "" {
    747 			w.Header().Set("Content-Length", v)
    748 		}
    749 	}))
    750 	defer ts.Close()
    751 	tests := []struct {
    752 		suffix string
    753 		want   int64
    754 	}{
    755 		{"/?cl=1234", 1234},
    756 		{"/?cl=0", 0},
    757 		{"", -1},
    758 	}
    759 	for _, tt := range tests {
    760 		req, _ := NewRequest("HEAD", ts.URL+tt.suffix, nil)
    761 		res, err := DefaultClient.Do(req)
    762 		if err != nil {
    763 			t.Fatal(err)
    764 		}
    765 		if res.ContentLength != tt.want {
    766 			t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
    767 		}
    768 		bs, err := ioutil.ReadAll(res.Body)
    769 		if err != nil {
    770 			t.Fatal(err)
    771 		}
    772 		if len(bs) != 0 {
    773 			t.Errorf("Unexpected content: %q", bs)
    774 		}
    775 	}
    776 }
    777 
    778 func TestEmptyPasswordAuth(t *testing.T) {
    779 	defer afterTest(t)
    780 	gopher := "gopher"
    781 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    782 		auth := r.Header.Get("Authorization")
    783 		if strings.HasPrefix(auth, "Basic ") {
    784 			encoded := auth[6:]
    785 			decoded, err := base64.StdEncoding.DecodeString(encoded)
    786 			if err != nil {
    787 				t.Fatal(err)
    788 			}
    789 			expected := gopher + ":"
    790 			s := string(decoded)
    791 			if expected != s {
    792 				t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
    793 			}
    794 		} else {
    795 			t.Errorf("Invalid auth %q", auth)
    796 		}
    797 	}))
    798 	defer ts.Close()
    799 	c := &Client{}
    800 	req, err := NewRequest("GET", ts.URL, nil)
    801 	if err != nil {
    802 		t.Fatal(err)
    803 	}
    804 	req.URL.User = url.User(gopher)
    805 	resp, err := c.Do(req)
    806 	if err != nil {
    807 		t.Fatal(err)
    808 	}
    809 	defer resp.Body.Close()
    810 }
    811 
    812 func TestBasicAuth(t *testing.T) {
    813 	defer afterTest(t)
    814 	tr := &recordingTransport{}
    815 	client := &Client{Transport: tr}
    816 
    817 	url := "http://My%20User:My%20Pass@dummy.faketld/"
    818 	expected := "My User:My Pass"
    819 	client.Get(url)
    820 
    821 	if tr.req.Method != "GET" {
    822 		t.Errorf("got method %q, want %q", tr.req.Method, "GET")
    823 	}
    824 	if tr.req.URL.String() != url {
    825 		t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
    826 	}
    827 	if tr.req.Header == nil {
    828 		t.Fatalf("expected non-nil request Header")
    829 	}
    830 	auth := tr.req.Header.Get("Authorization")
    831 	if strings.HasPrefix(auth, "Basic ") {
    832 		encoded := auth[6:]
    833 		decoded, err := base64.StdEncoding.DecodeString(encoded)
    834 		if err != nil {
    835 			t.Fatal(err)
    836 		}
    837 		s := string(decoded)
    838 		if expected != s {
    839 			t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
    840 		}
    841 	} else {
    842 		t.Errorf("Invalid auth %q", auth)
    843 	}
    844 }
    845 
    846 func TestBasicAuthHeadersPreserved(t *testing.T) {
    847 	defer afterTest(t)
    848 	tr := &recordingTransport{}
    849 	client := &Client{Transport: tr}
    850 
    851 	// If Authorization header is provided, username in URL should not override it
    852 	url := "http://My%20User@dummy.faketld/"
    853 	req, err := NewRequest("GET", url, nil)
    854 	if err != nil {
    855 		t.Fatal(err)
    856 	}
    857 	req.SetBasicAuth("My User", "My Pass")
    858 	expected := "My User:My Pass"
    859 	client.Do(req)
    860 
    861 	if tr.req.Method != "GET" {
    862 		t.Errorf("got method %q, want %q", tr.req.Method, "GET")
    863 	}
    864 	if tr.req.URL.String() != url {
    865 		t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
    866 	}
    867 	if tr.req.Header == nil {
    868 		t.Fatalf("expected non-nil request Header")
    869 	}
    870 	auth := tr.req.Header.Get("Authorization")
    871 	if strings.HasPrefix(auth, "Basic ") {
    872 		encoded := auth[6:]
    873 		decoded, err := base64.StdEncoding.DecodeString(encoded)
    874 		if err != nil {
    875 			t.Fatal(err)
    876 		}
    877 		s := string(decoded)
    878 		if expected != s {
    879 			t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
    880 		}
    881 	} else {
    882 		t.Errorf("Invalid auth %q", auth)
    883 	}
    884 
    885 }
    886 
    887 func TestClientTimeout(t *testing.T) {
    888 	if testing.Short() {
    889 		t.Skip("skipping in short mode")
    890 	}
    891 	defer afterTest(t)
    892 	sawRoot := make(chan bool, 1)
    893 	sawSlow := make(chan bool, 1)
    894 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    895 		if r.URL.Path == "/" {
    896 			sawRoot <- true
    897 			Redirect(w, r, "/slow", StatusFound)
    898 			return
    899 		}
    900 		if r.URL.Path == "/slow" {
    901 			w.Write([]byte("Hello"))
    902 			w.(Flusher).Flush()
    903 			sawSlow <- true
    904 			time.Sleep(2 * time.Second)
    905 			return
    906 		}
    907 	}))
    908 	defer ts.Close()
    909 	const timeout = 500 * time.Millisecond
    910 	c := &Client{
    911 		Timeout: timeout,
    912 	}
    913 
    914 	res, err := c.Get(ts.URL)
    915 	if err != nil {
    916 		t.Fatal(err)
    917 	}
    918 
    919 	select {
    920 	case <-sawRoot:
    921 		// good.
    922 	default:
    923 		t.Fatal("handler never got / request")
    924 	}
    925 
    926 	select {
    927 	case <-sawSlow:
    928 		// good.
    929 	default:
    930 		t.Fatal("handler never got /slow request")
    931 	}
    932 
    933 	errc := make(chan error, 1)
    934 	go func() {
    935 		_, err := ioutil.ReadAll(res.Body)
    936 		errc <- err
    937 		res.Body.Close()
    938 	}()
    939 
    940 	const failTime = timeout * 2
    941 	select {
    942 	case err := <-errc:
    943 		if err == nil {
    944 			t.Fatal("expected error from ReadAll")
    945 		}
    946 		ne, ok := err.(net.Error)
    947 		if !ok {
    948 			t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
    949 		} else if !ne.Timeout() {
    950 			t.Errorf("net.Error.Timeout = false; want true")
    951 		}
    952 		if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
    953 			t.Errorf("error string = %q; missing timeout substring", got)
    954 		}
    955 	case <-time.After(failTime):
    956 		t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
    957 	}
    958 }
    959 
    960 // Client.Timeout firing before getting to the body
    961 func TestClientTimeout_Headers(t *testing.T) {
    962 	if testing.Short() {
    963 		t.Skip("skipping in short mode")
    964 	}
    965 	defer afterTest(t)
    966 	donec := make(chan bool)
    967 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
    968 		<-donec
    969 	}))
    970 	defer ts.Close()
    971 	// Note that we use a channel send here and not a close.
    972 	// The race detector doesn't know that we're waiting for a timeout
    973 	// and thinks that the waitgroup inside httptest.Server is added to concurrently
    974 	// with us closing it. If we timed out immediately, we could close the testserver
    975 	// before we entered the handler. We're not timing out immediately and there's
    976 	// no way we would be done before we entered the handler, but the race detector
    977 	// doesn't know this, so synchronize explicitly.
    978 	defer func() { donec <- true }()
    979 
    980 	c := &Client{Timeout: 500 * time.Millisecond}
    981 
    982 	_, err := c.Get(ts.URL)
    983 	if err == nil {
    984 		t.Fatal("got response from Get; expected error")
    985 	}
    986 	ue, ok := err.(*url.Error)
    987 	if !ok {
    988 		t.Fatalf("Got error of type %T; want *url.Error", err)
    989 	}
    990 	ne, ok := ue.Err.(net.Error)
    991 	if !ok {
    992 		t.Fatalf("Got url.Error.Err of type %T; want some net.Error", err)
    993 	}
    994 	if !ne.Timeout() {
    995 		t.Error("net.Error.Timeout = false; want true")
    996 	}
    997 	if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
    998 		t.Errorf("error string = %q; missing timeout substring", got)
    999 	}
   1000 }
   1001 
   1002 func TestClientRedirectEatsBody(t *testing.T) {
   1003 	defer afterTest(t)
   1004 	saw := make(chan string, 2)
   1005 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
   1006 		saw <- r.RemoteAddr
   1007 		if r.URL.Path == "/" {
   1008 			Redirect(w, r, "/foo", StatusFound) // which includes a body
   1009 		}
   1010 	}))
   1011 	defer ts.Close()
   1012 
   1013 	res, err := Get(ts.URL)
   1014 	if err != nil {
   1015 		t.Fatal(err)
   1016 	}
   1017 	_, err = ioutil.ReadAll(res.Body)
   1018 	if err != nil {
   1019 		t.Fatal(err)
   1020 	}
   1021 	res.Body.Close()
   1022 
   1023 	var first string
   1024 	select {
   1025 	case first = <-saw:
   1026 	default:
   1027 		t.Fatal("server didn't see a request")
   1028 	}
   1029 
   1030 	var second string
   1031 	select {
   1032 	case second = <-saw:
   1033 	default:
   1034 		t.Fatal("server didn't see a second request")
   1035 	}
   1036 
   1037 	if first != second {
   1038 		t.Fatal("server saw different client ports before & after the redirect")
   1039 	}
   1040 }
   1041 
   1042 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
   1043 type eofReaderFunc func()
   1044 
   1045 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
   1046 	f()
   1047 	return 0, io.EOF
   1048 }
   1049 
   1050 func TestClientTrailers(t *testing.T) {
   1051 	defer afterTest(t)
   1052 	ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
   1053 		w.Header().Set("Connection", "close")
   1054 		w.Header().Set("Trailer", "Server-Trailer-A, Server-Trailer-B")
   1055 		w.Header().Add("Trailer", "Server-Trailer-C")
   1056 
   1057 		var decl []string
   1058 		for k := range r.Trailer {
   1059 			decl = append(decl, k)
   1060 		}
   1061 		sort.Strings(decl)
   1062 
   1063 		slurp, err := ioutil.ReadAll(r.Body)
   1064 		if err != nil {
   1065 			t.Errorf("Server reading request body: %v", err)
   1066 		}
   1067 		if string(slurp) != "foo" {
   1068 			t.Errorf("Server read request body %q; want foo", slurp)
   1069 		}
   1070 		if r.Trailer == nil {
   1071 			io.WriteString(w, "nil Trailer")
   1072 		} else {
   1073 			fmt.Fprintf(w, "decl: %v, vals: %s, %s",
   1074 				decl,
   1075 				r.Trailer.Get("Client-Trailer-A"),
   1076 				r.Trailer.Get("Client-Trailer-B"))
   1077 		}
   1078 
   1079 		// How handlers set Trailers: declare it ahead of time
   1080 		// with the Trailer header, and then mutate the
   1081 		// Header() of those values later, after the response
   1082 		// has been written (we wrote to w above).
   1083 		w.Header().Set("Server-Trailer-A", "valuea")
   1084 		w.Header().Set("Server-Trailer-C", "valuec") // skipping B
   1085 	}))
   1086 	defer ts.Close()
   1087 
   1088 	var req *Request
   1089 	req, _ = NewRequest("POST", ts.URL, io.MultiReader(
   1090 		eofReaderFunc(func() {
   1091 			req.Trailer["Client-Trailer-A"] = []string{"valuea"}
   1092 		}),
   1093 		strings.NewReader("foo"),
   1094 		eofReaderFunc(func() {
   1095 			req.Trailer["Client-Trailer-B"] = []string{"valueb"}
   1096 		}),
   1097 	))
   1098 	req.Trailer = Header{
   1099 		"Client-Trailer-A": nil, //  to be set later
   1100 		"Client-Trailer-B": nil, //  to be set later
   1101 	}
   1102 	req.ContentLength = -1
   1103 	res, err := DefaultClient.Do(req)
   1104 	if err != nil {
   1105 		t.Fatal(err)
   1106 	}
   1107 	if err := wantBody(res, err, "decl: [Client-Trailer-A Client-Trailer-B], vals: valuea, valueb"); err != nil {
   1108 		t.Error(err)
   1109 	}
   1110 	want := Header{
   1111 		"Server-Trailer-A": []string{"valuea"},
   1112 		"Server-Trailer-B": nil,
   1113 		"Server-Trailer-C": []string{"valuec"},
   1114 	}
   1115 	if !reflect.DeepEqual(res.Trailer, want) {
   1116 		t.Errorf("Response trailers = %#v; want %#v", res.Trailer, want)
   1117 	}
   1118 }
   1119 
   1120 func TestReferer(t *testing.T) {
   1121 	tests := []struct {
   1122 		lastReq, newReq string // from -> to URLs
   1123 		want            string
   1124 	}{
   1125 		// don't send user:
   1126 		{"http://gopher@test.com", "http://link.com", "http://test.com"},
   1127 		{"https://gopher@test.com", "https://link.com", "https://test.com"},
   1128 
   1129 		// don't send a user and password:
   1130 		{"http://gopher:go@test.com", "http://link.com", "http://test.com"},
   1131 		{"https://gopher:go@test.com", "https://link.com", "https://test.com"},
   1132 
   1133 		// nothing to do:
   1134 		{"http://test.com", "http://link.com", "http://test.com"},
   1135 		{"https://test.com", "https://link.com", "https://test.com"},
   1136 
   1137 		// https to http doesn't send a referer:
   1138 		{"https://test.com", "http://link.com", ""},
   1139 		{"https://gopher:go@test.com", "http://link.com", ""},
   1140 	}
   1141 	for _, tt := range tests {
   1142 		l, err := url.Parse(tt.lastReq)
   1143 		if err != nil {
   1144 			t.Fatal(err)
   1145 		}
   1146 		n, err := url.Parse(tt.newReq)
   1147 		if err != nil {
   1148 			t.Fatal(err)
   1149 		}
   1150 		r := ExportRefererForURL(l, n)
   1151 		if r != tt.want {
   1152 			t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
   1153 		}
   1154 	}
   1155 }
   1156