-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
195 lines (173 loc) · 4.38 KB
/
Copy pathclient.go
File metadata and controls
195 lines (173 loc) · 4.38 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
package cursor
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)
// HTTPDoer is the subset of *http.Client used by this package.
type HTTPDoer interface {
Do(req *http.Request) (*http.Response, error)
}
// Client talks directly to the Cursor Cloud Agents REST API.
type Client struct {
apiKey string
baseURL *url.URL
httpClient HTTPDoer
userAgent string
}
// ClientOption customizes a Client.
type ClientOption func(*Client) error
// WithBaseURL overrides the default Cursor API base URL. It is mainly useful
// for tests.
func WithBaseURL(baseURL string) ClientOption {
return func(c *Client) error {
parsed, err := url.Parse(baseURL)
if err != nil {
return fmt.Errorf("parse base url: %w", err)
}
c.baseURL = parsed
return nil
}
}
// WithHTTPClient overrides the HTTP client used for requests.
func WithHTTPClient(httpClient HTTPDoer) ClientOption {
return func(c *Client) error {
if httpClient == nil {
return errors.New("http client cannot be nil")
}
c.httpClient = httpClient
return nil
}
}
// WithUserAgent overrides the default User-Agent header.
func WithUserAgent(userAgent string) ClientOption {
return func(c *Client) error {
c.userAgent = userAgent
return nil
}
}
// NewClient creates a REST API client. If apiKey is empty, CURSOR_API_KEY is
// used.
func NewClient(apiKey string, opts ...ClientOption) (*Client, error) {
if apiKey == "" {
apiKey = os.Getenv("CURSOR_API_KEY")
}
baseURL, err := url.Parse(defaultBaseURL)
if err != nil {
return nil, err
}
client := &Client{
apiKey: apiKey,
baseURL: baseURL,
httpClient: &http.Client{Timeout: 60 * time.Second},
userAgent: defaultUserAgent,
}
for _, opt := range opts {
if opt == nil {
continue
}
if err := opt(client); err != nil {
return nil, err
}
}
return client, nil
}
type authMode int
const (
authBasic authMode = iota
authBearer
)
func (c *Client) doJSON(ctx context.Context, method, path string, query url.Values, body any, out any) error {
return c.doJSONAuth(ctx, method, path, query, body, out, authBasic)
}
func (c *Client) doJSONAuth(ctx context.Context, method, path string, query url.Values, body any, out any, auth authMode) error {
var requestBody io.Reader
if body != nil {
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(body); err != nil {
return fmt.Errorf("encode request body: %w", err)
}
requestBody = buf
}
req, err := http.NewRequestWithContext(ctx, method, c.url(path, query), requestBody)
if err != nil {
return err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
c.setAuth(req, auth)
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
raw, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return decodeAPIError(resp.StatusCode, resp.Header, raw)
}
if out == nil || len(bytes.TrimSpace(raw)) == 0 {
return nil
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("decode response body: %w", err)
}
return nil
}
func (c *Client) newRequest(ctx context.Context, method, path string, query url.Values, body io.Reader, auth authMode) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, c.url(path, query), body)
if err != nil {
return nil, err
}
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
c.setAuth(req, auth)
return req, nil
}
func (c *Client) setAuth(req *http.Request, auth authMode) {
if c.apiKey == "" {
return
}
switch auth {
case authBearer:
req.Header.Set("Authorization", "Bearer "+c.apiKey)
default:
req.SetBasicAuth(c.apiKey, "")
}
}
func (c *Client) url(path string, query url.Values) string {
u := *c.baseURL
basePath := strings.TrimRight(u.Path, "/")
u.Path = basePath + path
u.RawQuery = query.Encode()
return u.String()
}
func clientOptions(apiKey, baseURL string, httpClient HTTPDoer, userAgent string) ([]ClientOption, error) {
opts := make([]ClientOption, 0, 3)
if baseURL != "" {
opts = append(opts, WithBaseURL(baseURL))
}
if httpClient != nil {
opts = append(opts, WithHTTPClient(httpClient))
}
if userAgent != "" {
opts = append(opts, WithUserAgent(userAgent))
}
return opts, nil
}