-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
403 lines (339 loc) · 9.31 KB
/
Copy pathclient.go
File metadata and controls
403 lines (339 loc) · 9.31 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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package gitcode
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const (
DefaultBaseURL = "https://api.gitcode.com/api/v5"
)
// Client is the GitCode API client.
type Client struct {
baseURL string
token string
httpClient *http.Client
authStyle AuthStyle
mu sync.RWMutex
// Retry policy for failed requests.
retryPolicy *RetryPolicy
// Request/response hooks for middleware.
requestHooks []RequestHook
responseHooks []ResponseHook
}
// AuthStyle defines how authentication tokens are sent.
type AuthStyle int
const (
// AuthStyleBearer sends "Authorization: Bearer <token>" header.
AuthStyleBearer AuthStyle = iota
// AuthStylePrivateToken sends "PRIVATE-TOKEN: <token>" header.
AuthStylePrivateToken
// AuthStyleAccessToken sends "?access_token=<token>" query parameter.
AuthStyleAccessToken
)
// NewClient creates a new GitCode API client with the given token.
func NewClient(token string) *Client {
return &Client{
baseURL: DefaultBaseURL,
token: token,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
authStyle: AuthStyleBearer,
}
}
// NewClientWithBaseURL creates a new GitCode API client with a custom base URL.
func NewClientWithBaseURL(baseURL, token string) *Client {
return &Client{
baseURL: strings.TrimRight(baseURL, "/"),
token: token,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
authStyle: AuthStyleBearer,
}
}
// SetAuthStyle sets the authentication style for the client.
func (c *Client) SetAuthStyle(style AuthStyle) {
c.mu.Lock()
defer c.mu.Unlock()
c.authStyle = style
}
// SetHTTPClient sets a custom HTTP client.
func (c *Client) SetHTTPClient(client *http.Client) {
c.mu.Lock()
defer c.mu.Unlock()
c.httpClient = client
}
// setAuthHeader sets the authentication header on the request.
func (c *Client) setAuthHeader(req *http.Request) {
c.mu.RLock()
style := c.authStyle
token := c.token
c.mu.RUnlock()
switch style {
case AuthStylePrivateToken:
req.Header.Set("PRIVATE-TOKEN", token)
case AuthStyleAccessToken:
q := req.URL.Query()
q.Set("access_token", token)
req.URL.RawQuery = q.Encode()
default:
req.Header.Set("Authorization", "Bearer "+token)
}
}
// doRequest executes an HTTP request and unmarshals the result.
func (c *Client) doRequest(ctx context.Context, method, path string, body interface{}, result interface{}) error {
_, err := c.doRequestWithHeaders(ctx, method, path, body, result)
return err
}
// doRequestWithHeaders executes an HTTP request and returns the response headers.
func (c *Client) doRequestWithHeaders(ctx context.Context, method, path string, body interface{}, result interface{}) (http.Header, error) {
var reqBody io.Reader
if body != nil {
raw, err := json.Marshal(body)
if err != nil {
return nil, err
}
reqBody = bytes.NewReader(raw)
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reqBody)
if err != nil {
return nil, err
}
c.setAuthHeader(req)
req.Header.Set("Content-Type", "application/json")
// Run request hooks
if err := c.runRequestHooks(req); err != nil {
return nil, fmt.Errorf("request hook error: %w", err)
}
// Execute request with retry
resp, err := c.doRequestWithRetry(ctx, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Run response hooks
if err := c.runResponseHooks(resp); err != nil {
return nil, fmt.Errorf("response hook error: %w", err)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, newAPIError(method, path, resp.StatusCode, string(respBody))
}
if result != nil && resp.StatusCode != http.StatusNoContent {
if len(respBody) > 0 {
if err := json.Unmarshal(respBody, result); err != nil {
return nil, err
}
}
}
return resp.Header, nil
}
// doRawRequest executes a raw HTTP request and returns the response body.
func (c *Client) doRawRequest(ctx context.Context, method, path string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, nil)
if err != nil {
return nil, err
}
c.setAuthHeader(req)
// Run request hooks
if err := c.runRequestHooks(req); err != nil {
return nil, fmt.Errorf("request hook error: %w", err)
}
// Execute request with retry
resp, err := c.doRequestWithRetry(ctx, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Run response hooks
if err := c.runResponseHooks(resp); err != nil {
return nil, fmt.Errorf("response hook error: %w", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode >= 400 {
return nil, newAPIError(method, path, resp.StatusCode, string(body[:min(len(body), 200)]))
}
return body, nil
}
// doFormRequest executes a form-encoded HTTP request.
func (c *Client) doFormRequest(ctx context.Context, method, path string, params url.Values, result interface{}) error {
var reqBody io.Reader
if params != nil {
reqBody = strings.NewReader(params.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reqBody)
if err != nil {
return err
}
c.setAuthHeader(req)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Run request hooks
if err := c.runRequestHooks(req); err != nil {
return fmt.Errorf("request hook error: %w", err)
}
// Execute request with retry
resp, err := c.doRequestWithRetry(ctx, req)
if err != nil {
return err
}
defer resp.Body.Close()
// Run response hooks
if err := c.runResponseHooks(resp); err != nil {
return fmt.Errorf("response hook error: %w", err)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode >= 400 {
return newAPIError(method, path, resp.StatusCode, string(respBody))
}
if result != nil && resp.StatusCode != http.StatusNoContent {
if err := json.Unmarshal(respBody, result); err != nil {
return err
}
}
return nil
}
// doRawBodyRequest executes an HTTP request with a raw JSON body.
func (c *Client) doRawBodyRequest(ctx context.Context, method, path string, body interface{}, result interface{}) error {
raw, err := json.Marshal(body)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bytes.NewReader(raw))
if err != nil {
return err
}
c.setAuthHeader(req)
req.Header.Set("Content-Type", "application/json")
// Run request hooks
if err := c.runRequestHooks(req); err != nil {
return fmt.Errorf("request hook error: %w", err)
}
// Execute request with retry
resp, err := c.doRequestWithRetry(ctx, req)
if err != nil {
return err
}
defer resp.Body.Close()
// Run response hooks
if err := c.runResponseHooks(resp); err != nil {
return fmt.Errorf("response hook error: %w", err)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode >= 400 {
return newAPIError(method, path, resp.StatusCode, string(respBody))
}
if result != nil && resp.StatusCode != http.StatusNoContent && len(respBody) > 0 {
if err := json.Unmarshal(respBody, result); err != nil {
return err
}
}
return nil
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// isNotFoundError checks if an error is a 404 Not Found response.
func isNotFoundError(err error) bool {
if err == nil {
return false
}
if IsNotFound(err) {
return true
}
return contains(err.Error(), "404")
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && searchString(s, substr)
}
func searchString(s, substr string) bool {
for i := 0; i <= len(s)-len(substr); i++ {
if s[i:i+len(substr)] == substr {
return true
}
}
return false
}
// User represents a GitCode user.
type User struct {
ID FlexString `json:"id"`
Login string `json:"login"`
Name string `json:"name"`
Email string `json:"email"`
AvatarURL string `json:"avatar_url"`
HTMLURL string `json:"html_url,omitempty"`
Type string `json:"type,omitempty"`
}
// GetCurrentUser returns the authenticated user's profile.
func (c *Client) GetCurrentUser(ctx context.Context) (*User, error) {
var user User
err := c.doRequest(ctx, http.MethodGet, "/user", nil, &user)
if err != nil {
return nil, err
}
return &user, nil
}
// GetUser returns a user by username.
func (c *Client) GetUser(ctx context.Context, username string) (*User, error) {
var user User
err := c.doRequest(ctx, http.MethodGet, fmt.Sprintf("/users/%s", username), nil, &user)
if err != nil {
return nil, err
}
return &user, nil
}
// ListOptions contains pagination parameters for list requests.
type ListOptions struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
}
func (o ListOptions) withDefaults() ListOptions {
if o.Page == 0 {
o.Page = 1
}
if o.PerPage == 0 {
o.PerPage = 20
}
return o
}
func (o ListOptions) toQuery() string {
opts := o.withDefaults()
return fmt.Sprintf("page=%d&per_page=%d", opts.Page, opts.PerPage)
}
// RateLimit contains rate limit information.
type RateLimit struct {
Limit int `json:"limit"`
Remaining int `json:"remaining"`
Reset time.Time `json:"reset"`
}
// GetRateLimit returns the current rate limit status.
func (c *Client) GetRateLimit(ctx context.Context) (*RateLimit, error) {
var rl RateLimit
err := c.doRequest(ctx, http.MethodGet, "/rate_limit", nil, &rl)
if err != nil {
return nil, err
}
return &rl, nil
}