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 2616.
7
// This is the high-level Client interface.
8
// The low-level implementation is in transport.go.
25
// A Client is an HTTP client. Its zero value (DefaultClient) is a
26
// usable client that uses DefaultTransport.
28
// The Client's Transport typically has internal state (cached TCP
29
// connections), so Clients should be reused instead of created as
30
// needed. Clients are safe for concurrent use by multiple goroutines.
32
// A Client is higher-level than a RoundTripper (such as Transport)
33
// and additionally handles HTTP details such as cookies and
36
// Transport specifies the mechanism by which individual
37
// HTTP requests are made.
38
// If nil, DefaultTransport is used.
39
Transport RoundTripper
41
// CheckRedirect specifies the policy for handling redirects.
42
// If CheckRedirect is not nil, the client calls it before
43
// following an HTTP redirect. The arguments req and via are
44
// the upcoming request and the requests made already, oldest
45
// first. If CheckRedirect returns an error, the Client's Get
46
// method returns both the previous Response and
47
// CheckRedirect's error (wrapped in a url.Error) instead of
48
// issuing the Request req.
50
// If CheckRedirect is nil, the Client uses its default policy,
51
// which is to stop after 10 consecutive requests.
52
CheckRedirect func(req *Request, via []*Request) error
54
// Jar specifies the cookie jar.
55
// If Jar is nil, cookies are not sent in requests and ignored
59
// Timeout specifies a time limit for requests made by this
60
// Client. The timeout includes connection time, any
61
// redirects, and reading the response body. The timer remains
62
// running after Get, Head, Post, or Do return and will
63
// interrupt reading of the Response.Body.
65
// A Timeout of zero means no timeout.
67
// The Client's Transport must support the CancelRequest
68
// method or Client will return errors when attempting to make
69
// a request with Get, Head, Post, or Do. Client's default
70
// Transport (DefaultTransport) supports CancelRequest.
74
// DefaultClient is the default Client and is used by Get, Head, and Post.
75
var DefaultClient = &Client{}
77
// RoundTripper is an interface representing the ability to execute a
78
// single HTTP transaction, obtaining the Response for a given Request.
80
// A RoundTripper must be safe for concurrent use by multiple
82
type RoundTripper interface {
83
// RoundTrip executes a single HTTP transaction, returning
84
// the Response for the request req. RoundTrip should not
85
// attempt to interpret the response. In particular,
86
// RoundTrip must return err == nil if it obtained a response,
87
// regardless of the response's HTTP status code. A non-nil
88
// err should be reserved for failure to obtain a response.
89
// Similarly, RoundTrip should not attempt to handle
90
// higher-level protocol details such as redirects,
91
// authentication, or cookies.
93
// RoundTrip should not modify the request, except for
94
// consuming and closing the Body. The request's URL and
95
// Header fields are guaranteed to be initialized.
96
RoundTrip(*Request) (*Response, error)
99
// Given a string of the form "host", "host:port", or "[ipv6::address]:port",
100
// return true if the string includes a port.
101
func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }
103
// Used in Send to implement io.ReadCloser by bundling together the
104
// bufio.Reader through which we read the response, and the underlying
105
// network connection.
106
type readClose struct {
111
func (c *Client) send(req *Request) (*Response, error) {
113
for _, cookie := range c.Jar.Cookies(req.URL) {
114
req.AddCookie(cookie)
117
resp, err := send(req, c.transport())
122
if rc := resp.Cookies(); len(rc) > 0 {
123
c.Jar.SetCookies(req.URL, rc)
129
// Do sends an HTTP request and returns an HTTP response, following
130
// policy (e.g. redirects, cookies, auth) as configured on the client.
132
// An error is returned if caused by client policy (such as
133
// CheckRedirect), or if there was an HTTP protocol error.
134
// A non-2xx response doesn't cause an error.
136
// When err is nil, resp always contains a non-nil resp.Body.
138
// Callers should close resp.Body when done reading from it. If
139
// resp.Body is not closed, the Client's underlying RoundTripper
140
// (typically Transport) may not be able to re-use a persistent TCP
141
// connection to the server for a subsequent "keep-alive" request.
143
// Generally Get, Post, or PostForm will be used instead of Do.
144
func (c *Client) Do(req *Request) (resp *Response, err error) {
145
if req.Method == "GET" || req.Method == "HEAD" {
146
return c.doFollowingRedirects(req, shouldRedirectGet)
148
if req.Method == "POST" || req.Method == "PUT" {
149
return c.doFollowingRedirects(req, shouldRedirectPost)
154
func (c *Client) transport() RoundTripper {
155
if c.Transport != nil {
158
return DefaultTransport
161
// send issues an HTTP request.
162
// Caller should close resp.Body when done reading from it.
163
func send(req *Request, t RoundTripper) (resp *Response, err error) {
165
return nil, errors.New("http: no Client.Transport or DefaultTransport")
169
return nil, errors.New("http: nil Request.URL")
172
if req.RequestURI != "" {
173
return nil, errors.New("http: Request.RequestURI can't be set in client requests.")
176
// Most the callers of send (Get, Post, et al) don't need
177
// Headers, leaving it uninitialized. We guarantee to the
178
// Transport that this has been initialized, though.
179
if req.Header == nil {
180
req.Header = make(Header)
183
if u := req.URL.User; u != nil {
184
username := u.Username()
185
password, _ := u.Password()
186
req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
188
resp, err = t.RoundTrip(req)
191
log.Printf("RoundTripper returned a response & error; ignoring response")
198
// See 2 (end of page 4) http://www.ietf.org/rfc/rfc2617.txt
199
// "To receive authorization, the client sends the userid and password,
200
// separated by a single colon (":") character, within a base64
201
// encoded string in the credentials."
202
// It is not meant to be urlencoded.
203
func basicAuth(username, password string) string {
204
auth := username + ":" + password
205
return base64.StdEncoding.EncodeToString([]byte(auth))
208
// True if the specified HTTP status code is one for which the Get utility should
209
// automatically redirect.
210
func shouldRedirectGet(statusCode int) bool {
212
case StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect:
218
// True if the specified HTTP status code is one for which the Post utility should
219
// automatically redirect.
220
func shouldRedirectPost(statusCode int) bool {
222
case StatusFound, StatusSeeOther:
228
// Get issues a GET to the specified URL. If the response is one of the following
229
// redirect codes, Get follows the redirect, up to a maximum of 10 redirects:
231
// 301 (Moved Permanently)
234
// 307 (Temporary Redirect)
236
// An error is returned if there were too many redirects or if there
237
// was an HTTP protocol error. A non-2xx response doesn't cause an
240
// When err is nil, resp always contains a non-nil resp.Body.
241
// Caller should close resp.Body when done reading from it.
243
// Get is a wrapper around DefaultClient.Get.
244
func Get(url string) (resp *Response, err error) {
245
return DefaultClient.Get(url)
248
// Get issues a GET to the specified URL. If the response is one of the
249
// following redirect codes, Get follows the redirect after calling the
250
// Client's CheckRedirect function.
252
// 301 (Moved Permanently)
255
// 307 (Temporary Redirect)
257
// An error is returned if the Client's CheckRedirect function fails
258
// or if there was an HTTP protocol error. A non-2xx response doesn't
261
// When err is nil, resp always contains a non-nil resp.Body.
262
// Caller should close resp.Body when done reading from it.
263
func (c *Client) Get(url string) (resp *Response, err error) {
264
req, err := NewRequest("GET", url, nil)
268
return c.doFollowingRedirects(req, shouldRedirectGet)
271
func (c *Client) doFollowingRedirects(ireq *Request, shouldRedirect func(int) bool) (resp *Response, err error) {
273
redirectChecker := c.CheckRedirect
274
if redirectChecker == nil {
275
redirectChecker = defaultCheckRedirect
280
return nil, errors.New("http: nil Request.URL")
283
var reqmu sync.Mutex // guards req
286
var timer *time.Timer
288
type canceler interface {
289
CancelRequest(*Request)
291
tr, ok := c.transport().(canceler)
293
return nil, fmt.Errorf("net/http: Client Transport of type %T doesn't support CancelRequest; Timeout not supported", c.transport())
295
timer = time.AfterFunc(c.Timeout, func() {
298
tr.CancelRequest(req)
302
urlStr := "" // next relative or absolute URL to fetch (after first request)
303
redirectFailed := false
304
for redirect := 0; ; redirect++ {
307
nreq.Method = ireq.Method
308
if ireq.Method == "POST" || ireq.Method == "PUT" {
311
nreq.Header = make(Header)
312
nreq.URL, err = base.Parse(urlStr)
317
// Add the Referer header.
318
lastReq := via[len(via)-1]
319
if lastReq.URL.Scheme != "https" {
320
nreq.Header.Set("Referer", lastReq.URL.String())
323
err = redirectChecker(nreq, via)
325
redirectFailed = true
334
urlStr = req.URL.String()
335
if resp, err = c.send(req); err != nil {
339
if shouldRedirect(resp.StatusCode) {
340
// Read the body if small so underlying TCP connection will be re-used.
341
// No need to check for errors: if it fails, Transport won't reuse it anyway.
342
const maxBodySlurpSize = 2 << 10
343
if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
344
io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
347
if urlStr = resp.Header.Get("Location"); urlStr == "" {
348
err = errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
352
via = append(via, req)
356
resp.Body = &cancelTimerBody{timer, resp.Body}
361
method := ireq.Method
362
urlErr := &url.Error{
363
Op: method[0:1] + strings.ToLower(method[1:]),
369
// Special case for Go 1 compatibility: return both the response
370
// and an error if the CheckRedirect function failed.
371
// See http://golang.org/issue/3795
381
func defaultCheckRedirect(req *Request, via []*Request) error {
383
return errors.New("stopped after 10 redirects")
388
// Post issues a POST to the specified URL.
390
// Caller should close resp.Body when done reading from it.
392
// Post is a wrapper around DefaultClient.Post
393
func Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
394
return DefaultClient.Post(url, bodyType, body)
397
// Post issues a POST to the specified URL.
399
// Caller should close resp.Body when done reading from it.
401
// If the provided body is also an io.Closer, it is closed after the
402
// body is successfully written to the server.
403
func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
404
req, err := NewRequest("POST", url, body)
408
req.Header.Set("Content-Type", bodyType)
409
return c.doFollowingRedirects(req, shouldRedirectPost)
412
// PostForm issues a POST to the specified URL, with data's keys and
413
// values URL-encoded as the request body.
415
// When err is nil, resp always contains a non-nil resp.Body.
416
// Caller should close resp.Body when done reading from it.
418
// PostForm is a wrapper around DefaultClient.PostForm
419
func PostForm(url string, data url.Values) (resp *Response, err error) {
420
return DefaultClient.PostForm(url, data)
423
// PostForm issues a POST to the specified URL,
424
// with data's keys and values urlencoded as the request body.
426
// When err is nil, resp always contains a non-nil resp.Body.
427
// Caller should close resp.Body when done reading from it.
428
func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
429
return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
432
// Head issues a HEAD to the specified URL. If the response is one of the
433
// following redirect codes, Head follows the redirect after calling the
434
// Client's CheckRedirect function.
436
// 301 (Moved Permanently)
439
// 307 (Temporary Redirect)
441
// Head is a wrapper around DefaultClient.Head
442
func Head(url string) (resp *Response, err error) {
443
return DefaultClient.Head(url)
446
// Head issues a HEAD to the specified URL. If the response is one of the
447
// following redirect codes, Head follows the redirect after calling the
448
// Client's CheckRedirect function.
450
// 301 (Moved Permanently)
453
// 307 (Temporary Redirect)
454
func (c *Client) Head(url string) (resp *Response, err error) {
455
req, err := NewRequest("HEAD", url, nil)
459
return c.doFollowingRedirects(req, shouldRedirectGet)
462
type cancelTimerBody struct {
467
func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
468
n, err = b.rc.Read(p)
475
func (b *cancelTimerBody) Close() error {