|
@@ -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
|