http_utils.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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", err))
  30. }
  31. return m
  32. }
  33. func Get(url string) (*http.Response, error) {
  34. return send("GET", url, "application/json", nil)
  35. }
  36. func Post(url string, bodyType string, body io.Reader) (*http.Response, error) {
  37. return send("POST", url, bodyType, body)
  38. }
  39. func PostForm(url string, data url.Values) (*http.Response, error) {
  40. return Post(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  41. }
  42. func Put(url string, bodyType string, body io.Reader) (*http.Response, error) {
  43. return send("PUT", url, bodyType, body)
  44. }
  45. func PutForm(url string, data url.Values) (*http.Response, error) {
  46. return Put(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  47. }
  48. func Delete(url string, bodyType string, body io.Reader) (*http.Response, error) {
  49. return send("DELETE", url, bodyType, body)
  50. }
  51. func DeleteForm(url string, data url.Values) (*http.Response, error) {
  52. return Delete(url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
  53. }
  54. func send(method string, url string, bodyType string, body io.Reader) (*http.Response, error) {
  55. c := NewHTTPClient()
  56. req, err := http.NewRequest(method, url, body)
  57. if err != nil {
  58. return nil, err
  59. }
  60. req.Header.Set("Content-Type", bodyType)
  61. return c.Do(req)
  62. }