http_utils.go 2.1 KB

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