client.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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. // HTTP client. See RFC 7230 through 7235.
  5. //
  6. // This is the high-level Client interface.
  7. // The low-level implementation is in transport.go.
  8. package http
  9. import (
  10. "context"
  11. "crypto/tls"
  12. "encoding/base64"
  13. "errors"
  14. "fmt"
  15. "io"
  16. "log"
  17. "net/http/internal/ascii"
  18. "net/url"
  19. "reflect"
  20. "sort"
  21. "strings"
  22. "sync"
  23. "time"
  24. )
  25. // A Client is an HTTP client. Its zero value (DefaultClient) is a
  26. // usable client that uses DefaultTransport.
  27. //
  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.
  31. //
  32. // A Client is higher-level than a RoundTripper (such as Transport)
  33. // and additionally handles HTTP details such as cookies and
  34. // redirects.
  35. //
  36. // When following redirects, the Client will forward all headers set on the
  37. // initial Request except:
  38. //
  39. // • when forwarding sensitive headers like "Authorization",
  40. // "WWW-Authenticate", and "Cookie" to untrusted targets.
  41. // These headers will be ignored when following a redirect to a domain
  42. // that is not a subdomain match or exact match of the initial domain.
  43. // For example, a redirect from "foo.com" to either "foo.com" or "sub.foo.com"
  44. // will forward the sensitive headers, but a redirect to "bar.com" will not.
  45. //
  46. // • when forwarding the "Cookie" header with a non-nil cookie Jar.
  47. // Since each redirect may mutate the state of the cookie jar,
  48. // a redirect may possibly alter a cookie set in the initial request.
  49. // When forwarding the "Cookie" header, any mutated cookies will be omitted,
  50. // with the expectation that the Jar will insert those mutated cookies
  51. // with the updated values (assuming the origin matches).
  52. // If Jar is nil, the initial cookies are forwarded without change.
  53. //
  54. type Client struct {
  55. // Transport specifies the mechanism by which individual
  56. // HTTP requests are made.
  57. // If nil, DefaultTransport is used.
  58. Transport RoundTripper
  59. // CheckRedirect specifies the policy for handling redirects.
  60. // If CheckRedirect is not nil, the client calls it before
  61. // following an HTTP redirect. The arguments req and via are
  62. // the upcoming request and the requests made already, oldest
  63. // first. If CheckRedirect returns an error, the Client's Get
  64. // method returns both the previous Response (with its Body
  65. // closed) and CheckRedirect's error (wrapped in a url.Error)
  66. // instead of issuing the Request req.
  67. // As a special case, if CheckRedirect returns ErrUseLastResponse,
  68. // then the most recent response is returned with its body
  69. // unclosed, along with a nil error.
  70. //
  71. // If CheckRedirect is nil, the Client uses its default policy,
  72. // which is to stop after 10 consecutive requests.
  73. CheckRedirect func(req *Request, via []*Request) error
  74. // Jar specifies the cookie jar.
  75. //
  76. // The Jar is used to insert relevant cookies into every
  77. // outbound Request and is updated with the cookie values
  78. // of every inbound Response. The Jar is consulted for every
  79. // redirect that the Client follows.
  80. //
  81. // If Jar is nil, cookies are only sent if they are explicitly
  82. // set on the Request.
  83. Jar CookieJar
  84. // Timeout specifies a time limit for requests made by this
  85. // Client. The timeout includes connection time, any
  86. // redirects, and reading the response body. The timer remains
  87. // running after Get, Head, Post, or Do return and will
  88. // interrupt reading of the Response.Body.
  89. //
  90. // A Timeout of zero means no timeout.
  91. //
  92. // The Client cancels requests to the underlying Transport
  93. // as if the Request's Context ended.
  94. //
  95. // For compatibility, the Client will also use the deprecated
  96. // CancelRequest method on Transport if found. New
  97. // RoundTripper implementations should use the Request's Context
  98. // for cancellation instead of implementing CancelRequest.
  99. Timeout time.Duration
  100. }
  101. // DefaultClient is the default Client and is used by Get, Head, and Post.
  102. var DefaultClient = &Client{}
  103. // RoundTripper is an interface representing the ability to execute a
  104. // single HTTP transaction, obtaining the Response for a given Request.
  105. //
  106. // A RoundTripper must be safe for concurrent use by multiple
  107. // goroutines.
  108. type RoundTripper interface {
  109. // RoundTrip executes a single HTTP transaction, returning
  110. // a Response for the provided Request.
  111. //
  112. // RoundTrip should not attempt to interpret the response. In
  113. // particular, RoundTrip must return err == nil if it obtained
  114. // a response, regardless of the response's HTTP status code.
  115. // A non-nil err should be reserved for failure to obtain a
  116. // response. Similarly, RoundTrip should not attempt to
  117. // handle higher-level protocol details such as redirects,
  118. // authentication, or cookies.
  119. //
  120. // RoundTrip should not modify the request, except for
  121. // consuming and closing the Request's Body. RoundTrip may
  122. // read fields of the request in a separate goroutine. Callers
  123. // should not mutate or reuse the request until the Response's
  124. // Body has been closed.
  125. //
  126. // RoundTrip must always close the body, including on errors,
  127. // but depending on the implementation may do so in a separate
  128. // goroutine even after RoundTrip returns. This means that
  129. // callers wanting to reuse the body for subsequent requests
  130. // must arrange to wait for the Close call before doing so.
  131. //
  132. // The Request's URL and Header fields must be initialized.
  133. RoundTrip(*Request) (*Response, error)
  134. }
  135. // refererForURL returns a referer without any authentication info or
  136. // an empty string if lastReq scheme is https and newReq scheme is http.
  137. func refererForURL(lastReq, newReq *url.URL) string {
  138. // https://tools.ietf.org/html/rfc7231#section-5.5.2
  139. // "Clients SHOULD NOT include a Referer header field in a
  140. // (non-secure) HTTP request if the referring page was
  141. // transferred with a secure protocol."
  142. if lastReq.Scheme == "https" && newReq.Scheme == "http" {
  143. return ""
  144. }
  145. referer := lastReq.String()
  146. if lastReq.User != nil {
  147. // This is not very efficient, but is the best we can
  148. // do without:
  149. // - introducing a new method on URL
  150. // - creating a race condition
  151. // - copying the URL struct manually, which would cause
  152. // maintenance problems down the line
  153. auth := lastReq.User.String() + "@"
  154. referer = strings.Replace(referer, auth, "", 1)
  155. }
  156. return referer
  157. }
  158. // didTimeout is non-nil only if err != nil.
  159. func (c *Client) send(req *Request, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
  160. if c.Jar != nil {
  161. for _, cookie := range c.Jar.Cookies(req.URL) {
  162. req.AddCookie(cookie)
  163. }
  164. }
  165. resp, didTimeout, err = send(req, c.transport(), deadline)
  166. if err != nil {
  167. return nil, didTimeout, err
  168. }
  169. if c.Jar != nil {
  170. if rc := resp.Cookies(); len(rc) > 0 {
  171. c.Jar.SetCookies(req.URL, rc)
  172. }
  173. }
  174. return resp, nil, nil
  175. }
  176. func (c *Client) deadline() time.Time {
  177. if c.Timeout > 0 {
  178. return time.Now().Add(c.Timeout)
  179. }
  180. return time.Time{}
  181. }
  182. func (c *Client) transport() RoundTripper {
  183. if c.Transport != nil {
  184. return c.Transport
  185. }
  186. return DefaultTransport
  187. }
  188. // send issues an HTTP request.
  189. // Caller should close resp.Body when done reading from it.
  190. func send(ireq *Request, rt RoundTripper, deadline time.Time) (resp *Response, didTimeout func() bool, err error) {
  191. req := ireq // req is either the original request, or a modified fork
  192. if rt == nil {
  193. req.closeBody()
  194. return nil, alwaysFalse, errors.New("http: no Client.Transport or DefaultTransport")
  195. }
  196. if req.URL == nil {
  197. req.closeBody()
  198. return nil, alwaysFalse, errors.New("http: nil Request.URL")
  199. }
  200. if req.RequestURI != "" {
  201. req.closeBody()
  202. return nil, alwaysFalse, errors.New("http: Request.RequestURI can't be set in client requests")
  203. }
  204. // forkReq forks req into a shallow clone of ireq the first
  205. // time it's called.
  206. forkReq := func() {
  207. if ireq == req {
  208. req = new(Request)
  209. *req = *ireq // shallow clone
  210. }
  211. }
  212. // Most the callers of send (Get, Post, et al) don't need
  213. // Headers, leaving it uninitialized. We guarantee to the
  214. // Transport that this has been initialized, though.
  215. if req.Header == nil {
  216. forkReq()
  217. req.Header = make(Header)
  218. }
  219. if u := req.URL.User; u != nil && req.Header.Get("Authorization") == "" {
  220. username := u.Username()
  221. password, _ := u.Password()
  222. forkReq()
  223. req.Header = cloneOrMakeHeader(ireq.Header)
  224. req.Header.Set("Authorization", "Basic "+basicAuth(username, password))
  225. }
  226. if !deadline.IsZero() {
  227. forkReq()
  228. }
  229. stopTimer, didTimeout := setRequestCancel(req, rt, deadline)
  230. resp, err = rt.RoundTrip(req)
  231. if err != nil {
  232. stopTimer()
  233. if resp != nil {
  234. log.Printf("RoundTripper returned a response & error; ignoring response")
  235. }
  236. if tlsErr, ok := err.(tls.RecordHeaderError); ok {
  237. // If we get a bad TLS record header, check to see if the
  238. // response looks like HTTP and give a more helpful error.
  239. // See golang.org/issue/11111.
  240. if string(tlsErr.RecordHeader[:]) == "HTTP/" {
  241. err = errors.New("http: server gave HTTP response to HTTPS client")
  242. }
  243. }
  244. return nil, didTimeout, err
  245. }
  246. if resp == nil {
  247. return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a nil *Response with a nil error", rt)
  248. }
  249. if resp.Body == nil {
  250. // The documentation on the Body field says “The http Client and Transport
  251. // guarantee that Body is always non-nil, even on responses without a body
  252. // or responses with a zero-length body.” Unfortunately, we didn't document
  253. // that same constraint for arbitrary RoundTripper implementations, and
  254. // RoundTripper implementations in the wild (mostly in tests) assume that
  255. // they can use a nil Body to mean an empty one (similar to Request.Body).
  256. // (See https://golang.org/issue/38095.)
  257. //
  258. // If the ContentLength allows the Body to be empty, fill in an empty one
  259. // here to ensure that it is non-nil.
  260. if resp.ContentLength > 0 && req.Method != "HEAD" {
  261. return nil, didTimeout, fmt.Errorf("http: RoundTripper implementation (%T) returned a *Response with content length %d but a nil Body", rt, resp.ContentLength)
  262. }
  263. resp.Body = io.NopCloser(strings.NewReader(""))
  264. }
  265. if !deadline.IsZero() {
  266. resp.Body = &cancelTimerBody{
  267. stop: stopTimer,
  268. rc: resp.Body,
  269. reqDidTimeout: didTimeout,
  270. }
  271. }
  272. return resp, nil, nil
  273. }
  274. // timeBeforeContextDeadline reports whether the non-zero Time t is
  275. // before ctx's deadline, if any. If ctx does not have a deadline, it
  276. // always reports true (the deadline is considered infinite).
  277. func timeBeforeContextDeadline(t time.Time, ctx context.Context) bool {
  278. d, ok := ctx.Deadline()
  279. if !ok {
  280. return true
  281. }
  282. return t.Before(d)
  283. }
  284. // knownRoundTripperImpl reports whether rt is a RoundTripper that's
  285. // maintained by the Go team and known to implement the latest
  286. // optional semantics (notably contexts). The Request is used
  287. // to check whether this particular request is using an alternate protocol,
  288. // in which case we need to check the RoundTripper for that protocol.
  289. func knownRoundTripperImpl(rt RoundTripper, req *Request) bool {
  290. switch t := rt.(type) {
  291. case *Transport:
  292. if altRT := t.alternateRoundTripper(req); altRT != nil {
  293. return knownRoundTripperImpl(altRT, req)
  294. }
  295. return true
  296. case *http2Transport, http2noDialH2RoundTripper:
  297. return true
  298. }
  299. // There's a very minor chance of a false positive with this.
  300. // Instead of detecting our golang.org/x/net/http2.Transport,
  301. // it might detect a Transport type in a different http2
  302. // package. But I know of none, and the only problem would be
  303. // some temporarily leaked goroutines if the transport didn't
  304. // support contexts. So this is a good enough heuristic:
  305. if reflect.TypeOf(rt).String() == "*http2.Transport" {
  306. return true
  307. }
  308. return false
  309. }
  310. // setRequestCancel sets req.Cancel and adds a deadline context to req
  311. // if deadline is non-zero. The RoundTripper's type is used to
  312. // determine whether the legacy CancelRequest behavior should be used.
  313. //
  314. // As background, there are three ways to cancel a request:
  315. // First was Transport.CancelRequest. (deprecated)
  316. // Second was Request.Cancel.
  317. // Third was Request.Context.
  318. // This function populates the second and third, and uses the first if it really needs to.
  319. func setRequestCancel(req *Request, rt RoundTripper, deadline time.Time) (stopTimer func(), didTimeout func() bool) {
  320. if deadline.IsZero() {
  321. return nop, alwaysFalse
  322. }
  323. knownTransport := knownRoundTripperImpl(rt, req)
  324. oldCtx := req.Context()
  325. if req.Cancel == nil && knownTransport {
  326. // If they already had a Request.Context that's
  327. // expiring sooner, do nothing:
  328. if !timeBeforeContextDeadline(deadline, oldCtx) {
  329. return nop, alwaysFalse
  330. }
  331. var cancelCtx func()
  332. req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
  333. return cancelCtx, func() bool { return time.Now().After(deadline) }
  334. }
  335. initialReqCancel := req.Cancel // the user's original Request.Cancel, if any
  336. var cancelCtx func()
  337. if oldCtx := req.Context(); timeBeforeContextDeadline(deadline, oldCtx) {
  338. req.ctx, cancelCtx = context.WithDeadline(oldCtx, deadline)
  339. }
  340. cancel := make(chan struct{})
  341. req.Cancel = cancel
  342. doCancel := func() {
  343. // The second way in the func comment above:
  344. close(cancel)
  345. // The first way, used only for RoundTripper
  346. // implementations written before Go 1.5 or Go 1.6.
  347. type canceler interface{ CancelRequest(*Request) }
  348. if v, ok := rt.(canceler); ok {
  349. v.CancelRequest(req)
  350. }
  351. }
  352. stopTimerCh := make(chan struct{})
  353. var once sync.Once
  354. stopTimer = func() {
  355. once.Do(func() {
  356. close(stopTimerCh)
  357. if cancelCtx != nil {
  358. cancelCtx()
  359. }
  360. })
  361. }
  362. timer := time.NewTimer(time.Until(deadline))
  363. var timedOut atomicBool
  364. go func() {
  365. select {
  366. case <-initialReqCancel:
  367. doCancel()
  368. timer.Stop()
  369. case <-timer.C:
  370. timedOut.setTrue()
  371. doCancel()
  372. case <-stopTimerCh:
  373. timer.Stop()
  374. }
  375. }()
  376. return stopTimer, timedOut.isSet
  377. }
  378. // See 2 (end of page 4) https://www.ietf.org/rfc/rfc2617.txt
  379. // "To receive authorization, the client sends the userid and password,
  380. // separated by a single colon (":") character, within a base64
  381. // encoded string in the credentials."
  382. // It is not meant to be urlencoded.
  383. func basicAuth(username, password string) string {
  384. auth := username + ":" + password
  385. return base64.StdEncoding.EncodeToString([]byte(auth))
  386. }
  387. // Get issues a GET to the specified URL. If the response is one of
  388. // the following redirect codes, Get follows the redirect, up to a
  389. // maximum of 10 redirects:
  390. //
  391. // 301 (Moved Permanently)
  392. // 302 (Found)
  393. // 303 (See Other)
  394. // 307 (Temporary Redirect)
  395. // 308 (Permanent Redirect)
  396. //
  397. // An error is returned if there were too many redirects or if there
  398. // was an HTTP protocol error. A non-2xx response doesn't cause an
  399. // error. Any returned error will be of type *url.Error. The url.Error
  400. // value's Timeout method will report true if the request timed out.
  401. //
  402. // When err is nil, resp always contains a non-nil resp.Body.
  403. // Caller should close resp.Body when done reading from it.
  404. //
  405. // Get is a wrapper around DefaultClient.Get.
  406. //
  407. // To make a request with custom headers, use NewRequest and
  408. // DefaultClient.Do.
  409. //
  410. // To make a request with a specified context.Context, use NewRequestWithContext
  411. // and DefaultClient.Do.
  412. func Get(url string) (resp *Response, err error) {
  413. return DefaultClient.Get(url)
  414. }
  415. // Get issues a GET to the specified URL. If the response is one of the
  416. // following redirect codes, Get follows the redirect after calling the
  417. // Client's CheckRedirect function:
  418. //
  419. // 301 (Moved Permanently)
  420. // 302 (Found)
  421. // 303 (See Other)
  422. // 307 (Temporary Redirect)
  423. // 308 (Permanent Redirect)
  424. //
  425. // An error is returned if the Client's CheckRedirect function fails
  426. // or if there was an HTTP protocol error. A non-2xx response doesn't
  427. // cause an error. Any returned error will be of type *url.Error. The
  428. // url.Error value's Timeout method will report true if the request
  429. // timed out.
  430. //
  431. // When err is nil, resp always contains a non-nil resp.Body.
  432. // Caller should close resp.Body when done reading from it.
  433. //
  434. // To make a request with custom headers, use NewRequest and Client.Do.
  435. //
  436. // To make a request with a specified context.Context, use NewRequestWithContext
  437. // and Client.Do.
  438. func (c *Client) Get(url string) (resp *Response, err error) {
  439. req, err := NewRequest("GET", url, nil)
  440. if err != nil {
  441. return nil, err
  442. }
  443. return c.Do(req)
  444. }
  445. func alwaysFalse() bool { return false }
  446. // ErrUseLastResponse can be returned by Client.CheckRedirect hooks to
  447. // control how redirects are processed. If returned, the next request
  448. // is not sent and the most recent response is returned with its body
  449. // unclosed.
  450. var ErrUseLastResponse = errors.New("net/http: use last response")
  451. // checkRedirect calls either the user's configured CheckRedirect
  452. // function, or the default.
  453. func (c *Client) checkRedirect(req *Request, via []*Request) error {
  454. fn := c.CheckRedirect
  455. if fn == nil {
  456. fn = defaultCheckRedirect
  457. }
  458. return fn(req, via)
  459. }
  460. // redirectBehavior describes what should happen when the
  461. // client encounters a 3xx status code from the server
  462. func redirectBehavior(reqMethod string, resp *Response, ireq *Request) (redirectMethod string, shouldRedirect, includeBody bool) {
  463. switch resp.StatusCode {
  464. case 301, 302, 303:
  465. redirectMethod = reqMethod
  466. shouldRedirect = true
  467. includeBody = false
  468. // RFC 2616 allowed automatic redirection only with GET and
  469. // HEAD requests. RFC 7231 lifts this restriction, but we still
  470. // restrict other methods to GET to maintain compatibility.
  471. // See Issue 18570.
  472. if reqMethod != "GET" && reqMethod != "HEAD" {
  473. redirectMethod = "GET"
  474. }
  475. case 307, 308:
  476. redirectMethod = reqMethod
  477. shouldRedirect = true
  478. includeBody = true
  479. // Treat 307 and 308 specially, since they're new in
  480. // Go 1.8, and they also require re-sending the request body.
  481. if resp.Header.Get("Location") == "" {
  482. // 308s have been observed in the wild being served
  483. // without Location headers. Since Go 1.7 and earlier
  484. // didn't follow these codes, just stop here instead
  485. // of returning an error.
  486. // See Issue 17773.
  487. shouldRedirect = false
  488. break
  489. }
  490. if ireq.GetBody == nil && ireq.outgoingLength() != 0 {
  491. // We had a request body, and 307/308 require
  492. // re-sending it, but GetBody is not defined. So just
  493. // return this response to the user instead of an
  494. // error, like we did in Go 1.7 and earlier.
  495. shouldRedirect = false
  496. }
  497. }
  498. return redirectMethod, shouldRedirect, includeBody
  499. }
  500. // urlErrorOp returns the (*url.Error).Op value to use for the
  501. // provided (*Request).Method value.
  502. func urlErrorOp(method string) string {
  503. if method == "" {
  504. return "Get"
  505. }
  506. if lowerMethod, ok := ascii.ToLower(method); ok {
  507. return method[:1] + lowerMethod[1:]
  508. }
  509. return method
  510. }
  511. // Do sends an HTTP request and returns an HTTP response, following
  512. // policy (such as redirects, cookies, auth) as configured on the
  513. // client.
  514. //
  515. // An error is returned if caused by client policy (such as
  516. // CheckRedirect), or failure to speak HTTP (such as a network
  517. // connectivity problem). A non-2xx status code doesn't cause an
  518. // error.
  519. //
  520. // If the returned error is nil, the Response will contain a non-nil
  521. // Body which the user is expected to close. If the Body is not both
  522. // read to EOF and closed, the Client's underlying RoundTripper
  523. // (typically Transport) may not be able to re-use a persistent TCP
  524. // connection to the server for a subsequent "keep-alive" request.
  525. //
  526. // The request Body, if non-nil, will be closed by the underlying
  527. // Transport, even on errors.
  528. //
  529. // On error, any Response can be ignored. A non-nil Response with a
  530. // non-nil error only occurs when CheckRedirect fails, and even then
  531. // the returned Response.Body is already closed.
  532. //
  533. // Generally Get, Post, or PostForm will be used instead of Do.
  534. //
  535. // If the server replies with a redirect, the Client first uses the
  536. // CheckRedirect function to determine whether the redirect should be
  537. // followed. If permitted, a 301, 302, or 303 redirect causes
  538. // subsequent requests to use HTTP method GET
  539. // (or HEAD if the original request was HEAD), with no body.
  540. // A 307 or 308 redirect preserves the original HTTP method and body,
  541. // provided that the Request.GetBody function is defined.
  542. // The NewRequest function automatically sets GetBody for common
  543. // standard library body types.
  544. //
  545. // Any returned error will be of type *url.Error. The url.Error
  546. // value's Timeout method will report true if the request timed out.
  547. func (c *Client) Do(req *Request) (*Response, error) {
  548. return c.do(req)
  549. }
  550. var testHookClientDoResult func(retres *Response, reterr error)
  551. func (c *Client) do(req *Request) (retres *Response, reterr error) {
  552. if testHookClientDoResult != nil {
  553. defer func() { testHookClientDoResult(retres, reterr) }()
  554. }
  555. if req.URL == nil {
  556. req.closeBody()
  557. return nil, &url.Error{
  558. Op: urlErrorOp(req.Method),
  559. Err: errors.New("http: nil Request.URL"),
  560. }
  561. }
  562. var (
  563. deadline = c.deadline()
  564. reqs []*Request
  565. resp *Response
  566. copyHeaders = c.makeHeadersCopier(req)
  567. reqBodyClosed = false // have we closed the current req.Body?
  568. // Redirect behavior:
  569. redirectMethod string
  570. includeBody bool
  571. )
  572. uerr := func(err error) error {
  573. // the body may have been closed already by c.send()
  574. if !reqBodyClosed {
  575. req.closeBody()
  576. }
  577. var urlStr string
  578. if resp != nil && resp.Request != nil {
  579. urlStr = stripPassword(resp.Request.URL)
  580. } else {
  581. urlStr = stripPassword(req.URL)
  582. }
  583. return &url.Error{
  584. Op: urlErrorOp(reqs[0].Method),
  585. URL: urlStr,
  586. Err: err,
  587. }
  588. }
  589. for {
  590. // For all but the first request, create the next
  591. // request hop and replace req.
  592. if len(reqs) > 0 {
  593. loc := resp.Header.Get("Location")
  594. if loc == "" {
  595. resp.closeBody()
  596. return nil, uerr(fmt.Errorf("%d response missing Location header", resp.StatusCode))
  597. }
  598. u, err := req.URL.Parse(loc)
  599. if err != nil {
  600. resp.closeBody()
  601. return nil, uerr(fmt.Errorf("failed to parse Location header %q: %v", loc, err))
  602. }
  603. host := ""
  604. if req.Host != "" && req.Host != req.URL.Host {
  605. // If the caller specified a custom Host header and the
  606. // redirect location is relative, preserve the Host header
  607. // through the redirect. See issue #22233.
  608. if u, _ := url.Parse(loc); u != nil && !u.IsAbs() {
  609. host = req.Host
  610. }
  611. }
  612. ireq := reqs[0]
  613. req = &Request{
  614. Method: redirectMethod,
  615. Response: resp,
  616. URL: u,
  617. Header: make(Header),
  618. Host: host,
  619. Cancel: ireq.Cancel,
  620. ctx: ireq.ctx,
  621. }
  622. if includeBody && ireq.GetBody != nil {
  623. req.Body, err = ireq.GetBody()
  624. if err != nil {
  625. resp.closeBody()
  626. return nil, uerr(err)
  627. }
  628. req.ContentLength = ireq.ContentLength
  629. }
  630. // Copy original headers before setting the Referer,
  631. // in case the user set Referer on their first request.
  632. // If they really want to override, they can do it in
  633. // their CheckRedirect func.
  634. copyHeaders(req)
  635. // Add the Referer header from the most recent
  636. // request URL to the new one, if it's not https->http:
  637. if ref := refererForURL(reqs[len(reqs)-1].URL, req.URL); ref != "" {
  638. req.Header.Set("Referer", ref)
  639. }
  640. err = c.checkRedirect(req, reqs)
  641. // Sentinel error to let users select the
  642. // previous response, without closing its
  643. // body. See Issue 10069.
  644. if err == ErrUseLastResponse {
  645. return resp, nil
  646. }
  647. // Close the previous response's body. But
  648. // read at least some of the body so if it's
  649. // small the underlying TCP connection will be
  650. // re-used. No need to check for errors: if it
  651. // fails, the Transport won't reuse it anyway.
  652. const maxBodySlurpSize = 2 << 10
  653. if resp.ContentLength == -1 || resp.ContentLength <= maxBodySlurpSize {
  654. io.CopyN(io.Discard, resp.Body, maxBodySlurpSize)
  655. }
  656. resp.Body.Close()
  657. if err != nil {
  658. // Special case for Go 1 compatibility: return both the response
  659. // and an error if the CheckRedirect function failed.
  660. // See https://golang.org/issue/3795
  661. // The resp.Body has already been closed.
  662. ue := uerr(err)
  663. ue.(*url.Error).URL = loc
  664. return resp, ue
  665. }
  666. }
  667. reqs = append(reqs, req)
  668. var err error
  669. var didTimeout func() bool
  670. if resp, didTimeout, err = c.send(req, deadline); err != nil {
  671. // c.send() always closes req.Body
  672. reqBodyClosed = true
  673. if !deadline.IsZero() && didTimeout() {
  674. err = &httpError{
  675. err: err.Error() + " (Client.Timeout exceeded while awaiting headers)",
  676. timeout: true,
  677. }
  678. }
  679. return nil, uerr(err)
  680. }
  681. var shouldRedirect bool
  682. redirectMethod, shouldRedirect, includeBody = redirectBehavior(req.Method, resp, reqs[0])
  683. if !shouldRedirect {
  684. return resp, nil
  685. }
  686. req.closeBody()
  687. }
  688. }
  689. // makeHeadersCopier makes a function that copies headers from the
  690. // initial Request, ireq. For every redirect, this function must be called
  691. // so that it can copy headers into the upcoming Request.
  692. func (c *Client) makeHeadersCopier(ireq *Request) func(*Request) {
  693. // The headers to copy are from the very initial request.
  694. // We use a closured callback to keep a reference to these original headers.
  695. var (
  696. ireqhdr = cloneOrMakeHeader(ireq.Header)
  697. icookies map[string][]*Cookie
  698. )
  699. if c.Jar != nil && ireq.Header.Get("Cookie") != "" {
  700. icookies = make(map[string][]*Cookie)
  701. for _, c := range ireq.Cookies() {
  702. icookies[c.Name] = append(icookies[c.Name], c)
  703. }
  704. }
  705. preq := ireq // The previous request
  706. return func(req *Request) {
  707. // If Jar is present and there was some initial cookies provided
  708. // via the request header, then we may need to alter the initial
  709. // cookies as we follow redirects since each redirect may end up
  710. // modifying a pre-existing cookie.
  711. //
  712. // Since cookies already set in the request header do not contain
  713. // information about the original domain and path, the logic below
  714. // assumes any new set cookies override the original cookie
  715. // regardless of domain or path.
  716. //
  717. // See https://golang.org/issue/17494
  718. if c.Jar != nil && icookies != nil {
  719. var changed bool
  720. resp := req.Response // The response that caused the upcoming redirect
  721. for _, c := range resp.Cookies() {
  722. if _, ok := icookies[c.Name]; ok {
  723. delete(icookies, c.Name)
  724. changed = true
  725. }
  726. }
  727. if changed {
  728. ireqhdr.Del("Cookie")
  729. var ss []string
  730. for _, cs := range icookies {
  731. for _, c := range cs {
  732. ss = append(ss, c.Name+"="+c.Value)
  733. }
  734. }
  735. sort.Strings(ss) // Ensure deterministic headers
  736. ireqhdr.Set("Cookie", strings.Join(ss, "; "))
  737. }
  738. }
  739. // Copy the initial request's Header values
  740. // (at least the safe ones).
  741. for k, vv := range ireqhdr {
  742. if shouldCopyHeaderOnRedirect(k, preq.URL, req.URL) {
  743. req.Header[k] = vv
  744. }
  745. }
  746. preq = req // Update previous Request with the current request
  747. }
  748. }
  749. func defaultCheckRedirect(req *Request, via []*Request) error {
  750. if len(via) >= 10 {
  751. return errors.New("stopped after 10 redirects")
  752. }
  753. return nil
  754. }
  755. // Post issues a POST to the specified URL.
  756. //
  757. // Caller should close resp.Body when done reading from it.
  758. //
  759. // If the provided body is an io.Closer, it is closed after the
  760. // request.
  761. //
  762. // Post is a wrapper around DefaultClient.Post.
  763. //
  764. // To set custom headers, use NewRequest and DefaultClient.Do.
  765. //
  766. // See the Client.Do method documentation for details on how redirects
  767. // are handled.
  768. //
  769. // To make a request with a specified context.Context, use NewRequestWithContext
  770. // and DefaultClient.Do.
  771. func Post(url, contentType string, body io.Reader) (resp *Response, err error) {
  772. return DefaultClient.Post(url, contentType, body)
  773. }
  774. // Post issues a POST to the specified URL.
  775. //
  776. // Caller should close resp.Body when done reading from it.
  777. //
  778. // If the provided body is an io.Closer, it is closed after the
  779. // request.
  780. //
  781. // To set custom headers, use NewRequest and Client.Do.
  782. //
  783. // To make a request with a specified context.Context, use NewRequestWithContext
  784. // and Client.Do.
  785. //
  786. // See the Client.Do method documentation for details on how redirects
  787. // are handled.
  788. func (c *Client) Post(url, contentType string, body io.Reader) (resp *Response, err error) {
  789. req, err := NewRequest("POST", url, body)
  790. if err != nil {
  791. return nil, err
  792. }
  793. req.Header.Set("Content-Type", contentType)
  794. return c.Do(req)
  795. }
  796. // PostForm issues a POST to the specified URL, with data's keys and
  797. // values URL-encoded as the request body.
  798. //
  799. // The Content-Type header is set to application/x-www-form-urlencoded.
  800. // To set other headers, use NewRequest and DefaultClient.Do.
  801. //
  802. // When err is nil, resp always contains a non-nil resp.Body.
  803. // Caller should close resp.Body when done reading from it.
  804. //
  805. // PostForm is a wrapper around DefaultClient.PostForm.
  806. //
  807. // See the Client.Do method documentation for details on how redirects
  808. // are handled.
  809. //
  810. // To make a request with a specified context.Context, use NewRequestWithContext
  811. // and DefaultClient.Do.
  812. func PostForm(url string, data url.Values) (resp *Response, err error) {
  813. return DefaultClient.PostForm(url, data)
  814. }
  815. // PostForm issues a POST to the specified URL,
  816. // with data's keys and values URL-encoded as the request body.
  817. //
  818. // The Content-Type header is set to application/x-www-form-urlencoded.
  819. // To set other headers, use NewRequest and Client.Do.
  820. //
  821. // When err is nil, resp always contains a non-nil resp.Body.
  822. // Caller should close resp.Body when done reading from it.
  823. //
  824. // See the Client.Do method documentation for details on how redirects
  825. // are handled.
  826. //
  827. // To make a request with a specified context.Context, use NewRequestWithContext
  828. // and Client.Do.
  829. func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error) {
  830. return c.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  831. }
  832. // Head issues a HEAD to the specified URL. If the response is one of
  833. // the following redirect codes, Head follows the redirect, up to a
  834. // maximum of 10 redirects:
  835. //
  836. // 301 (Moved Permanently)
  837. // 302 (Found)
  838. // 303 (See Other)
  839. // 307 (Temporary Redirect)
  840. // 308 (Permanent Redirect)
  841. //
  842. // Head is a wrapper around DefaultClient.Head
  843. //
  844. // To make a request with a specified context.Context, use NewRequestWithContext
  845. // and DefaultClient.Do.
  846. func Head(url string) (resp *Response, err error) {
  847. return DefaultClient.Head(url)
  848. }
  849. // Head issues a HEAD to the specified URL. If the response is one of the
  850. // following redirect codes, Head follows the redirect after calling the
  851. // Client's CheckRedirect function:
  852. //
  853. // 301 (Moved Permanently)
  854. // 302 (Found)
  855. // 303 (See Other)
  856. // 307 (Temporary Redirect)
  857. // 308 (Permanent Redirect)
  858. //
  859. // To make a request with a specified context.Context, use NewRequestWithContext
  860. // and Client.Do.
  861. func (c *Client) Head(url string) (resp *Response, err error) {
  862. req, err := NewRequest("HEAD", url, nil)
  863. if err != nil {
  864. return nil, err
  865. }
  866. return c.Do(req)
  867. }
  868. // CloseIdleConnections closes any connections on its Transport which
  869. // were previously connected from previous requests but are now
  870. // sitting idle in a "keep-alive" state. It does not interrupt any
  871. // connections currently in use.
  872. //
  873. // If the Client's Transport does not have a CloseIdleConnections method
  874. // then this method does nothing.
  875. func (c *Client) CloseIdleConnections() {
  876. type closeIdler interface {
  877. CloseIdleConnections()
  878. }
  879. if tr, ok := c.transport().(closeIdler); ok {
  880. tr.CloseIdleConnections()
  881. }
  882. }
  883. // cancelTimerBody is an io.ReadCloser that wraps rc with two features:
  884. // 1) On Read error or close, the stop func is called.
  885. // 2) On Read failure, if reqDidTimeout is true, the error is wrapped and
  886. // marked as net.Error that hit its timeout.
  887. type cancelTimerBody struct {
  888. stop func() // stops the time.Timer waiting to cancel the request
  889. rc io.ReadCloser
  890. reqDidTimeout func() bool
  891. }
  892. func (b *cancelTimerBody) Read(p []byte) (n int, err error) {
  893. n, err = b.rc.Read(p)
  894. if err == nil {
  895. return n, nil
  896. }
  897. if err == io.EOF {
  898. return n, err
  899. }
  900. if b.reqDidTimeout() {
  901. err = &httpError{
  902. err: err.Error() + " (Client.Timeout or context cancellation while reading body)",
  903. timeout: true,
  904. }
  905. }
  906. return n, err
  907. }
  908. func (b *cancelTimerBody) Close() error {
  909. err := b.rc.Close()
  910. b.stop()
  911. return err
  912. }
  913. func shouldCopyHeaderOnRedirect(headerKey string, initial, dest *url.URL) bool {
  914. switch CanonicalHeaderKey(headerKey) {
  915. case "Authorization", "Www-Authenticate", "Cookie", "Cookie2":
  916. // Permit sending auth/cookie headers from "foo.com"
  917. // to "sub.foo.com".
  918. // Note that we don't send all cookies to subdomains
  919. // automatically. This function is only used for
  920. // Cookies set explicitly on the initial outgoing
  921. // client request. Cookies automatically added via the
  922. // CookieJar mechanism continue to follow each
  923. // cookie's scope as set by Set-Cookie. But for
  924. // outgoing requests with the Cookie header set
  925. // directly, we don't know their scope, so we assume
  926. // it's for *.domain.com.
  927. ihost := canonicalAddr(initial)
  928. dhost := canonicalAddr(dest)
  929. return isDomainOrSubdomain(dhost, ihost)
  930. }
  931. // All other headers are copied:
  932. return true
  933. }
  934. // isDomainOrSubdomain reports whether sub is a subdomain (or exact
  935. // match) of the parent domain.
  936. //
  937. // Both domains must already be in canonical form.
  938. func isDomainOrSubdomain(sub, parent string) bool {
  939. if sub == parent {
  940. return true
  941. }
  942. // If sub is "foo.example.com" and parent is "example.com",
  943. // that means sub must end in "."+parent.
  944. // Do it without allocating.
  945. if !strings.HasSuffix(sub, parent) {
  946. return false
  947. }
  948. return sub[len(sub)-len(parent)-1] == '.'
  949. }
  950. func stripPassword(u *url.URL) string {
  951. _, passSet := u.User.Password()
  952. if passSet {
  953. return strings.Replace(u.String(), u.User.String()+"@", u.User.Username()+":***@", 1)
  954. }
  955. return u.String()
  956. }