http.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. type roundTripResponse struct {
  26. resp *http.Response
  27. err error
  28. }
  29. type httpClient struct {
  30. transport CancelableTransport
  31. endpoint url.URL
  32. }
  33. func (c *httpClient) Do(ctx context.Context, act HTTPAction) (*http.Response, []byte, error) {
  34. req := act.HTTPRequest(c.endpoint)
  35. rtchan := make(chan roundTripResponse, 1)
  36. go func() {
  37. resp, err := c.transport.RoundTrip(req)
  38. rtchan <- roundTripResponse{resp: resp, err: err}
  39. close(rtchan)
  40. }()
  41. var resp *http.Response
  42. var err error
  43. select {
  44. case rtresp := <-rtchan:
  45. resp, err = rtresp.resp, rtresp.err
  46. case <-ctx.Done():
  47. c.transport.CancelRequest(req)
  48. // wait for request to actually exit before continuing
  49. <-rtchan
  50. err = ctx.Err()
  51. }
  52. // always check for resp nil-ness to deal with possible
  53. // race conditions between channels above
  54. defer func() {
  55. if resp != nil {
  56. resp.Body.Close()
  57. }
  58. }()
  59. if err != nil {
  60. return nil, nil, err
  61. }
  62. body, err := ioutil.ReadAll(resp.Body)
  63. return resp, body, err
  64. }