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.
21 // A Client is an HTTP client. Its zero value (DefaultClient) is a usable client
22 // that uses DefaultTransport.
24 // The Client's Transport typically has internal state (cached
25 // TCP connections), so Clients should be reused instead of created as
26 // needed. Clients are safe for concurrent use by multiple goroutines.
28 // Client is not yet very configurable.
30 Transport RoundTripper // if nil, DefaultTransport is used
32 // If CheckRedirect is not nil, the client calls it before
33 // following an HTTP redirect. The arguments req and via
34 // are the upcoming request and the requests made already,
35 // oldest first. If CheckRedirect returns an error, the client
36 // returns that error instead of issue the Request req.
38 // If CheckRedirect is nil, the Client uses its default policy,
39 // which is to stop after 10 consecutive requests.
40 CheckRedirect func(req *Request, via []*Request) error
43 // DefaultClient is the default Client and is used by Get, Head, and Post.
44 var DefaultClient = &Client{}
46 // RoundTripper is an interface representing the ability to execute a
47 // single HTTP transaction, obtaining the Response for a given Request.
49 // A RoundTripper must be safe for concurrent use by multiple
51 type RoundTripper interface {
52 // RoundTrip executes a single HTTP transaction, returning
53 // the Response for the request req. RoundTrip should not
54 // attempt to interpret the response. In particular,
55 // RoundTrip must return err == nil if it obtained a response,
56 // regardless of the response's HTTP status code. A non-nil
57 // err should be reserved for failure to obtain a response.
58 // Similarly, RoundTrip should not attempt to handle
59 // higher-level protocol details such as redirects,
60 // authentication, or cookies.
62 // RoundTrip should not modify the request, except for
63 // consuming the Body. The request's URL and Header fields
64 // are guaranteed to be initialized.
65 RoundTrip(*Request) (*Response, error)
68 // Given a string of the form "host", "host:port", or "[ipv6::address]:port",
69 // return true if the string includes a port.
70 func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }
72 // Used in Send to implement io.ReadCloser by bundling together the
73 // bufio.Reader through which we read the response, and the underlying
74 // network connection.
75 type readClose struct {
80 // Do sends an HTTP request and returns an HTTP response, following
81 // policy (e.g. redirects, cookies, auth) as configured on the client.
83 // A non-nil response always contains a non-nil resp.Body.
85 // Callers should close resp.Body when done reading from it. If
86 // resp.Body is not closed, the Client's underlying RoundTripper
87 // (typically Transport) may not be able to re-use a persistent TCP
88 // connection to the server for a subsequent "keep-alive" request.
90 // Generally Get, Post, or PostForm will be used instead of Do.
91 func (c *Client) Do(req *Request) (resp *Response, err error) {
92 if req.Method == "GET" || req.Method == "HEAD" {
93 return c.doFollowingRedirects(req)
95 return send(req, c.Transport)
98 // send issues an HTTP request. Caller should close resp.Body when done reading from it.
99 func send(req *Request, t RoundTripper) (resp *Response, err error) {
103 err = errors.New("http: no Client.Transport or DefaultTransport")
109 return nil, errors.New("http: nil Request.URL")
112 // Most the callers of send (Get, Post, et al) don't need
113 // Headers, leaving it uninitialized. We guarantee to the
114 // Transport that this has been initialized, though.
115 if req.Header == nil {
116 req.Header = make(Header)
119 info := req.URL.RawUserinfo
121 req.Header.Set("Authorization", "Basic "+base64.URLEncoding.EncodeToString([]byte(info)))
123 return t.RoundTrip(req)
126 // True if the specified HTTP status code is one for which the Get utility should
127 // automatically redirect.
128 func shouldRedirect(statusCode int) bool {
130 case StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect:
136 // Get issues a GET to the specified URL. If the response is one of the following
137 // redirect codes, Get follows the redirect, up to a maximum of 10 redirects:
139 // 301 (Moved Permanently)
142 // 307 (Temporary Redirect)
144 // Caller should close r.Body when done reading from it.
146 // Get is a convenience wrapper around DefaultClient.Get.
147 func Get(url string) (r *Response, err error) {
148 return DefaultClient.Get(url)
151 // Get issues a GET to the specified URL. If the response is one of the
152 // following redirect codes, Get follows the redirect after calling the
153 // Client's CheckRedirect function.
155 // 301 (Moved Permanently)
158 // 307 (Temporary Redirect)
160 // Caller should close r.Body when done reading from it.
161 func (c *Client) Get(url string) (r *Response, err error) {
162 req, err := NewRequest("GET", url, nil)
166 return c.doFollowingRedirects(req)
169 func (c *Client) doFollowingRedirects(ireq *Request) (r *Response, err error) {
170 // TODO: if/when we add cookie support, the redirected request shouldn't
171 // necessarily supply the same cookies as the original.
173 redirectChecker := c.CheckRedirect
174 if redirectChecker == nil {
175 redirectChecker = defaultCheckRedirect
180 return nil, errors.New("http: nil Request.URL")
184 urlStr := "" // next relative or absolute URL to fetch (after first request)
185 for redirect := 0; ; redirect++ {
188 req.Method = ireq.Method
189 req.Header = make(Header)
190 req.URL, err = base.Parse(urlStr)
195 // Add the Referer header.
196 lastReq := via[len(via)-1]
197 if lastReq.URL.Scheme != "https" {
198 req.Header.Set("Referer", lastReq.URL.String())
201 err = redirectChecker(req, via)
208 urlStr = req.URL.String()
209 if r, err = send(req, c.Transport); err != nil {
212 if shouldRedirect(r.StatusCode) {
214 if urlStr = r.Header.Get("Location"); urlStr == "" {
215 err = errors.New(fmt.Sprintf("%d response missing Location header", r.StatusCode))
219 via = append(via, req)
225 method := ireq.Method
226 err = &url.Error{method[0:1] + strings.ToLower(method[1:]), urlStr, err}
230 func defaultCheckRedirect(req *Request, via []*Request) error {
232 return errors.New("stopped after 10 redirects")
237 // Post issues a POST to the specified URL.
239 // Caller should close r.Body when done reading from it.
241 // Post is a wrapper around DefaultClient.Post
242 func Post(url string, bodyType string, body io.Reader) (r *Response, err error) {
243 return DefaultClient.Post(url, bodyType, body)
246 // Post issues a POST to the specified URL.
248 // Caller should close r.Body when done reading from it.
249 func (c *Client) Post(url string, bodyType string, body io.Reader) (r *Response, err error) {
250 req, err := NewRequest("POST", url, body)
254 req.Header.Set("Content-Type", bodyType)
255 return send(req, c.Transport)
258 // PostForm issues a POST to the specified URL,
259 // with data's keys and values urlencoded as the request body.
261 // Caller should close r.Body when done reading from it.
263 // PostForm is a wrapper around DefaultClient.PostForm
264 func PostForm(url string, data url.Values) (r *Response, err error) {
265 return DefaultClient.PostForm(url, data)
268 // PostForm issues a POST to the specified URL,
269 // with data's keys and values urlencoded as the request body.
271 // Caller should close r.Body when done reading from it.
272 func (c *Client) PostForm(url string, data url.Values) (r *Response, err error) {
273 return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
276 // Head issues a HEAD to the specified URL. If the response is one of the
277 // following redirect codes, Head follows the redirect after calling the
278 // Client's CheckRedirect function.
280 // 301 (Moved Permanently)
283 // 307 (Temporary Redirect)
285 // Head is a wrapper around DefaultClient.Head
286 func Head(url string) (r *Response, err error) {
287 return DefaultClient.Head(url)
290 // Head issues a HEAD to the specified URL. If the response is one of the
291 // following redirect codes, Head follows the redirect after calling the
292 // Client's CheckRedirect function.
294 // 301 (Moved Permanently)
297 // 307 (Temporary Redirect)
298 func (c *Client) Head(url string) (r *Response, err error) {
299 req, err := NewRequest("HEAD", url, nil)
303 return c.doFollowingRedirects(req)