http.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. // CancelableTransport 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 CancelableTransport interface {
  29. http.RoundTripper
  30. CancelRequest(req *http.Request)
  31. }
  32. type httpAction interface {
  33. httpRequest(url.URL) *http.Request
  34. }
  35. type httpActionDo interface {
  36. do(context.Context, httpAction) (*http.Response, []byte, error)
  37. }
  38. type roundTripResponse struct {
  39. resp *http.Response
  40. err error
  41. }
  42. type httpClient struct {
  43. transport CancelableTransport
  44. endpoint url.URL
  45. timeout time.Duration
  46. }
  47. func (c *httpClient) do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
  48. req := act.httpRequest(c.endpoint)
  49. rtchan := make(chan roundTripResponse, 1)
  50. go func() {
  51. resp, err := c.transport.RoundTrip(req)
  52. rtchan <- roundTripResponse{resp: resp, err: err}
  53. close(rtchan)
  54. }()
  55. var resp *http.Response
  56. var err error
  57. select {
  58. case rtresp := <-rtchan:
  59. resp, err = rtresp.resp, rtresp.err
  60. case <-ctx.Done():
  61. c.transport.CancelRequest(req)
  62. // wait for request to actually exit before continuing
  63. <-rtchan
  64. err = ctx.Err()
  65. }
  66. // always check for resp nil-ness to deal with possible
  67. // race conditions between channels above
  68. defer func() {
  69. if resp != nil {
  70. resp.Body.Close()
  71. }
  72. }()
  73. if err != nil {
  74. return nil, nil, err
  75. }
  76. body, err := ioutil.ReadAll(resp.Body)
  77. return resp, body, err
  78. }