curl.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package helpers
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "time"
  8. )
  9. var (
  10. ErrCurlGetStatus = error(&CurlGetStatusError{})
  11. )
  12. type CurlGetStatusError struct {
  13. Expected int
  14. Received int
  15. }
  16. func (e *CurlGetStatusError) Is(err error) bool {
  17. if _, ok := err.(*CurlGetStatusError); !ok {
  18. return false
  19. }
  20. return true
  21. }
  22. func (e *CurlGetStatusError) Error() string {
  23. return fmt.Sprintf("CurlGet: expected %d, received %d", e.Expected, e.Received)
  24. }
  25. func CurlGet(ctx context.Context, url string, timeout time.Duration) ([]byte, error) {
  26. var b []byte
  27. ctx, cancel := context.WithTimeout(ctx, timeout)
  28. defer cancel()
  29. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  30. if err != nil {
  31. return b, err
  32. }
  33. rcl := &http.Client{}
  34. var resp *http.Response
  35. resp, err = rcl.Do(req)
  36. if err != nil {
  37. return b, err
  38. }
  39. defer resp.Body.Close()
  40. if resp.StatusCode != http.StatusOK {
  41. return b, error(&CurlGetStatusError{
  42. Expected: http.StatusOK,
  43. Received: resp.StatusCode,
  44. })
  45. }
  46. b, err = io.ReadAll(resp.Body)
  47. if err != nil {
  48. return b, err
  49. }
  50. return b, nil
  51. }