http_utils.go 2.1 KB

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