http.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package client
  14. import (
  15. "io/ioutil"
  16. "net/http"
  17. "net/url"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  20. )
  21. var (
  22. ErrTimeout = context.DeadlineExceeded
  23. DefaultRequestTimeout = 5 * time.Second
  24. )
  25. // transport mimics http.Transport to provide an interface which can be
  26. // substituted for testing (since the RoundTripper interface alone does not
  27. // require the CancelRequest method)
  28. type transport interface {
  29. http.RoundTripper
  30. CancelRequest(req *http.Request)
  31. }
  32. type httpAction interface {
  33. httpRequest(url.URL) *http.Request
  34. }
  35. type roundTripResponse struct {
  36. resp *http.Response
  37. err error
  38. }
  39. type httpClient struct {
  40. transport transport
  41. endpoint url.URL
  42. timeout time.Duration
  43. }
  44. func (c *httpClient) doWithTimeout(act httpAction) (int, []byte, error) {
  45. ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
  46. defer cancel()
  47. return c.do(ctx, act)
  48. }
  49. func (c *httpClient) do(ctx context.Context, act httpAction) (int, []byte, error) {
  50. req := act.httpRequest(c.endpoint)
  51. rtchan := make(chan roundTripResponse, 1)
  52. go func() {
  53. resp, err := c.transport.RoundTrip(req)
  54. rtchan <- roundTripResponse{resp: resp, err: err}
  55. close(rtchan)
  56. }()
  57. var resp *http.Response
  58. var err error
  59. select {
  60. case rtresp := <-rtchan:
  61. resp, err = rtresp.resp, rtresp.err
  62. case <-ctx.Done():
  63. c.transport.CancelRequest(req)
  64. // wait for request to actually exit before continuing
  65. <-rtchan
  66. err = ctx.Err()
  67. }
  68. // always check for resp nil-ness to deal with possible
  69. // race conditions between channels above
  70. defer func() {
  71. if resp != nil {
  72. resp.Body.Close()
  73. }
  74. }()
  75. if err != nil {
  76. return 0, nil, err
  77. }
  78. body, err := ioutil.ReadAll(resp.Body)
  79. return resp.StatusCode, body, err
  80. }