httpclient.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package beaconfire
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net/http"
  6. "time"
  7. )
  8. const (
  9. _DEFAULT_USER_AGENT = "curl v7.19.1"
  10. )
  11. func Get(url string) ([]byte, error) {
  12. return Request(http.MethodGet, url, nil, nil, "", "")
  13. }
  14. func PostJson(url string, body []byte) ([]byte, error) {
  15. return Request(http.MethodPost, url, body, map[string]string{"Content-Type": "application/json"}, "", "")
  16. }
  17. // Delivery a HTTP request
  18. //
  19. // @method: http Method, eg. http.MethodGet
  20. // @url: endpoint
  21. // @body: post body
  22. // @headers: request headers
  23. // @usename: basic auth
  24. // @password: basic auth
  25. // @return: response, error
  26. func Request(method string, url string, body []byte, headers map[string]string, username, password string) ([]byte, error) {
  27. client := http.Client{
  28. Timeout: time.Second * 5,
  29. }
  30. req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
  31. if err != nil {
  32. return nil, err
  33. }
  34. if len(username) > 0 || len(password) > 0 {
  35. req.SetBasicAuth(username, password)
  36. }
  37. req.Header.Set("User-Agent", _DEFAULT_USER_AGENT)
  38. for k, v := range headers {
  39. req.Header.Set(k, v)
  40. }
  41. resp, err := client.Do(req)
  42. if err != nil {
  43. return nil, err
  44. }
  45. defer resp.Body.Close()
  46. return ioutil.ReadAll(resp.Body)
  47. }