Browse Source

Move params to struct, use status code, use headers

Volodymyr Tkach 2 years ago
parent
commit
c5a234728f
1 changed files with 24 additions and 7 deletions
  1. 24 7
      utils/http/helpers/curl.go

+ 24 - 7
utils/http/helpers/curl.go

@@ -12,6 +12,12 @@ var (
 	ErrCurlGetStatus = error(&CurlGetStatusError{})
 )
 
+type CurlGetOpts struct {
+	ExpectStatusCode int
+	Headers          map[string][]string
+	Timeout          time.Duration
+}
+
 type CurlGetStatusError struct {
 	Expected int
 	Received int
@@ -28,16 +34,25 @@ func (e *CurlGetStatusError) Error() string {
 	return fmt.Sprintf("CurlGet: expected %d, received %d", e.Expected, e.Received)
 }
 
-func CurlGet(ctx context.Context, url string, timeout time.Duration) ([]byte, error) {
+func CurlGet(ctx context.Context, url string, opts *CurlGetOpts) ([]byte, error) {
+	if opts == nil {
+		opts = &CurlGetOpts{
+			ExpectStatusCode: http.StatusOK,
+			Headers:          nil,
+			Timeout:          time.Second * 60,
+		}
+	}
+
 	var b []byte
 
-	ctx, cancel := context.WithTimeout(ctx, timeout)
+	ctx, cancel := context.WithTimeout(ctx, opts.Timeout)
 	defer cancel()
 
 	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
 	if err != nil {
 		return b, err
 	}
+	req.Header = opts.Headers
 
 	rcl := &http.Client{}
 	var resp *http.Response
@@ -52,11 +67,13 @@ func CurlGet(ctx context.Context, url string, timeout time.Duration) ([]byte, er
 		return b, err
 	}
 
-	if resp.StatusCode != http.StatusOK {
-		return b, error(&CurlGetStatusError{
-			Expected: http.StatusOK,
-			Received: resp.StatusCode,
-		})
+	if opts.ExpectStatusCode > 0 {
+		if resp.StatusCode != opts.ExpectStatusCode {
+			return b, error(&CurlGetStatusError{
+				Expected: opts.ExpectStatusCode,
+				Received: resp.StatusCode,
+			})
+		}
 	}
 
 	return b, nil