-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi_client.go
203 lines (178 loc) · 5.01 KB
/
api_client.go
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package flareio
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/hashicorp/go-retryablehttp"
)
type ApiClient struct {
tenantId int
apiKey string
httpClient *retryablehttp.Client
baseUrl string
apiToken string
apiTokenExp time.Time
}
type ApiClientOption func(*ApiClient)
// WithTenantId allows configuring the tenant id.
func WithTenantId(tenantId int) ApiClientOption {
return func(client *ApiClient) {
client.tenantId = tenantId
}
}
// withBaseUrl allows configuring the base url, for testing only.
func withBaseUrl(baseUrl string) ApiClientOption {
return func(client *ApiClient) {
client.baseUrl = baseUrl
}
}
func defaultHttpClient() *retryablehttp.Client {
c := retryablehttp.NewClient()
c.Logger = nil
// Match the Python SDK retry settings:
// - https://github.com/Flared/python-flareio/blob/d24061a086137e6a6fc7f467d6773660edf851f2/flareio/api_client.py#L44
c.RetryMax = 5
c.RetryWaitMin = time.Second * 2
c.RetryWaitMax = time.Second * 15
return c
}
// NewApiClient can be used to create a new ApiClient
// instance.
func NewApiClient(
apiKey string,
optionFns ...ApiClientOption,
) *ApiClient {
c := &ApiClient{
apiKey: apiKey,
baseUrl: "https://api.flare.io/",
httpClient: defaultHttpClient(),
}
for _, optionFn := range optionFns {
optionFn(c)
}
return c
}
// GenerateToken creates a Flare API token using the
// API Client's API key.
func (client *ApiClient) GenerateToken() (string, error) {
// Prepare payload
type GeneratePayload struct {
TenantId int `json:"tenant_id,omitempty"`
}
payload := &GeneratePayload{
TenantId: client.tenantId,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
return "", fmt.Errorf("failed to marshal generate payload: %w", err)
}
// Prepare the request
request, err := client.newRequest(
"POST",
"/tokens/generate",
nil,
bytes.NewReader(payloadBytes),
)
if err != nil {
return "", fmt.Errorf("failed to prepare request: %w", err)
}
request.Header.Set("Authorization", client.apiKey)
// Tenant scoping like {"tenant_id": 123} is ignored if Content-Type not set to "application/json"
request.Header.Set("Content-Type", "application/json")
// Fire the request
resp, err := client.do(request, false)
if err != nil {
return "", fmt.Errorf("failed to generate API token: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", fmt.Errorf("unexpected response code: %d", resp.StatusCode)
}
// Parse response
type TokenResponse struct {
Token string `json:"token"`
}
var tokenResponse TokenResponse
if err := json.NewDecoder(resp.Body).Decode(&tokenResponse); err != nil {
return "", err
}
client.apiToken = tokenResponse.Token
client.apiTokenExp = time.Now().Add(time.Minute * 45)
return tokenResponse.Token, nil
}
func (client *ApiClient) isApiTokenExpired() bool {
return client.apiTokenExp.Before(time.Now())
}
func (client *ApiClient) getOrGenerateToken() (string, error) {
if !client.isApiTokenExpired() {
return client.apiToken, nil
}
return client.GenerateToken()
}
func (client *ApiClient) newRequest(
method string,
path string,
params *url.Values,
body io.Reader,
) (*http.Request, error) {
destUrl, err := url.JoinPath(client.baseUrl, path)
if err != nil {
return nil, fmt.Errorf("failed to create dest URL: %w", err)
}
if params != nil {
destUrl = destUrl + "?" + params.Encode()
}
return http.NewRequest(method, destUrl, body)
}
func (client *ApiClient) do(
request *http.Request,
authenticated bool,
) (*http.Response, error) {
if authenticated {
apiToken, err := client.getOrGenerateToken()
if err != nil {
return nil, err
}
request.Header.Add(
"Authorization",
fmt.Sprintf("Bearer %s", apiToken),
)
}
// Just like Go's User-Agent is hardcoded to "Go-http-client/1.1", we hardcode ours.
// It isn't meant to reflect the actual library version.
request.Header.Set("User-Agent", "go-flareio/0.1.0")
retryableRequest, err := retryablehttp.FromRequest(request)
if err != nil {
return nil, fmt.Errorf("failed to prepare retryable request: %w", err)
}
return client.httpClient.Do(retryableRequest)
}
// Get peforms an authenticated GET request at the given path.
// Includes params in the query string.
func (client *ApiClient) Get(path string, params *url.Values) (*http.Response, error) {
request, err := client.newRequest("GET", path, params, nil)
if err != nil {
return nil, fmt.Errorf("failed to create http request: %w", err)
}
return client.do(request, true)
}
// Post performs an authenticated POST request at the given path.
// Includes params in the query string.
// The provided ContentType should describe the content of the body.
func (client *ApiClient) Post(
path string,
params *url.Values,
contentType string,
body io.Reader,
) (*http.Response, error) {
request, err := client.newRequest("POST", path, params, body)
if err != nil {
return nil, fmt.Errorf("failed to create http request: %w", err)
}
request.Header.Set("Content-Type", contentType)
return client.do(request, true)
}