-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest_client.go
278 lines (227 loc) · 6.92 KB
/
rest_client.go
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
package zulip
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"path/filepath"
"strings"
"time"
"github.com/google/uuid"
)
type RESTClient interface {
DoRequest(ctx context.Context, method, path string, data map[string]any, response APIResponse, opts ...DoRequestOption) error
DoFileRequest(ctx context.Context, method, path string, fileName string, file io.Reader, response APIResponse, opts ...DoRequestOption) error
}
// Client is the main HTTP Client to interact with Zulip's API
type Client struct {
baseURL string
userAgent string
userEmail string
userAPIKey string
httpClient *http.Client
logger *slog.Logger
}
const (
RESTClientDefaultTimeout = 5 * time.Second
RESTClientLongPollTimeout = 10 * time.Minute
)
type clientOptions struct {
httpClient *http.Client
userAgent string
logger *slog.Logger
}
type ClientOption func(*clientOptions) error
func WithHTTPClient(client *http.Client) ClientOption {
return func(o *clientOptions) error {
if client == nil {
return errors.New("http client is nil")
}
o.httpClient = client
return nil
}
}
func WithCustomUserAgent(userAgent string) ClientOption {
return func(o *clientOptions) error {
o.userAgent = userAgent
return nil
}
}
func WithLogger(logger *slog.Logger) ClientOption {
return func(o *clientOptions) error {
if logger == nil {
return errors.New("logger is nil")
}
o.logger = logger
return nil
}
}
func NewClient(credentials CredentialsProvider, options ...ClientOption) (*Client, error) {
creds, err := credentials()
if err != nil {
return nil, err
}
opts := clientOptions{
httpClient: &http.Client{},
userAgent: DefaultUserAgentName + "/" + Version,
logger: slog.New(slog.NewJSONHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError})),
}
for _, opt := range options {
if err := opt(&opts); err != nil {
return nil, err
}
}
return &Client{
baseURL: creds.Site,
userEmail: creds.Email,
userAPIKey: creds.APIKey,
userAgent: opts.userAgent,
httpClient: opts.httpClient,
logger: opts.logger,
}, nil
}
type clientSendRequestOptions struct {
timeout time.Duration
}
type DoRequestOption func(*clientSendRequestOptions)
func WithTimeout(duration time.Duration) DoRequestOption {
return func(o *clientSendRequestOptions) {
o.timeout = duration
}
}
// DoRequest is the main function to send requests to Zulip's API.
func (c *Client) DoRequest(ctx context.Context, method, path string, data map[string]any, response APIResponse, opts ...DoRequestOption) error {
options := clientSendRequestOptions{
timeout: RESTClientDefaultTimeout,
}
for _, opt := range opts {
opt(&options)
}
formData := url.Values{}
for k, v := range data {
formData.Set(k, fmt.Sprintf("%v", v))
}
formDataEncoded := formData.Encode()
var body io.Reader
if method != http.MethodGet {
body = strings.NewReader(formDataEncoded)
}
fullURLPath := c.baseURL + path
requestID := uuid.New().String()
reqLog := c.logger.With(slog.String("request_id", requestID))
reqLog.DebugContext(ctx, "Sending request",
slog.String("method", method),
slog.String("url", fullURLPath),
slog.String("data", formDataEncoded))
if method == http.MethodGet && len(data) > 0 {
fullURLPath += "?" + formDataEncoded
}
reqCtx, reqCancel := context.WithTimeout(ctx, options.timeout)
defer reqCancel()
req, err := http.NewRequestWithContext(reqCtx, method, fullURLPath, body)
if err != nil {
return fmt.Errorf("creating send request: %w", err)
}
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(c.userEmail, c.userAPIKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("send request: %w", err)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return fmt.Errorf("cannot read response body: %s", err)
}
headersGroup := []slog.Attr{}
for k, v := range resp.Header {
headersGroup = append(headersGroup, slog.String(k, strings.Join(v, ", ")))
}
reqLog.DebugContext(ctx, "Received response",
slog.Any("headers", slog.GroupValue(headersGroup...)),
slog.String("request_id", requestID),
slog.Int("status_code", resp.StatusCode),
)
response.SetHTTPCode(resp.StatusCode)
response.SetHTTPHeaders(resp.Header)
return nil
}
// DoFileRequest is the main function to send requests to Zulip's API with a file. For file and emoji uploads.
func (c *Client) DoFileRequest(ctx context.Context, method, path string, fileName string, file io.Reader, response APIResponse, opts ...DoRequestOption) error {
options := clientSendRequestOptions{
timeout: RESTClientDefaultTimeout,
}
for _, opt := range opts {
opt(&options)
}
var requestBody bytes.Buffer
writer := multipart.NewWriter(&requestBody)
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
"filename",
filepath.Base(fileName)))
mimeType := mime.TypeByExtension(filepath.Ext(fileName))
if mimeType == "" {
mimeType = "application/octet-stream"
}
h.Set("Content-Type", mimeType)
part, err := writer.CreatePart(h)
if err != nil {
return fmt.Errorf("cannot create writer from file: %v", err)
}
_, err = io.Copy(part, file)
if err != nil {
return fmt.Errorf("copying file content: %v", err)
}
if err := writer.Close(); err != nil {
return fmt.Errorf("closing writer: %v", err)
}
reqCtx, reqCancel := context.WithTimeout(ctx, options.timeout)
defer reqCancel()
fullURLPath := c.baseURL + path
requestID := uuid.New().String()
reqLog := c.logger.With(slog.String("request_id", requestID))
reqLog.DebugContext(ctx, "Sending file request",
slog.String("method", method),
slog.String("url", fullURLPath),
slog.String("filename", fileName),
slog.String("mimetype", mimeType),
slog.Int("content_length", requestBody.Len()))
req, err := http.NewRequestWithContext(reqCtx, method, fullURLPath, &requestBody)
if err != nil {
return fmt.Errorf("creating send request: %w", err)
}
req.Header.Set("User-Agent", c.userAgent)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(c.userEmail, c.userAPIKey)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("send request: %w", err)
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return fmt.Errorf("cannot read response body: %w", err)
}
headersGroup := []slog.Attr{}
for k, v := range resp.Header {
headersGroup = append(headersGroup, slog.String(k, strings.Join(v, ", ")))
}
reqLog.DebugContext(ctx, "Received response",
slog.Any("headers", slog.GroupValue(headersGroup...)),
slog.Int("status_code", resp.StatusCode),
)
response.SetHTTPCode(resp.StatusCode)
response.SetHTTPHeaders(resp.Header)
return nil
}