-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
304 lines (272 loc) · 8.78 KB
/
client.go
File metadata and controls
304 lines (272 loc) · 8.78 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package quote0
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"runtime"
"strings"
"sync"
"time"
)
const (
// DefaultBaseURL is the default API host. Endpoints are under /api/open/*.
// This matches the official curl examples.
DefaultBaseURL = "https://dot.mindreset.tech"
textEndpoint = "/api/open/text"
imageEndpoint = "/api/open/image"
userAgentProduct = "quote0-go-sdk"
userAgentVersion = "1.0"
defaultHTTPTimeout = 30 * time.Second
maxResponseBodySize = 4 << 20 // 4 MiB guard
)
// APIResponse reflects a typical JSON envelope from the service.
// Some responses may be plain text; in those cases, Message/StatusCode/RawBody are set.
type APIResponse struct {
// Code carries the numeric status returned by the Quote/0 API (0 on success).
Code int `json:"code"`
// Message is the string message provided by the service (e.g., "ok" or reason text).
Message string `json:"message"`
// Result contains the raw JSON payload (varies per endpoint; caller can unmarshal).
Result json.RawMessage `json:"result"`
// StatusCode keeps the HTTP status code observed for the request.
StatusCode int `json:"-"`
// RawBody contains the exact response bytes for troubleshooting or custom parsing.
RawBody []byte `json:"-"`
}
// Client exposes the Quote/0 APIs with proper authentication and rate limiting.
type Client struct {
baseURL string
apiKey string
http *http.Client
limiter RateLimiter
userAgent string
debug bool
mu sync.RWMutex
defaultDevice string
}
// ClientOption mutates the client during construction.
type ClientOption func(*Client)
// NewClient builds a client. apiKey is required (format: dot_app_xxx).
func NewClient(apiKey string, opts ...ClientOption) (*Client, error) {
apiKey = strings.TrimSpace(apiKey)
if apiKey == "" {
return nil, errors.New("quote0: API token is required")
}
c := &Client{
baseURL: DefaultBaseURL,
apiKey: apiKey,
userAgent: buildDefaultUserAgent(),
http: &http.Client{Timeout: defaultHTTPTimeout},
limiter: NewFixedIntervalLimiter(time.Second), // 1 QPS
}
for _, opt := range opts {
if opt != nil {
opt(c)
}
}
if c.http == nil {
c.http = &http.Client{Timeout: defaultHTTPTimeout}
}
c.baseURL = sanitizeBaseURL(c.baseURL)
return c, nil
}
// WithBaseURL overrides the API host (useful for staging/tests). No trailing slash required.
func WithBaseURL(baseURL string) ClientOption {
return func(c *Client) {
c.baseURL = baseURL
}
}
// WithHTTPClient installs a custom http.Client.
func WithHTTPClient(hc *http.Client) ClientOption {
return func(c *Client) { c.http = hc }
}
// WithRateLimiter replaces the default limiter. Pass nil to disable (not recommended).
func WithRateLimiter(l RateLimiter) ClientOption {
return func(c *Client) { c.limiter = l }
}
// WithUserAgent sets a custom User-Agent string.
// Pass an empty string to send an empty User-Agent header (not recommended).
// If not called, the client uses a default SDK User-Agent.
func WithUserAgent(ua string) ClientOption {
return func(c *Client) { c.userAgent = ua }
}
// WithDebug enables debug mode which logs request details (method, URL, headers, body) to stderr.
// Useful for debugging and verifying SDK behavior.
func WithDebug(debug bool) ClientOption {
return func(c *Client) { c.debug = debug }
}
// WithDefaultDeviceID sets a default device serial number used when request omits deviceId.
func WithDefaultDeviceID(deviceID string) ClientOption {
return func(c *Client) {
c.mu.Lock()
c.defaultDevice = strings.TrimSpace(deviceID)
c.mu.Unlock()
}
}
// SetDefaultDeviceID updates the default device ID in a thread-safe manner.
func (c *Client) SetDefaultDeviceID(deviceID string) {
c.mu.Lock()
c.defaultDevice = strings.TrimSpace(deviceID)
c.mu.Unlock()
}
// GetDefaultDeviceID returns the current default device ID.
func (c *Client) GetDefaultDeviceID() string {
c.mu.RLock()
id := c.defaultDevice
c.mu.RUnlock()
return id
}
func sanitizeBaseURL(baseURL string) string {
baseURL = strings.TrimSpace(baseURL)
if baseURL == "" {
return DefaultBaseURL
}
return strings.TrimRight(baseURL, "/")
}
func (c *Client) resolveDeviceID(explicit string) (string, error) {
explicit = strings.TrimSpace(explicit)
if explicit != "" {
return explicit, nil
}
c.mu.RLock()
id := c.defaultDevice
c.mu.RUnlock()
id = strings.TrimSpace(id)
if id == "" {
return "", ErrDeviceIDMissing
}
return id, nil
}
// doJSON encodes the payload, executes the POST, and normalizes the response.
func (c *Client) doJSON(ctx context.Context, endpoint string, payload interface{}) (*APIResponse, error) {
if ctx == nil {
ctx = context.Background()
}
if c.limiter != nil {
if err := c.limiter.Wait(ctx); err != nil {
return nil, err
}
}
body, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("quote0: encode request: %w", err)
}
url := c.baseURL + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("quote0: build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Content-Type", "application/json")
// Always set User-Agent, even if empty, to give users full control.
// If empty, it sends an empty UA instead of Go's default "Go-http-client/1.1".
req.Header.Set("User-Agent", c.userAgent)
// Record start time for debug logging
var startTime time.Time
if c.debug {
startTime = time.Now()
c.logRequest(req, body, startTime)
}
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("quote0: execute request: %w", err)
}
defer resp.Body.Close()
limited := io.LimitReader(resp.Body, maxResponseBodySize)
raw, err := io.ReadAll(limited)
if err != nil {
return nil, fmt.Errorf("quote0: read response: %w", err)
}
// Debug logging: print response details with timing
if c.debug {
endTime := time.Now()
c.logResponse(resp, raw, startTime, endTime)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, buildAPIError(resp.StatusCode, raw)
}
return parseResponse(resp, raw), nil
}
// parseResponse converts raw HTTP response into APIResponse.
func parseResponse(resp *http.Response, raw []byte) *APIResponse {
out := &APIResponse{StatusCode: resp.StatusCode, RawBody: raw}
if len(raw) == 0 {
return out
}
// Try JSON first based on header; if it fails, fall back to plain text.
ct := strings.ToLower(resp.Header.Get("Content-Type"))
if strings.Contains(ct, "application/json") {
if err := json.Unmarshal(raw, out); err == nil {
return out
}
}
out.Message = strings.TrimSpace(string(raw))
return out
}
func buildDefaultUserAgent() string {
goVer := strings.TrimPrefix(runtime.Version(), "go")
if goVer == "" {
goVer = runtime.Version()
}
return fmt.Sprintf("%s/%s (+https://github.com/1set/quote0; Go%s; %s/%s)",
userAgentProduct, userAgentVersion, goVer, runtime.GOOS, runtime.GOARCH)
}
// logRequest prints HTTP request details to stderr for debugging.
func (*Client) logRequest(req *http.Request, body []byte, startTime time.Time) {
logger := log.New(os.Stderr, "[quote0-debug] ", 0)
logger.Println("========== REQUEST ==========")
logger.Printf("Time: %s", startTime.Format("2006-01-02 15:04:05.000"))
logger.Printf("%s %s", req.Method, req.URL.String())
logger.Println("Headers:")
for key, values := range req.Header {
for _, value := range values {
// Mask the API key for security
if key == "Authorization" && strings.HasPrefix(value, "Bearer ") {
token := value[7:]
if len(token) > 16 {
value = "Bearer " + token[:8] + "..." + token[len(token)-8:]
}
}
logger.Printf(" %s: %s", key, value)
}
}
logger.Println("Body:")
// Pretty print JSON
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, body, " ", " "); err == nil {
logger.Println(prettyJSON.String())
} else {
logger.Println(string(body))
}
logger.Println("=============================")
}
// logResponse prints HTTP response details to stderr for debugging.
func (*Client) logResponse(resp *http.Response, body []byte, startTime, endTime time.Time) {
logger := log.New(os.Stderr, "[quote0-debug] ", 0)
logger.Println("========== RESPONSE ==========")
logger.Printf("Time: %s", endTime.Format("2006-01-02 15:04:05.000"))
duration := endTime.Sub(startTime)
logger.Printf("Duration: %v", duration)
logger.Printf("Status: %s (%d)", resp.Status, resp.StatusCode)
logger.Println("Headers:")
for key, values := range resp.Header {
for _, value := range values {
logger.Printf(" %s: %s", key, value)
}
}
logger.Println("Body:")
// Pretty print JSON if possible
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, body, " ", " "); err == nil {
logger.Println(prettyJSON.String())
} else {
logger.Println(string(body))
}
logger.Println("==============================")
}