-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
179 lines (161 loc) · 4.43 KB
/
client.go
File metadata and controls
179 lines (161 loc) · 4.43 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
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
package loops
import (
"bytes"
"encoding/json"
"fmt"
"io"
"math/rand/v2"
"net/http"
"time"
)
const (
DefaultBaseURL = "https://app.loops.so/api/v1"
maxRetries = 2
baseDelay = 500 * time.Millisecond
)
var sleep = time.Sleep
func isRetryable(statusCode int) bool {
return statusCode == http.StatusTooManyRequests || statusCode >= 500
}
type APIError struct {
StatusCode int
Message string
}
func (e *APIError) Error() string {
return e.Message
}
type Client struct {
baseURL string
apiKey string
httpClient *http.Client
logger io.Writer
userAgent string
}
type Option func(*Client)
func WithBaseURL(u string) Option { return func(c *Client) { c.baseURL = u } }
func WithUserAgent(ua string) Option { return func(c *Client) { c.userAgent = ua } }
func WithLogger(w io.Writer) Option { return func(c *Client) { c.logger = w } }
func WithHTTPClient(h *http.Client) Option { return func(c *Client) { c.httpClient = h } }
func NewClient(apiKey string, opts ...Option) *Client {
c := &Client{
baseURL: DefaultBaseURL,
apiKey: apiKey,
httpClient: &http.Client{Timeout: 5 * time.Second},
userAgent: "loops-go/" + Version,
}
for _, opt := range opts {
opt(c)
}
return c
}
func errorFromResponse(resp *http.Response) *APIError {
var body struct {
Error string `json:"error"`
Message string `json:"message"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err == nil {
if body.Error != "" {
return &APIError{StatusCode: resp.StatusCode, Message: body.Error}
}
if body.Message != "" {
return &APIError{StatusCode: resp.StatusCode, Message: body.Message}
}
}
return &APIError{StatusCode: resp.StatusCode, Message: fmt.Sprintf("unexpected status: %d", resp.StatusCode)}
}
func (c *Client) logResponse(resp *http.Response) {
raw, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Fprintf(c.logger, "[debug] Response: %s (body read failed: %v)\n", resp.Status, err)
resp.Body = io.NopCloser(bytes.NewReader(nil))
return
}
resp.Body = io.NopCloser(bytes.NewReader(raw))
fmt.Fprintf(c.logger, "[debug] Response: %s (%d bytes)\n", resp.Status, len(raw))
if len(raw) == 0 {
return
}
var pretty bytes.Buffer
if json.Indent(&pretty, raw, "", " ") == nil {
fmt.Fprintf(c.logger, "[debug] Body:\n%s\n", pretty.String())
} else {
fmt.Fprintf(c.logger, "[debug] Body: %s\n", raw)
}
}
func (c *Client) do(req *http.Request) (*http.Response, error) {
var (
resp *http.Response
err error
)
for attempt := 0; attempt <= maxRetries; attempt++ {
if attempt > 0 {
if req.GetBody != nil {
body, err := req.GetBody()
if err != nil {
return nil, fmt.Errorf("failed to reset request body: %w", err)
}
req.Body = body
}
delay := time.Duration(1<<(attempt-1)) * baseDelay
jitter := time.Duration(rand.Int64N(int64(delay / 2)))
sleep(delay + jitter)
}
resp, err = c.httpClient.Do(req)
if err != nil {
if req.Context().Err() != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
continue
}
if !isRetryable(resp.StatusCode) {
if c.logger != nil {
c.logResponse(resp)
}
return resp, nil
}
if attempt < maxRetries {
resp.Body.Close()
}
}
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
return resp, nil
}
func (c *Client) newRequest(method, path string, body io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s%s", c.baseURL, path)
var bodyBytes []byte
if body != nil && c.logger != nil {
var err error
bodyBytes, err = io.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("failed to read request body: %w", err)
}
body = bytes.NewReader(bodyBytes)
}
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("User-Agent", c.userAgent)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.logger != nil {
fmt.Fprintf(c.logger, "[debug] %s %s\n", method, url)
fmt.Fprintf(c.logger, "[debug] Authorization: Bearer [REDACTED]\n")
if req.Header.Get("Content-Type") != "" {
fmt.Fprintf(c.logger, "[debug] Content-Type: %s\n", req.Header.Get("Content-Type"))
}
if len(bodyBytes) > 0 {
var pretty bytes.Buffer
if json.Indent(&pretty, bodyBytes, "", " ") == nil {
fmt.Fprintf(c.logger, "[debug] Body:\n%s\n", pretty.String())
} else {
fmt.Fprintf(c.logger, "[debug] Body: %s\n", bodyBytes)
}
}
}
return req, nil
}