httpclient.go 995 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. func Request(method string, url string, body []byte, headers map[string]string, username, password string) ([]byte, error) {
  18. client := http.Client{
  19. Timeout: time.Second * 5,
  20. }
  21. req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
  22. if err != nil {
  23. return nil, err
  24. }
  25. if len(username) > 0 || len(password) > 0 {
  26. req.SetBasicAuth(username, password)
  27. }
  28. req.Header.Set("User-Agent", _DEFAULT_USER_AGENT)
  29. for k, v := range headers {
  30. req.Header.Set(k, v)
  31. }
  32. resp, err := client.Do(req)
  33. if err != nil {
  34. return nil, err
  35. }
  36. defer resp.Body.Close()
  37. return ioutil.ReadAll(resp.Body)
  38. }