-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
109 lines (90 loc) · 2.26 KB
/
Copy pathclient.go
File metadata and controls
109 lines (90 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package marketstack
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"github.com/google/go-querystring/query"
)
const (
defaultBaseURL = "http://api.marketstack.com/v1"
envAPIKey = "MARKETSTACK_API_KEY"
)
type Client struct {
apiKey string
baseURL string
httpClient *http.Client
}
func NewClient(apiKey string, httpClient *http.Client) *Client {
if apiKey == "" {
apiKey = os.Getenv(envAPIKey)
}
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Client{
apiKey: apiKey,
baseURL: defaultBaseURL,
httpClient: httpClient,
}
}
func (c *Client) SetBaseURL(baseURL string) {
c.baseURL = strings.TrimSuffix(baseURL, "/")
}
func (c *Client) doRequest(ctx context.Context, endpoint string, params interface{}, result interface{}) error {
if c.apiKey == "" {
return &APIError{
Code: "missing_api_key",
Message: "API key is required. Set it via NewClient or MARKETSTACK_API_KEY environment variable",
}
}
u, err := url.Parse(c.baseURL + endpoint)
if err != nil {
return fmt.Errorf("invalid URL: %w", err)
}
q := u.Query()
q.Set("access_key", c.apiKey)
if params != nil {
values, err := query.Values(params)
if err != nil {
return fmt.Errorf("failed to encode query parameters: %w", err)
}
for k, v := range values {
for _, val := range v {
q.Add(k, val)
}
}
}
u.RawQuery = q.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
var apiErr ErrorResponse
if err := json.Unmarshal(body, &apiErr); err != nil {
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
if apiErr.Error != nil {
return apiErr.Error
}
return fmt.Errorf("API request failed with status %d", resp.StatusCode)
}
if err := json.Unmarshal(body, result); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
return nil
}