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
|
// Package api is a thin, standalone HTTP client for the rickub JSON API
// (`/api/v1`), hand-written against the API's published OpenAPI description. It
// imports none of the server's packages: the CLI is a pure client with a clean
// dependency boundary.
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
// Client talks to a rickub API host with a bearer PAT.
type Client struct {
Host string // e.g. https://rickub.com (no trailing slash)
Token string // rickub_pat_…
HTTPClient *http.Client
// UserAgent is sent on every request.
UserAgent string
}
// New builds a Client with a sane default HTTP client.
func New(host, token string) *Client {
return &Client{
Host: strings.TrimRight(host, "/"),
Token: token,
HTTPClient: &http.Client{Timeout: 30 * time.Second},
UserAgent: "rickub-cli",
}
}
// APIError is the parsed `{error:{code,message}}` envelope plus HTTP status.
type APIError struct {
Status int
Code string
Message string
}
func (e *APIError) Error() string {
if e.Code != "" {
return fmt.Sprintf("%s (%s)", e.Message, e.Code)
}
if e.Message != "" {
return e.Message
}
return fmt.Sprintf("HTTP %d", e.Status)
}
type errorEnvelope struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
// Request is a low-level typed request description.
type Request struct {
Method string
// Path is the API path WITHOUT the /api/v1 prefix, e.g. "/repos/o/r".
// Each segment must already be escaped by the caller where needed.
Path string
Query url.Values
// Body, if non-nil, is JSON-encoded.
Body any
// Accept overrides the Accept header (default application/json).
Accept string
}
// raw performs the request and returns status, body bytes, and content-type.
// A non-2xx response is decoded into an *APIError.
func (c *Client) raw(ctx context.Context, r Request) (int, []byte, string, error) {
u := c.Host + "/api/v1" + r.Path
if len(r.Query) > 0 {
u += "?" + r.Query.Encode()
}
var body io.Reader
if r.Body != nil {
b, err := json.Marshal(r.Body)
if err != nil {
return 0, nil, "", err
}
body = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, r.Method, u, body)
if err != nil {
return 0, nil, "", err
}
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
accept := r.Accept
if accept == "" {
accept = "application/json"
}
req.Header.Set("Accept", accept)
if r.Body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("User-Agent", c.UserAgent)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return 0, nil, "", err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, nil, resp.Header.Get("Content-Type"), err
}
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return resp.StatusCode, data, resp.Header.Get("Content-Type"), nil
}
// Attempt to decode the standard error envelope.
apiErr := &APIError{Status: resp.StatusCode}
var env errorEnvelope
if json.Unmarshal(data, &env) == nil && env.Error.Code != "" {
apiErr.Code = env.Error.Code
apiErr.Message = env.Error.Message
} else {
apiErr.Message = strings.TrimSpace(string(data))
if apiErr.Message == "" {
apiErr.Message = http.StatusText(resp.StatusCode)
}
}
return resp.StatusCode, data, resp.Header.Get("Content-Type"), apiErr
}
// do performs the request and unmarshals a JSON success body into out (which
// may be nil for empty 204 responses).
func (c *Client) do(ctx context.Context, r Request, out any) error {
_, data, _, err := c.raw(ctx, r)
if err != nil {
return err
}
if out == nil || len(bytes.TrimSpace(data)) == 0 {
return nil
}
return json.Unmarshal(data, out)
}
// RawJSON performs a request and returns the raw (success) response body. Used
// by the `rickub api` escape hatch and `--json` passthrough.
func (c *Client) RawJSON(ctx context.Context, method, path string, query url.Values, body any) ([]byte, string, error) {
_, data, ct, err := c.raw(ctx, Request{Method: method, Path: path, Query: query, Body: body})
return data, ct, err
}
// RawText performs a GET requesting text/plain and returns the decoded body.
func (c *Client) RawText(ctx context.Context, path string, query url.Values) ([]byte, error) {
_, data, _, err := c.raw(ctx, Request{Method: http.MethodGet, Path: path, Query: query, Accept: "text/plain"})
return data, err
}
// itoa is a small helper for building integer path segments.
func itoa(n int) string { return strconv.Itoa(n) }
// pageQuery builds a ?page/?per_page query, omitting zero values.
func pageQuery(page, perPage int, extra url.Values) url.Values {
q := url.Values{}
for k, v := range extra {
q[k] = v
}
if page > 0 {
q.Set("page", strconv.Itoa(page))
}
if perPage > 0 {
q.Set("per_page", strconv.Itoa(perPage))
}
return q
}
|