OSDN Git Service

libgo: Update to weekly.2011-11-02.
[pf3gnuchains/gcc-fork.git] / libgo / go / http / client.go
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 // HTTP client. See RFC 2616.
6 // 
7 // This is the high-level Client interface.
8 // The low-level implementation is in transport.go.
9
10 package http
11
12 import (
13         "encoding/base64"
14         "errors"
15         "fmt"
16         "io"
17         "strings"
18         "url"
19 )
20
21 // A Client is an HTTP client. Its zero value (DefaultClient) is a usable client
22 // that uses DefaultTransport.
23 //
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.
27 //
28 // Client is not yet very configurable.
29 type Client struct {
30         Transport RoundTripper // if nil, DefaultTransport is used
31
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.
37         //
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
41 }
42
43 // DefaultClient is the default Client and is used by Get, Head, and Post.
44 var DefaultClient = &Client{}
45
46 // RoundTripper is an interface representing the ability to execute a
47 // single HTTP transaction, obtaining the Response for a given Request.
48 //
49 // A RoundTripper must be safe for concurrent use by multiple
50 // goroutines.
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.
61         //
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)
66 }
67
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, "]") }
71
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 {
76         io.Reader
77         io.Closer
78 }
79
80 // Do sends an HTTP request and returns an HTTP response, following
81 // policy (e.g. redirects, cookies, auth) as configured on the client.
82 //
83 // A non-nil response always contains a non-nil resp.Body.
84 //
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.
89 //
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)
94         }
95         return send(req, c.Transport)
96 }
97
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) {
100         if t == nil {
101                 t = DefaultTransport
102                 if t == nil {
103                         err = errors.New("http: no Client.Transport or DefaultTransport")
104                         return
105                 }
106         }
107
108         if req.URL == nil {
109                 return nil, errors.New("http: nil Request.URL")
110         }
111
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)
117         }
118
119         info := req.URL.RawUserinfo
120         if len(info) > 0 {
121                 req.Header.Set("Authorization", "Basic "+base64.URLEncoding.EncodeToString([]byte(info)))
122         }
123         return t.RoundTrip(req)
124 }
125
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 {
129         switch statusCode {
130         case StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect:
131                 return true
132         }
133         return false
134 }
135
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:
138 //
139 //    301 (Moved Permanently)
140 //    302 (Found)
141 //    303 (See Other)
142 //    307 (Temporary Redirect)
143 //
144 // Caller should close r.Body when done reading from it.
145 //
146 // Get is a convenience wrapper around DefaultClient.Get.
147 func Get(url string) (r *Response, err error) {
148         return DefaultClient.Get(url)
149 }
150
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.
154 //
155 //    301 (Moved Permanently)
156 //    302 (Found)
157 //    303 (See Other)
158 //    307 (Temporary Redirect)
159 //
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)
163         if err != nil {
164                 return nil, err
165         }
166         return c.doFollowingRedirects(req)
167 }
168
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.
172         var base *url.URL
173         redirectChecker := c.CheckRedirect
174         if redirectChecker == nil {
175                 redirectChecker = defaultCheckRedirect
176         }
177         var via []*Request
178
179         if ireq.URL == nil {
180                 return nil, errors.New("http: nil Request.URL")
181         }
182
183         req := ireq
184         urlStr := "" // next relative or absolute URL to fetch (after first request)
185         for redirect := 0; ; redirect++ {
186                 if redirect != 0 {
187                         req = new(Request)
188                         req.Method = ireq.Method
189                         req.Header = make(Header)
190                         req.URL, err = base.Parse(urlStr)
191                         if err != nil {
192                                 break
193                         }
194                         if len(via) > 0 {
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())
199                                 }
200
201                                 err = redirectChecker(req, via)
202                                 if err != nil {
203                                         break
204                                 }
205                         }
206                 }
207
208                 urlStr = req.URL.String()
209                 if r, err = send(req, c.Transport); err != nil {
210                         break
211                 }
212                 if shouldRedirect(r.StatusCode) {
213                         r.Body.Close()
214                         if urlStr = r.Header.Get("Location"); urlStr == "" {
215                                 err = errors.New(fmt.Sprintf("%d response missing Location header", r.StatusCode))
216                                 break
217                         }
218                         base = req.URL
219                         via = append(via, req)
220                         continue
221                 }
222                 return
223         }
224
225         method := ireq.Method
226         err = &url.Error{method[0:1] + strings.ToLower(method[1:]), urlStr, err}
227         return
228 }
229
230 func defaultCheckRedirect(req *Request, via []*Request) error {
231         if len(via) >= 10 {
232                 return errors.New("stopped after 10 redirects")
233         }
234         return nil
235 }
236
237 // Post issues a POST to the specified URL.
238 //
239 // Caller should close r.Body when done reading from it.
240 //
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)
244 }
245
246 // Post issues a POST to the specified URL.
247 //
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)
251         if err != nil {
252                 return nil, err
253         }
254         req.Header.Set("Content-Type", bodyType)
255         return send(req, c.Transport)
256 }
257
258 // PostForm issues a POST to the specified URL, 
259 // with data's keys and values urlencoded as the request body.
260 //
261 // Caller should close r.Body when done reading from it.
262 //
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)
266 }
267
268 // PostForm issues a POST to the specified URL, 
269 // with data's keys and values urlencoded as the request body.
270 //
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()))
274 }
275
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.
279 //
280 //    301 (Moved Permanently)
281 //    302 (Found)
282 //    303 (See Other)
283 //    307 (Temporary Redirect)
284 //
285 // Head is a wrapper around DefaultClient.Head
286 func Head(url string) (r *Response, err error) {
287         return DefaultClient.Head(url)
288 }
289
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.
293 //
294 //    301 (Moved Permanently)
295 //    302 (Found)
296 //    303 (See Other)
297 //    307 (Temporary Redirect)
298 func (c *Client) Head(url string) (r *Response, err error) {
299         req, err := NewRequest("HEAD", url, nil)
300         if err != nil {
301                 return nil, err
302         }
303         return c.doFollowingRedirects(req)
304 }