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.
5
// HTTP client. See RFC 7230 through 7235.
7
// This is the high-level Client interface.
8
// The low-level implementation is in transport.go.
27
// A Client is an HTTP client. Its zero value (DefaultClient) is a
28
// usable client that uses DefaultTransport.
30
// The Client's Transport typically has internal state (cached TCP
31
// connections), so Clients should be reused instead of created as
32
// needed. Clients are safe for concurrent use by multiple goroutines.
34
// A Client is higher-level than a RoundTripper (such as Transport)
35
// and additionally handles HTTP details such as cookies and
38
// When following redirects, the Client will forward all headers set on the
39
// initial Request except:
41
// • when forwarding sensitive headers like "Authorization",
42
// "WWW-Authenticate", and "Cookie" to untrusted targets.
43
// These headers will be ignored when following a redirect to a domain
44
// that is not a subdomain match or exact match of the initial domain.
45
// For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
46
// will forward the sensitive headers, but a redirect to "bar.com" will not.
48
// • when forwarding the "Cookie" header with a non-nil cookie Jar.
49
// Since each redirect may mutate the state of the cookie jar,
50
// a redirect may possibly alter a cookie set in the initial request.
51
// When forwarding the "Cookie" header, any mutated cookies will be omitted,
52
// with the expectation that the Jar will insert those mutated cookies
53
// with the updated values (assuming the origin matches).
54
// If Jar is nil, the initial cookies are forwarded without change.
57
// Transport specifies the mechanism by which individual
58
// HTTP requests are made.
59
// If nil, DefaultTransport is used.
60
Transport RoundTripper
62
// CheckRedirect specifies the policy for handling redirects.
63
// If CheckRedirect is not nil, the client calls it before
64
// following an HTTP redirect. The arguments req and via are
65
// the upcoming request and the requests made already, oldest
66
// first. If CheckRedirect returns an error, the Client's Get
67
// method returns both the previous Response (with its Body
68
// closed) and CheckRedirect's error (wrapped in a url.Error)
69
// instead of issuing the Request req.
70
// As a special case, if CheckRedirect returns ErrUseLastResponse,
71
// then the most recent response is returned with its body
72
// unclosed, along with a nil error.
74
// If CheckRedirect is nil, the Client uses its default policy,
75
// which is to stop after 10 consecutive requests.
76
CheckRedirect func(req *Request, via []*Request) error
78
// Jar specifies the cookie jar.
80
// The Jar is used to insert relevant cookies into every
81
// outbound Request and is updated with the cookie values
82
// of every inbound Response. The Jar is consulted for every
83
// redirect that the Client follows.
85
// If Jar is nil, cookies are only sent if they are explicitly
86
// set on the Request.
89
// Timeout specifies a time limit for requests made by this
90
// Client. The timeout includes connection time, any
91
// redirects, and reading the response body. The timer remains
92
// running after Get, Head, Post, or Do return and will
93
// interrupt reading of the Response.Body.
95
// A Timeout of zero means no timeout.
97
// The Client cancels requests to the underlying Transport
98
// as if the Request's Context ended.
100
// For compatibility, the Client will also use the deprecated
101
// CancelRequest method on Transport if found. New
102
// RoundTripper implementations should use the Request's Context
103
// for cancelation instead of implementing CancelRequest.
104
Timeout time.Duration
107
// DefaultClient is the default Client and is used by Get, Head, and Post.
108
var DefaultClient = &Client{}
110
// RoundTripper is an interface representing the ability to execute a
111
// single HTTP transaction, obtaining the Response for a given Request.
113
// A RoundTripper must be safe for concurrent use by multiple
115
type RoundTripper interface {
116
// RoundTrip executes a single HTTP transaction, returning
117
// a Response for the provided Request.
119
// RoundTrip should not attempt to interpret the response. In
120
// particular, RoundTrip must return err == nil if it obtained
121
// a response, regardless of the response's HTTP status code.
122
// A non-nil err should be reserved for failure to obtain a
123
// response. Similarly, RoundTrip should not attempt to
124
// handle higher-level protocol details such as redirects,
125
// authentication, or cookies.
127
// RoundTrip should not modify the request, except for
128
// consuming and closing the Request's Body. RoundTrip may
129
// read fields of the request in a separate goroutine. Callers
130
// should not mutate or reuse the request until the Response's
131
// Body has been closed.
133
// RoundTrip must always close the body, including on errors,
134
// but depending on the implementation may do so in a separate
135
// goroutine even after RoundTrip returns. This means that
136
// callers wanting to reuse the body for subsequent requests
137
// must arrange to wait for the Close call before doing so.
139
// The Request's URL and Header fields must be initialized.
140
RoundTrip(*Request) (*Response, error)
143
// refererForURL returns a referer without any authentication info or
144
// an empty string if lastReq scheme is https and newReq scheme is http.
145
func refererForURL(lastReq, newReq *url.URL) string {
146
// https://tools.ietf.org/html/rfc7231#section-5.5.2
147
// "Clients SHOULD NOT include a Referer header field in a
148
// (non-secure) HTTP request if the referring page was
149
// transferred with a secure protocol."
150
if lastReq.Scheme == "https" && newReq.Scheme == "http" {
153
referer := lastReq.String()
154
if lastReq.User != nil {
155
// This is not very efficient, but is the best we can
157
// - introducing a new method on URL
158
// - creating a race condition
159
// - copying the URL struct manually, which would cause
160
// maintenance problems down the line
161
auth := lastReq.User.String() + "@"
162
referer = strings.Replace(referer, auth, "", 1)
167
// didTimeout is non-nil only if err != nil.
168
func (c *Client) send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
170
for _, cookie := range c.Jar.Cookies(req.URL) {
171
req.AddCookie(cookie)
174
resp, didTimeout, err = send(req, c.transport(), deadline)
176
return nil, didTimeout, err
179
if rc := resp.Cookies(); len(rc) > 0 {
180
c.Jar.SetCookies(req.URL, rc)
183
return resp, nil, nil
186
func (c *Client) deadline() time.Time {
188
return time.Now().Add(c.Timeout)
193
func (c *Client) transport() RoundTripper {
194
if c.Transport != nil {
197
return DefaultTransport
200
// send issues an HTTP request.
201
// Caller should close resp.Body when done reading from it.
202
func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
203
req := ireq // req is either the original request, or a modified fork
207
return nil, alwaysFalse, errors.New("http: no Client.Transport or DefaultTransport")
212
return nil, alwaysFalse, errors.New("http: nil Request.URL")
215
if req.RequestURI != "" {
217
return nil, alwaysFalse, errors.New("http: Request.RequestURI can't be set in client requests.")
220
// forkReq forks req into a shallow clone of ireq the first
225
*req = *ireq // shallow clone
229
// Most the callers of send (Get, Post, et al) don't need
230
// Headers, leaving it uninitialized. We guarantee to the
231
// Transport that this has been initialized, though.
232
if req.Header == nil {
234
req.Header = make(Header)
237
if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" {
238
username := u.Username()
239
password, _ := u.Password()
241
req.Header = cloneHeader(ireq.Header)
242
req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
245
if !deadline.IsZero() {
248
stopTimer, didTimeout := setRequestCancel(req, rt, deadline)
250
resp, err = rt.RoundTrip(req)
254
log.Printf("RoundTripper returned a response & error; ignoring response")
256
if tlsErr, ok := err.(tls.RecordHeaderError); ok {
257
// If we get a bad TLS record header, check to see if the
258
// response looks like HTTP and give a more helpful error.
259
// See golang.org/issue/11111.
260
if string(tlsErr.RecordHeader[:]) == "HTTP/" {
261
err = errors.New("http: server gave HTTP response to HTTPS client")
264
return nil, didTimeout, err
266
if !deadline.IsZero() {
267
resp.Body = &cancelTimerBody{
270
reqDidTimeout: didTimeout,
273
return resp, nil, nil
276
// setRequestCancel sets the Cancel field of req, if deadline is
277
// non-zero. The RoundTripper's type is used to determine whether the legacy
278
// CancelRequest behavior should be used.
280
// As background, there are three ways to cancel a request:
281
// First was Transport.CancelRequest. (deprecated)
282
// Second was Request.Cancel (this mechanism).
283
// Third was Request.Context.
284
func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool) {
285
if deadline.IsZero() {
286
return nop, alwaysFalse
289
initialReqCancel := req.Cancel // the user's original Request.Cancel, if any
291
cancel := make(chan struct{})
295
// The newer way (the second way in the func comment):
298
// The legacy compatibility way, used only
299
// for RoundTripper implementations written
300
// before Go 1.5 or Go 1.6.
301
type canceler interface {
302
CancelRequest(*Request)
304
switch v := rt.(type) {
305
case *Transport, *http2Transport:
306
// Do nothing. The net/http package's transports
307
// support the new Request.Cancel channel
313
stopTimerCh := make(chan struct{})
315
stopTimer = func() { once.Do(func() { close(stopTimerCh) }) }
317
timer := time.NewTimer(time.Until(deadline))
318
var timedOut atomicBool
322
case <-initialReqCancel:
333
return stopTimer, timedOut.isSet
336
// See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt
337
// "To receive authorization, the client sends the userid and password,
338
// separated by a single colon (":") character, within a base64
339
// encoded string in the credentials."
340
// It is not meant to be urlencoded.
341
func basicAuth(username, password string) string {
342
auth := username + ":" + password
343
return base64.StdEncoding.EncodeToString([]byte(auth))
346
// Get issues a GET to the specified URL. If the response is one of
347
// the following redirect codes, Get follows the redirect, up to a
348
// maximum of 10 redirects:
350
// 301 (Moved Permanently)
353
// 307 (Temporary Redirect)
354
// 308 (Permanent Redirect)
356
// An error is returned if there were too many redirects or if there
357
// was an HTTP protocol error. A non-2xx response doesn't cause an
358
// error. Any returned error will be of type *url.Error. The url.Error
359
// value's Timeout method will report true if request timed out or was
362
// When err is nil, resp always contains a non-nil resp.Body.
363
// Caller should close resp.Body when done reading from it.
365
// Get is a wrapper around DefaultClient.Get.
367
// To make a request with custom headers, use NewRequest and
369
func Get(url string) (resp *Response, err error) {
370
return DefaultClient.Get(url)
373
// Get issues a GET to the specified URL. If the response is one of the
374
// following redirect codes, Get follows the redirect after calling the
375
// Client's CheckRedirect function:
377
// 301 (Moved Permanently)
380
// 307 (Temporary Redirect)
381
// 308 (Permanent Redirect)
383
// An error is returned if the Client's CheckRedirect function fails
384
// or if there was an HTTP protocol error. A non-2xx response doesn't
385
// cause an error. Any returned error will be of type *url.Error. The
386
// url.Error value's Timeout method will report true if request timed
387
// out or was canceled.
389
// When err is nil, resp always contains a non-nil resp.Body.
390
// Caller should close resp.Body when done reading from it.
392
// To make a request with custom headers, use NewRequest and Client.Do.
393
func (c *Client) Get(url string) (resp *Response, err error) {
394
req, err := NewRequest("GET", url, nil)
401
func alwaysFalse() bool { return false }
403
// ErrUseLastResponse can be returned by Client.CheckRedirect hooks to
404
// control how redirects are processed. If returned, the next request
405
// is not sent and the most recent response is returned with its body
407
var ErrUseLastResponse = errors.New("net/http: use last response")
409
// checkRedirect calls either the user's configured CheckRedirect
410
// function, or the default.
411
func (c *Client) checkRedirect(req *Request, via []*Request) error {
412
fn := c.CheckRedirect
414
fn = defaultCheckRedirect
419
// redirectBehavior describes what should happen when the
420
// client encounters a 3xx status code from the server
421
func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool) {
422
switch resp.StatusCode {
424
redirectMethod = reqMethod
425
shouldRedirect = true
428
// RFC 2616 allowed automatic redirection only with GET and
429
// HEAD requests. RFC 7231 lifts this restriction, but we still
430
// restrict other methods to GET to maintain compatibility.
432
if reqMethod != "GET" && reqMethod != "HEAD" {
433
redirectMethod = "GET"
436
redirectMethod = reqMethod
437
shouldRedirect = true
440
// Treat 307 and 308 specially, since they're new in
441
// Go 1.8, and they also require re-sending the request body.
442
if resp.Header.Get("Location") == "" {
443
// 308s have been observed in the wild being served
444
// without Location headers. Since Go 1.7 and earlier
445
// didn't follow these codes, just stop here instead
446
// of returning an error.
448
shouldRedirect = false
451
if ireq.GetBody == nil && ireq.outgoingLength() != 0 {
452
// We had a request body, and 307/308 require
453
// re-sending it, but GetBody is not defined. So just
454
// return this response to the user instead of an
455
// error, like we did in Go 1.7 and earlier.
456
shouldRedirect = false
459
return redirectMethod, shouldRedirect, includeBody
462
// urlErrorOp returns the (*url.Error).Op value to use for the
463
// provided (*Request).Method value.
464
func urlErrorOp(method string) string {
468
return method[:1] + strings.ToLower(method[1:])
471
// Do sends an HTTP request and returns an HTTP response, following
472
// policy (such as redirects, cookies, auth) as configured on the
475
// An error is returned if caused by client policy (such as
476
// CheckRedirect), or failure to speak HTTP (such as a network
477
// connectivity problem). A non-2xx status code doesn't cause an
480
// If the returned error is nil, the Response will contain a non-nil
481
// Body which the user is expected to close. If the Body is not
482
// closed, the Client's underlying RoundTripper (typically Transport)
483
// may not be able to re-use a persistent TCP connection to the server
484
// for a subsequent "keep-alive" request.
486
// The request Body, if non-nil, will be closed by the underlying
487
// Transport, even on errors.
489
// On error, any Response can be ignored. A non-nil Response with a
490
// non-nil error only occurs when CheckRedirect fails, and even then
491
// the returned Response.Body is already closed.
493
// Generally Get, Post, or PostForm will be used instead of Do.
495
// If the server replies with a redirect, the Client first uses the
496
// CheckRedirect function to determine whether the redirect should be
497
// followed. If permitted, a 301, 302, or 303 redirect causes
498
// subsequent requests to use HTTP method GET
499
// (or HEAD if the original request was HEAD), with no body.
500
// A 307 or 308 redirect preserves the original HTTP method and body,
501
// provided that the Request.GetBody function is defined.
502
// The NewRequest function automatically sets GetBody for common
503
// standard library body types.
505
// Any returned error will be of type *url.Error. The url.Error
506
// value's Timeout method will report true if request timed out or was
508
func (c *Client) Do(req *Request) (*Response, error) {
512
var testHookClientDoResult func(retres *Response, reterr error)
514
func (c *Client) do(req *Request) (retres *Response, reterr error) {
515
if testHookClientDoResult != nil {
516
defer func() { testHookClientDoResult(retres, reterr) }()
520
return nil, &url.Error{
521
Op: urlErrorOp(req.Method),
522
Err: errors.New("http: nil Request.URL"),
527
deadline = c.deadline()
530
copyHeaders = c.makeHeadersCopier(req)
531
reqBodyClosed = false // have we closed the current req.Body?
533
// Redirect behavior:
534
redirectMethod string
537
uerr := func(err error) error {
538
// the body may have been closed already by c.send()
543
if resp != nil && resp.Request != nil {
544
urlStr = stripPassword(resp.Request.URL)
546
urlStr = stripPassword(req.URL)
549
Op: urlErrorOp(reqs[0].Method),
555
// For all but the first request, create the next
556
// request hop and replace req.
558
loc := resp.Header.Get("Location")
561
return nil, uerr(fmt.Errorf("%d response missing Location header", resp.StatusCode))
563
u, err := req.URL.Parse(loc)
566
return nil, uerr(fmt.Errorf("failed to parse Location header %q: %v", loc, err))
569
if req.Host != "" && req.Host != req.URL.Host {
570
// If the caller specified a custom Host header and the
571
// redirect location is relative, preserve the Host header
572
// through the redirect. See issue #22233.
573
if u, _ := url.Parse(loc); u != nil && !u.IsAbs() {
579
Method: redirectMethod,
582
Header: make(Header),
587
if includeBody && ireq.GetBody != nil {
588
req.Body, err = ireq.GetBody()
591
return nil, uerr(err)
593
req.ContentLength = ireq.ContentLength
596
// Copy original headers before setting the Referer,
597
// in case the user set Referer on their first request.
598
// If they really want to override, they can do it in
599
// their CheckRedirect func.
602
// Add the Referer header from the most recent
603
// request URL to the new one, if it's not https->http:
604
if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL); ref != "" {
605
req.Header.Set("Referer", ref)
607
err = c.checkRedirect(req, reqs)
609
// Sentinel error to let users select the
610
// previous response, without closing its
611
// body. See Issue 10069.
612
if err == ErrUseLastResponse {
616
// Close the previous response's body. But
617
// read at least some of the body so if it's
618
// small the underlying TCP connection will be
619
// re-used. No need to check for errors: if it
620
// fails, the Transport won't reuse it anyway.
621
const maxBodySlurpSize = 2 << 10
622
if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
623
io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
628
// Special case for Go 1 compatibility: return both the response
629
// and an error if the CheckRedirect function failed.
630
// See https://golang.org/issue/3795
631
// The resp.Body has already been closed.
633
ue.(*url.Error).URL = loc
638
reqs = append(reqs, req)
640
var didTimeout func() bool
641
if resp, didTimeout, err = c.send(req, deadline); err != nil {
642
// c.send() always closes req.Body
644
if !deadline.IsZero() && didTimeout() {
646
// TODO: early in cycle: s/Client.Timeout exceeded/timeout or context cancelation/
647
err: err.Error() + " (Client.Timeout exceeded while awaiting headers)",
651
return nil, uerr(err)
654
var shouldRedirect bool
655
redirectMethod, shouldRedirect, includeBody = redirectBehavior(req.Method, resp, reqs[0])
664
// makeHeadersCopier makes a function that copies headers from the
665
// initial Request, ireq. For every redirect, this function must be called
666
// so that it can copy headers into the upcoming Request.
667
func (c *Client) makeHeadersCopier(ireq *Request) func(*Request) {
668
// The headers to copy are from the very initial request.
669
// We use a closured callback to keep a reference to these original headers.
671
ireqhdr = ireq.Header.clone()
672
icookies map[string][]*Cookie
674
if c.Jar != nil && ireq.Header.Get("Cookie") != "" {
675
icookies = make(map[string][]*Cookie)
676
for _, c := range ireq.Cookies() {
677
icookies[c.Name] = append(icookies[c.Name], c)
681
preq := ireq // The previous request
682
return func(req *Request) {
683
// If Jar is present and there was some initial cookies provided
684
// via the request header, then we may need to alter the initial
685
// cookies as we follow redirects since each redirect may end up
686
// modifying a pre-existing cookie.
688
// Since cookies already set in the request header do not contain
689
// information about the original domain and path, the logic below
690
// assumes any new set cookies override the original cookie
691
// regardless of domain or path.
693
// See https://golang.org/issue/17494
694
if c.Jar != nil && icookies != nil {
696
resp := req.Response // The response that caused the upcoming redirect
697
for _, c := range resp.Cookies() {
698
if _, ok := icookies[c.Name]; ok {
699
delete(icookies, c.Name)
704
ireqhdr.Del("Cookie")
706
for _, cs := range icookies {
707
for _, c := range cs {
708
ss = append(ss, c.Name+"="+c.Value)
711
sort.Strings(ss) // Ensure deterministic headers
712
ireqhdr.Set("Cookie", strings.Join(ss, "; "))
716
// Copy the initial request's Header values
717
// (at least the safe ones).
718
for k, vv := range ireqhdr {
719
if shouldCopyHeaderOnRedirect(k, preq.URL, req.URL) {
724
preq = req // Update previous Request with the current request
728
func defaultCheckRedirect(req *Request, via []*Request) error {
730
return errors.New("stopped after 10 redirects")
735
// Post issues a POST to the specified URL.
737
// Caller should close resp.Body when done reading from it.
739
// If the provided body is an io.Closer, it is closed after the
742
// Post is a wrapper around DefaultClient.Post.
744
// To set custom headers, use NewRequest and DefaultClient.Do.
746
// See the Client.Do method documentation for details on how redirects
748
func Post(url, contentType string, body io.Reader) (resp *Response, err error) {
749
return DefaultClient.Post(url, contentType, body)
752
// Post issues a POST to the specified URL.
754
// Caller should close resp.Body when done reading from it.
756
// If the provided body is an io.Closer, it is closed after the
759
// To set custom headers, use NewRequest and Client.Do.
761
// See the Client.Do method documentation for details on how redirects
763
func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error) {
764
req, err := NewRequest("POST", url, body)
768
req.Header.Set("Content-Type", contentType)
772
// PostForm issues a POST to the specified URL, with data's keys and
773
// values URL-encoded as the request body.
775
// The Content-Type header is set to application/x-www-form-urlencoded.
776
// To set other headers, use NewRequest and DefaultClient.Do.
778
// When err is nil, resp always contains a non-nil resp.Body.
779
// Caller should close resp.Body when done reading from it.
781
// PostForm is a wrapper around DefaultClient.PostForm.
783
// See the Client.Do method documentation for details on how redirects
785
func PostForm(url string, data url.Values) (resp *Response, err error) {
786
return DefaultClient.PostForm(url, data)
789
// PostForm issues a POST to the specified URL,
790
// with data's keys and values URL-encoded as the request body.
792
// The Content-Type header is set to application/x-www-form-urlencoded.
793
// To set other headers, use NewRequest and Client.Do.
795
// When err is nil, resp always contains a non-nil resp.Body.
796
// Caller should close resp.Body when done reading from it.
798
// See the Client.Do method documentation for details on how redirects
800
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
801
return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
804
// Head issues a HEAD to the specified URL. If the response is one of
805
// the following redirect codes, Head follows the redirect, up to a
806
// maximum of 10 redirects:
808
// 301 (Moved Permanently)
811
// 307 (Temporary Redirect)
812
// 308 (Permanent Redirect)
814
// Head is a wrapper around DefaultClient.Head
815
func Head(url string) (resp *Response, err error) {
816
return DefaultClient.Head(url)
819
// Head issues a HEAD to the specified URL. If the response is one of the
820
// following redirect codes, Head follows the redirect after calling the
821
// Client's CheckRedirect function:
823
// 301 (Moved Permanently)
826
// 307 (Temporary Redirect)
827
// 308 (Permanent Redirect)
828
func (c *Client) Head(url string) (resp *Response, err error) {
829
req, err := NewRequest("HEAD", url, nil)
836
// cancelTimerBody is an io.ReadCloser that wraps rc with two features:
837
// 1) on Read error or close, the stop func is called.
838
// 2) On Read failure, if reqDidTimeout is true, the error is wrapped and
839
// marked as net.Error that hit its timeout.
840
type cancelTimerBody struct {
841
stop func() // stops the time.Timer waiting to cancel the request
843
reqDidTimeout func() bool
846
func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
847
n, err = b.rc.Read(p)
855
if b.reqDidTimeout() {
857
// TODO: early in cycle: s/Client.Timeout exceeded/timeout or context cancelation/
858
err: err.Error() + " (Client.Timeout exceeded while reading body)",
865
func (b *cancelTimerBody) Close() error {
871
func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool {
872
switch CanonicalHeaderKey(headerKey) {
873
case "Authorization", "Www-Authenticate", "Cookie", "Cookie2":
874
// Permit sending auth/cookie headers from "foo.com"
877
// Note that we don't send all cookies to subdomains
878
// automatically. This function is only used for
879
// Cookies set explicitly on the initial outgoing
880
// client request. Cookies automatically added via the
881
// CookieJar mechanism continue to follow each
882
// cookie's scope as set by Set-Cookie. But for
883
// outgoing requests with the Cookie header set
884
// directly, we don't know their scope, so we assume
885
// it's for *.domain.com.
887
ihost := canonicalAddr(initial)
888
dhost := canonicalAddr(dest)
889
return isDomainOrSubdomain(dhost, ihost)
891
// All other headers are copied:
895
// isDomainOrSubdomain reports whether sub is a subdomain (or exact
896
// match) of the parent domain.
898
// Both domains must already be in canonical form.
899
func isDomainOrSubdomain(sub, parent string) bool {
903
// If sub is "foo.example.com" and parent is "example.com",
904
// that means sub must end in "."+parent.
905
// Do it without allocating.
906
if !strings.HasSuffix(sub, parent) {
909
return sub[len(sub)-len(parent)-1] == '.'
912
func stripPassword(u *url.URL) string {
913
pass, passSet := u.User.Password()
915
return strings.Replace(u.String(), pass+"@", "***@", 1)