-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
297 lines (247 loc) · 7.65 KB
/
client.go
File metadata and controls
297 lines (247 loc) · 7.65 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
package forge
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
coreerr "dappco.re/go/core/log"
)
// APIError represents an error response from the Forgejo API.
type APIError struct {
StatusCode int
Message string
URL string
}
func (e *APIError) Error() string {
return fmt.Sprintf("forge: %s %d: %s", e.URL, e.StatusCode, e.Message)
}
// IsNotFound returns true if the error is a 404 response.
func IsNotFound(err error) bool {
var apiErr *APIError
return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound
}
// IsForbidden returns true if the error is a 403 response.
func IsForbidden(err error) bool {
var apiErr *APIError
return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusForbidden
}
// IsConflict returns true if the error is a 409 response.
func IsConflict(err error) bool {
var apiErr *APIError
return errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusConflict
}
// Option configures the Client.
type Option func(*Client)
// WithHTTPClient sets a custom http.Client.
func WithHTTPClient(hc *http.Client) Option {
return func(c *Client) { c.httpClient = hc }
}
// WithUserAgent sets the User-Agent header.
func WithUserAgent(ua string) Option {
return func(c *Client) { c.userAgent = ua }
}
// RateLimit represents the rate limit information from the Forgejo API.
type RateLimit struct {
Limit int
Remaining int
Reset int64
}
// Client is a low-level HTTP client for the Forgejo API.
type Client struct {
baseURL string
token string
httpClient *http.Client
userAgent string
rateLimit RateLimit
}
// RateLimit returns the last known rate limit information.
func (c *Client) RateLimit() RateLimit {
return c.rateLimit
}
// NewClient creates a new Forgejo API client.
func NewClient(url, token string, opts ...Option) *Client {
c := &Client{
baseURL: strings.TrimRight(url, "/"),
token: token,
httpClient: &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
},
userAgent: "go-forge/0.1",
}
for _, opt := range opts {
opt(c)
}
return c
}
// Get performs a GET request.
func (c *Client) Get(ctx context.Context, path string, out any) error {
_, err := c.doJSON(ctx, http.MethodGet, path, nil, out)
return err
}
// Post performs a POST request.
func (c *Client) Post(ctx context.Context, path string, body, out any) error {
_, err := c.doJSON(ctx, http.MethodPost, path, body, out)
return err
}
// Patch performs a PATCH request.
func (c *Client) Patch(ctx context.Context, path string, body, out any) error {
_, err := c.doJSON(ctx, http.MethodPatch, path, body, out)
return err
}
// Put performs a PUT request.
func (c *Client) Put(ctx context.Context, path string, body, out any) error {
_, err := c.doJSON(ctx, http.MethodPut, path, body, out)
return err
}
// Delete performs a DELETE request.
func (c *Client) Delete(ctx context.Context, path string) error {
_, err := c.doJSON(ctx, http.MethodDelete, path, nil, nil)
return err
}
// DeleteWithBody performs a DELETE request with a JSON body.
func (c *Client) DeleteWithBody(ctx context.Context, path string, body any) error {
_, err := c.doJSON(ctx, http.MethodDelete, path, body, nil)
return err
}
// PostRaw performs a POST request with a JSON body and returns the raw
// response body as bytes instead of JSON-decoding. Useful for endpoints
// such as /markdown that return raw HTML text.
func (c *Client) PostRaw(ctx context.Context, path string, body any) ([]byte, error) {
url := c.baseURL + path
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, coreerr.E("Client.PostRaw", "forge: marshal body", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bodyReader)
if err != nil {
return nil, coreerr.E("Client.PostRaw", "forge: create request", err)
}
req.Header.Set("Authorization", "token "+c.token)
req.Header.Set("Content-Type", "application/json")
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, coreerr.E("Client.PostRaw", "forge: request POST "+path, err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, c.parseError(resp, path)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, coreerr.E("Client.PostRaw", "forge: read response body", err)
}
return data, nil
}
// GetRaw performs a GET request and returns the raw response body as bytes
// instead of JSON-decoding. Useful for endpoints that return raw file content.
func (c *Client) GetRaw(ctx context.Context, path string) ([]byte, error) {
url := c.baseURL + path
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, coreerr.E("Client.GetRaw", "forge: create request", err)
}
req.Header.Set("Authorization", "token "+c.token)
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, coreerr.E("Client.GetRaw", "forge: request GET "+path, err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, c.parseError(resp, path)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, coreerr.E("Client.GetRaw", "forge: read response body", err)
}
return data, nil
}
func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
_, err := c.doJSON(ctx, method, path, body, out)
return err
}
func (c *Client) doJSON(ctx context.Context, method, path string, body, out any) (*http.Response, error) {
url := c.baseURL + path
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, coreerr.E("Client.doJSON", "forge: marshal body", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, coreerr.E("Client.doJSON", "forge: create request", err)
}
req.Header.Set("Authorization", "token "+c.token)
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if c.userAgent != "" {
req.Header.Set("User-Agent", c.userAgent)
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, coreerr.E("Client.doJSON", "forge: request "+method+" "+path, err)
}
defer resp.Body.Close()
c.updateRateLimit(resp)
if resp.StatusCode >= 400 {
return nil, c.parseError(resp, path)
}
if out != nil && resp.StatusCode != http.StatusNoContent {
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return nil, coreerr.E("Client.doJSON", "forge: decode response", err)
}
}
return resp, nil
}
func (c *Client) parseError(resp *http.Response, path string) error {
var errBody struct {
Message string `json:"message"`
}
// Read a bit of the body to see if we can get a message
data, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
_ = json.Unmarshal(data, &errBody)
msg := errBody.Message
if msg == "" && len(data) > 0 {
msg = string(data)
}
if msg == "" {
msg = http.StatusText(resp.StatusCode)
}
return &APIError{
StatusCode: resp.StatusCode,
Message: msg,
URL: path,
}
}
func (c *Client) updateRateLimit(resp *http.Response) {
if limit := resp.Header.Get("X-RateLimit-Limit"); limit != "" {
c.rateLimit.Limit, _ = strconv.Atoi(limit)
}
if remaining := resp.Header.Get("X-RateLimit-Remaining"); remaining != "" {
c.rateLimit.Remaining, _ = strconv.Atoi(remaining)
}
if reset := resp.Header.Get("X-RateLimit-Reset"); reset != "" {
c.rateLimit.Reset, _ = strconv.ParseInt(reset, 10, 64)
}
}