Debian Codegraph @

testdata/net_http_client.go

raw symbols SCIP
1 // +build ignore
2 // Copyright 2009 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
5
6 // HTTP client. See RFC 2616.
7 //
8 // This is the high-level Client interface.
9 // The low-level implementation is in transport.go.
10
11 package http
12
13 import (
14 "encoding/base64"
15 "errors"
16 "fmt"
17 "io"
18 "io/ioutil"
19 "log"
20 "net/url"
21 "strings"
22 "sync"
23 "time"
24 )
25
26 // A Client is an HTTP client. Its zero value (DefaultClient) is a
27 // usable client that uses DefaultTransport.
28 //
29 // The Client's Transport typically has internal state (cached TCP
30 // connections), so Clients should be reused instead of created as
31 // needed. Clients are safe for concurrent use by multiple goroutines.
32 //
33 // A Client is higher-level than a RoundTripper (such as Transport)
34 // and additionally handles HTTP details such as cookies and
35 // redirects.
36 type Client struct {
37 // Transport specifies the mechanism by which individual
38 // HTTP requests are made.
39 // If nil, DefaultTransport is used.
40 Transport RoundTripper
41
42 // CheckRedirect specifies the policy for handling redirects.
43 // If CheckRedirect is not nil, the client calls it before
44 // following an HTTP redirect. The arguments req and via are
45 // the upcoming request and the requests made already, oldest
46 // first. If CheckRedirect returns an error, the Client's Get
47 // method returns both the previous Response and
48 // CheckRedirect's error (wrapped in a url.Error) instead of
49 // issuing the Request req.
50 //
51 // If CheckRedirect is nil, the Client uses its default policy,
52 // which is to stop after 10 consecutive requests.
53 CheckRedirect func(req *Request, via []*Request) error
54
55 // Jar specifies the cookie jar.
56 // If Jar is nil, cookies are not sent in requests and ignored
57 // in responses.
58 Jar CookieJar
59
60 // Timeout specifies a time limit for requests made by this
61 // Client. The timeout includes connection time, any
62 // redirects, and reading the response body. The timer remains
63 // running after Get, Head, Post, or Do return and will
64 // interrupt reading of the Response.Body.
65 //
66 // A Timeout of zero means no timeout.
67 //
68 // The Client's Transport must support the CancelRequest
69 // method or Client will return errors when attempting to make
70 // a request with Get, Head, Post, or Do. Client's default
71 // Transport (DefaultTransport) supports CancelRequest.
72 Timeout time.Duration
73 }
74
75 // DefaultClient is the default Client and is used by Get, Head, and Post.
76 var DefaultClient = &Client{}
77
78 // RoundTripper is an interface representing the ability to execute a
79 // single HTTP transaction, obtaining the Response for a given Request.
80 //
81 // A RoundTripper must be safe for concurrent use by multiple
82 // goroutines.
83 type RoundTripper interface {
84 // RoundTrip executes a single HTTP transaction, returning
85 // the Response for the request req. RoundTrip should not
86 // attempt to interpret the response. In particular,
87 // RoundTrip must return err == nil if it obtained a response,
88 // regardless of the response's HTTP status code. A non-nil
89 // err should be reserved for failure to obtain a response.
90 // Similarly, RoundTrip should not attempt to handle
91 // higher-level protocol details such as redirects,
92 // authentication, or cookies.
93 //
94 // RoundTrip should not modify the request, except for
95 // consuming and closing the Body, including on errors. The
96 // request's URL and Header fields are guaranteed to be
97 // initialized.
98 RoundTrip(*Request) (*Response, error)
99 }
100
101 // Given a string of the form "host", "host:port", or "[ipv6::address]:port",
102 // return true if the string includes a port.
103 func hasPort(s string) bool { return strings.LastIndex(s, ":") > strings.LastIndex(s, "]") }
104
105 // Used in Send to implement io.ReadCloser by bundling together the
106 // bufio.Reader through which we read the response, and the underlying
107 // network connection.
108 type readClose struct {
109 io.Reader
110 io.Closer
111 }
112
113 func (c *Client) send(req *Request) (*Response, error) {
114 if c.Jar != nil {
115 for _, cookie := range c.Jar.Cookies(req.URL) {
116 req.AddCookie(cookie)
117 }
118 }
119 resp, err := send(req, c.transport())
120 if err != nil {
121 return nil, err
122 }
123 if c.Jar != nil {
124 if rc := resp.Cookies(); len(rc) > 0 {
125 c.Jar.SetCookies(req.URL, rc)
126 }
127 }
128 return resp, err
129 }
130
131 // Do sends an HTTP request and returns an HTTP response, following
132 // policy (e.g. redirects, cookies, auth) as configured on the client.
133 //
134 // An error is returned if caused by client policy (such as
135 // CheckRedirect), or if there was an HTTP protocol error.
136 // A non-2xx response doesn't cause an error.
137 //
138 // When err is nil, resp always contains a non-nil resp.Body.
139 //
140 // Callers should close resp.Body when done reading from it. If
141 // resp.Body is not closed, the Client's underlying RoundTripper
142 // (typically Transport) may not be able to re-use a persistent TCP
143 // connection to the server for a subsequent "keep-alive" request.
144 //
145 // The request Body, if non-nil, will be closed by the underlying
146 // Transport, even on errors.
147 //
148 // Generally Get, Post, or PostForm will be used instead of Do.
149 func (c *Client) Do(req *Request) (resp *Response, err error) {
150 if req.Method == "GET" || req.Method == "HEAD" {
151 return c.doFollowingRedirects(req, shouldRedirectGet)
152 }
153 if req.Method == "POST" || req.Method == "PUT" {
154 return c.doFollowingRedirects(req, shouldRedirectPost)
155 }
156 return c.send(req)
157 }
158
159 func (c *Client) transport() RoundTripper {
160 if c.Transport != nil {
161 return c.Transport
162 }
163 return DefaultTransport
164 }
165
166 // send issues an HTTP request.
167 // Caller should close resp.Body when done reading from it.
168 func send(req *Request, t RoundTripper) (resp *Response, err error) {
169 if t == nil {
170 req.closeBody()
171 return nil, errors.New("http: no Client.Transport or DefaultTransport")
172 }
173
174 if req.URL == nil {
175 req.closeBody()
176 return nil, errors.New("http: nil Request.URL")
177 }
178
179 if req.RequestURI != "" {
180 req.closeBody()
181 return nil, errors.New("http: Request.RequestURI can't be set in client requests.")
182 }
183
184 // Most the callers of send (Get, Post, et al) don't need
185 // Headers, leaving it uninitialized. We guarantee to the
186 // Transport that this has been initialized, though.
187 if req.Header == nil {
188 req.Header = make(Header)
189 }
190
191 if u := req.URL.User; u != nil {
192 username := u.Username()
193 password, _ := u.Password()
194 req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
195 }
196 resp, err = t.RoundTrip(req)
197 if err != nil {
198 if resp != nil {
199 log.Printf("RoundTripper returned a response & error; ignoring response")
200 }
201 return nil, err
202 }
203 return resp, nil
204 }
205
206 // See 2 (end of page 4) http://www.ietf.org/rfc/rfc2617.txt
207 // "To receive authorization, the client sends the userid and password,
208 // separated by a single colon (":") character, within a base64
209 // encoded string in the credentials."
210 // It is not meant to be urlencoded.
211 func basicAuth(username, password string) string {
212 auth := username + ":" + password
213 return base64.StdEncoding.EncodeToString([]byte(auth))
214 }
215
216 // True if the specified HTTP status code is one for which the Get utility should
217 // automatically redirect.
218 func shouldRedirectGet(statusCode int) bool {
219 switch statusCode {
220 case StatusMovedPermanently, StatusFound, StatusSeeOther, StatusTemporaryRedirect:
221 return true
222 }
223 return false
224 }
225
226 // True if the specified HTTP status code is one for which the Post utility should
227 // automatically redirect.
228 func shouldRedirectPost(statusCode int) bool {
229 switch statusCode {
230 case StatusFound, StatusSeeOther:
231 return true
232 }
233 return false
234 }
235
236 // Get issues a GET to the specified URL. If the response is one of the following
237 // redirect codes, Get follows the redirect, up to a maximum of 10 redirects:
238 //
239 // 301 (Moved Permanently)
240 // 302 (Found)
241 // 303 (See Other)
242 // 307 (Temporary Redirect)
243 //
244 // An error is returned if there were too many redirects or if there
245 // was an HTTP protocol error. A non-2xx response doesn't cause an
246 // error.
247 //
248 // When err is nil, resp always contains a non-nil resp.Body.
249 // Caller should close resp.Body when done reading from it.
250 //
251 // Get is a wrapper around DefaultClient.Get.
252 func Get(url string) (resp *Response, err error) {
253 return DefaultClient.Get(url)
254 }
255
256 // Get issues a GET to the specified URL. If the response is one of the
257 // following redirect codes, Get follows the redirect after calling the
258 // Client's CheckRedirect function.
259 //
260 // 301 (Moved Permanently)
261 // 302 (Found)
262 // 303 (See Other)
263 // 307 (Temporary Redirect)
264 //
265 // An error is returned if the Client's CheckRedirect function fails
266 // or if there was an HTTP protocol error. A non-2xx response doesn't
267 // cause an error.
268 //
269 // When err is nil, resp always contains a non-nil resp.Body.
270 // Caller should close resp.Body when done reading from it.
271 func (c *Client) Get(url string) (resp *Response, err error) {
272 req, err := NewRequest("GET", url, nil)
273 if err != nil {
274 return nil, err
275 }
276 return c.doFollowingRedirects(req, shouldRedirectGet)
277 }
278
279 func (c *Client) doFollowingRedirects(ireq *Request, shouldRedirect func(int) bool) (resp *Response, err error) {
280 var base *url.URL
281 redirectChecker := c.CheckRedirect
282 if redirectChecker == nil {
283 redirectChecker = defaultCheckRedirect
284 }
285 var via []*Request
286
287 if ireq.URL == nil {
288 ireq.closeBody()
289 return nil, errors.New("http: nil Request.URL")
290 }
291
292 var reqmu sync.Mutex // guards req
293 req := ireq
294
295 var timer *time.Timer
296 if c.Timeout > 0 {
297 type canceler interface {
298 CancelRequest(*Request)
299 }
300 tr, ok := c.transport().(canceler)
301 if !ok {
302 return nil, fmt.Errorf("net/http: Client Transport of type %T doesn't support CancelRequest; Timeout not supported", c.transport())
303 }
304 timer = time.AfterFunc(c.Timeout, func() {
305 reqmu.Lock()
306 defer reqmu.Unlock()
307 tr.CancelRequest(req)
308 })
309 }
310
311 urlStr := "" // next relative or absolute URL to fetch (after first request)
312 redirectFailed := false
313 for redirect := 0; ; redirect++ {
314 if redirect != 0 {
315 nreq := new(Request)
316 nreq.Method = ireq.Method
317 if ireq.Method == "POST" || ireq.Method == "PUT" {
318 nreq.Method = "GET"
319 }
320 nreq.Header = make(Header)
321 nreq.URL, err = base.Parse(urlStr)
322 if err != nil {
323 break
324 }
325 if len(via) > 0 {
326 // Add the Referer header.
327 lastReq := via[len(via)-1]
328 if lastReq.URL.Scheme != "https" {
329 nreq.Header.Set("Referer", lastReq.URL.String())
330 }
331
332 err = redirectChecker(nreq, via)
333 if err != nil {
334 redirectFailed = true
335 break
336 }
337 }
338 reqmu.Lock()
339 req = nreq
340 reqmu.Unlock()
341 }
342
343 urlStr = req.URL.String()
344 if resp, err = c.send(req); err != nil {
345 break
346 }
347
348 if shouldRedirect(resp.StatusCode) {
349 // Read the body if small so underlying TCP connection will be re-used.
350 // No need to check for errors: if it fails, Transport won't reuse it anyway.
351 const maxBodySlurpSize = 2 << 10
352 if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
353 io.CopyN(ioutil.Discard, resp.Body, maxBodySlurpSize)
354 }
355 resp.Body.Close()
356 if urlStr = resp.Header.Get("Location"); urlStr == "" {
357 err = errors.New(fmt.Sprintf("%d response missing Location header", resp.StatusCode))
358 break
359 }
360 base = req.URL
361 via = append(via, req)
362 continue
363 }
364 if timer != nil {
365 resp.Body = &cancelTimerBody{timer, resp.Body}
366 }
367 return resp, nil
368 }
369
370 method := ireq.Method
371 urlErr := &url.Error{
372 Op: method[0:1] + strings.ToLower(method[1:]),
373 URL: urlStr,
374 Err: err,
375 }
376
377 if redirectFailed {
378 // Special case for Go 1 compatibility: return both the response
379 // and an error if the CheckRedirect function failed.
380 // See http://golang.org/issue/3795
381 return resp, urlErr
382 }
383
384 if resp != nil {
385 resp.Body.Close()
386 }
387 return nil, urlErr
388 }
389
390 func defaultCheckRedirect(req *Request, via []*Request) error {
391 if len(via) >= 10 {
392 return errors.New("stopped after 10 redirects")
393 }
394 return nil
395 }
396
397 // Post issues a POST to the specified URL.
398 //
399 // Caller should close resp.Body when done reading from it.
400 //
401 // Post is a wrapper around DefaultClient.Post
402 func Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
403 return DefaultClient.Post(url, bodyType, body)
404 }
405
406 // Post issues a POST to the specified URL.
407 //
408 // Caller should close resp.Body when done reading from it.
409 //
410 // If the provided body is also an io.Closer, it is closed after the
411 // request.
412 func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error) {
413 req, err := NewRequest("POST", url, body)
414 if err != nil {
415 return nil, err
416 }
417 req.Header.Set("Content-Type", bodyType)
418 return c.doFollowingRedirects(req, shouldRedirectPost)
419 }
420
421 // PostForm issues a POST to the specified URL, with data's keys and
422 // values URL-encoded as the request body.
423 //
424 // When err is nil, resp always contains a non-nil resp.Body.
425 // Caller should close resp.Body when done reading from it.
426 //
427 // PostForm is a wrapper around DefaultClient.PostForm
428 func PostForm(url string, data url.Values) (resp *Response, err error) {
429 return DefaultClient.PostForm(url, data)
430 }
431
432 // PostForm issues a POST to the specified URL,
433 // with data's keys and values urlencoded as the request body.
434 //
435 // When err is nil, resp always contains a non-nil resp.Body.
436 // Caller should close resp.Body when done reading from it.
437 func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
438 return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
439 }
440
441 // Head issues a HEAD to the specified URL. If the response is one of the
442 // following redirect codes, Head follows the redirect after calling the
443 // Client's CheckRedirect function.
444 //
445 // 301 (Moved Permanently)
446 // 302 (Found)
447 // 303 (See Other)
448 // 307 (Temporary Redirect)
449 //
450 // Head is a wrapper around DefaultClient.Head
451 func Head(url string) (resp *Response, err error) {
452 return DefaultClient.Head(url)
453 }
454
455 // Head issues a HEAD to the specified URL. If the response is one of the
456 // following redirect codes, Head follows the redirect after calling the
457 // Client's CheckRedirect function.
458 //
459 // 301 (Moved Permanently)
460 // 302 (Found)
461 // 303 (See Other)
462 // 307 (Temporary Redirect)
463 func (c *Client) Head(url string) (resp *Response, err error) {
464 req, err := NewRequest("HEAD", url, nil)
465 if err != nil {
466 return nil, err
467 }
468 return c.doFollowingRedirects(req, shouldRedirectGet)
469 }
470
471 type cancelTimerBody struct {
472 t *time.Timer
473 rc io.ReadCloser
474 }
475
476 func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
477 n, err = b.rc.Read(p)
478 if err == io.EOF {
479 b.t.Stop()
480 }
481 return
482 }
483
484 func (b *cancelTimerBody) Close() error {
485 err := b.rc.Close()
486 b.t.Stop()
487 return err
488 }