client.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. "net/http"
  16. "net/url"
  17. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  18. )
  19. type HTTPClient interface {
  20. Do(context.Context, HTTPAction) (*http.Response, []byte, error)
  21. Sync() error
  22. }
  23. type httpActionDo interface {
  24. Do(context.Context, HTTPAction) (*http.Response, []byte, error)
  25. }
  26. type HTTPAction interface {
  27. HTTPRequest(url.URL) *http.Request
  28. }
  29. // CancelableTransport mimics http.Transport to provide an interface which can be
  30. // substituted for testing (since the RoundTripper interface alone does not
  31. // require the CancelRequest method)
  32. type CancelableTransport interface {
  33. http.RoundTripper
  34. CancelRequest(req *http.Request)
  35. }
  36. func NewHTTPClient(tr CancelableTransport, eps []string) (*httpClusterClient, error) {
  37. c := httpClusterClient{
  38. transport: tr,
  39. endpoints: make([]httpActionDo, len(eps)),
  40. }
  41. for i, ep := range eps {
  42. u, err := url.Parse(ep)
  43. if err != nil {
  44. return nil, err
  45. }
  46. c.endpoints[i] = &httpClient{
  47. transport: tr,
  48. endpoint: *u,
  49. }
  50. }
  51. return &c, nil
  52. }
  53. type httpClusterClient struct {
  54. transport CancelableTransport
  55. endpoints []httpActionDo
  56. }
  57. func (c *httpClusterClient) Do(ctx context.Context, act HTTPAction) (*http.Response, []byte, error) {
  58. //TODO(bcwaldon): introduce retry logic so all endpoints are attempted
  59. return c.endpoints[0].Do(ctx, act)
  60. }
  61. func (c *httpClusterClient) Sync(ctx context.Context) error {
  62. mAPI := NewMembersAPI(c)
  63. ms, err := mAPI.List(ctx)
  64. if err != nil {
  65. return err
  66. }
  67. eps := make([]string, 0)
  68. for _, m := range ms {
  69. eps = append(eps, m.ClientURLs...)
  70. }
  71. nc, err := NewHTTPClient(c.transport, eps)
  72. if err != nil {
  73. return err
  74. }
  75. *c = *nc
  76. return nil
  77. }