v2_util.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package etcd
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. )
  11. type testHttpClient struct {
  12. *http.Client
  13. }
  14. // Creates a new HTTP client with KeepAlive disabled.
  15. func NewTestClient() *testHttpClient {
  16. return &testHttpClient{&http.Client{Transport: &http.Transport{DisableKeepAlives: true}}}
  17. }
  18. // Reads the body from the response and closes it.
  19. func (t *testHttpClient) ReadBody(resp *http.Response) []byte {
  20. if resp == nil {
  21. return []byte{}
  22. }
  23. body, _ := ioutil.ReadAll(resp.Body)
  24. resp.Body.Close()
  25. return body
  26. }
  27. // Reads the body from the response and parses it as JSON.
  28. func (t *testHttpClient) ReadBodyJSON(resp *http.Response) map[string]interface{} {
  29. m := make(map[string]interface{})
  30. b := t.ReadBody(resp)
  31. if err := json.Unmarshal(b, &m); err != nil {
  32. panic(fmt.Sprintf("HTTP body JSON parse error: %v: %s", err, string(b)))
  33. }
  34. return m
  35. }
  36. func (t *testHttpClient) Head(url string) (*http.Response, error) {
  37. return t.send("HEAD", url, "application/json", nil)
  38. }
  39. func (t *testHttpClient) Get(url string) (*http.Response, error) {
  40. return t.send("GET", url, "application/json", nil)
  41. }
  42. func (t *testHttpClient) Post(url string, bodyType string, body io.Reader) (*http.Response, error) {
  43. return t.send("POST", url, bodyType, body)
  44. }
  45. func (t *testHttpClient) PostForm(url string, data url.Values) (*http.Response, error) {
  46. return t.Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  47. }
  48. func (t *testHttpClient) Put(url string, bodyType string, body io.Reader) (*http.Response, error) {
  49. return t.send("PUT", url, bodyType, body)
  50. }
  51. func (t *testHttpClient) PutForm(url string, data url.Values) (*http.Response, error) {
  52. return t.Put(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  53. }
  54. func (t *testHttpClient) Delete(url string, bodyType string, body io.Reader) (*http.Response, error) {
  55. return t.send("DELETE", url, bodyType, body)
  56. }
  57. func (t *testHttpClient) DeleteForm(url string, data url.Values) (*http.Response, error) {
  58. return t.Delete(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  59. }
  60. func (t *testHttpClient) send(method string, url string, bodyType string, body io.Reader) (*http.Response, error) {
  61. req, err := http.NewRequest(method, url, body)
  62. if err != nil {
  63. return nil, err
  64. }
  65. req.Header.Set("Content-Type", bodyType)
  66. return t.Do(req)
  67. }