-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
373 lines (303 loc) · 8.12 KB
/
request.go
File metadata and controls
373 lines (303 loc) · 8.12 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
package syro
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"strings"
"time"
)
type HttpClient struct {
client *http.Client
}
// Make http requests with the client reused
func NewHttpClient(c *http.Client) *HttpClient {
if c == nil {
c = http.DefaultClient
}
return &HttpClient{c}
}
func (c *HttpClient) Client() *http.Client {
return c.client
}
func (c *HttpClient) Transport() *http.Transport {
if tr, ok := c.client.Transport.(*http.Transport); ok {
return tr
}
return http.DefaultTransport.(*http.Transport)
}
func (c *HttpClient) Request(method, url string) *Request {
return &Request{
Method: method,
URL: url,
Headers: map[string]string{},
client: c.client,
ctx: ctx,
}
}
type Request struct {
ctx context.Context
Headers map[string]string
client *http.Client // Optional custom HTTP client. If nil, default client will be used
errBodyLimit *int // Optional limit for the returned body size on error. If nil, no limit
Method string
URL string
Body []byte
ignoreStatusCodes bool
}
type Response struct {
Request *Request
Header http.Header
Body []byte
StatusCode int
Duration time.Duration
}
func NewRequest(method, url string) *Request {
defaultErrBodyLimit := 1000
return &Request{
Method: method,
URL: url,
Headers: make(map[string]string),
client: &http.Client{},
errBodyLimit: &defaultErrBodyLimit,
ctx: ctx,
}
}
func (r *Request) WithHeaders(headers map[string]string) *Request {
maps.Copy(r.Headers, headers)
return r
}
func (r *Request) WithCtx(ctx context.Context) *Request {
if ctx != nil {
r.ctx = ctx
}
return r
}
func (r *Request) WithBearerToken(token string) *Request {
r.Headers["Authorization"] = "Bearer " + token
return r
}
func (r *Request) WithFormData(data map[string]string) *Request {
form := url.Values{}
for k, v := range data {
form.Add(k, v)
}
r.Body = []byte(form.Encode())
r.Headers["Content-Type"] = "application/x-www-form-urlencoded"
return r
}
func (r *Request) WithBasicAuth(username, password string) *Request {
auth := fmt.Sprintf("%s:%s", username, password)
encoded := base64.StdEncoding.EncodeToString([]byte(auth))
r.Headers["Authorization"] = "Basic " + encoded
return r
}
// WithErrorBodyLimit sets a limit for the error body size. If nil, no limit is applied.
func (r *Request) WithErrorBodyLimit(limit *int) *Request {
r.errBodyLimit = limit
return r
}
func (r *Request) WithHeader(key, value string) *Request {
r.Headers[key] = value
return r
}
func (r *Request) WithJsonHeader() *Request {
r.Headers["Content-Type"] = "application/json"
return r
}
func (r *Request) WithBody(body []byte) *Request {
r.Body = body
return r
}
func (r *Request) WithIgnoreStatusCodes(ignore bool) *Request {
r.ignoreStatusCodes = ignore
return r
}
func (r *Request) WithClient(c *http.Client) *Request {
r.client = c
return r
}
func (r *Request) Do() (*Response, error) {
url := r.URL
if r.Method == "" {
return nil, fmt.Errorf("request method is not set")
}
if url == "" {
return nil, fmt.Errorf("request URL is not set")
}
var reqBody []byte
if r.Body != nil {
reqBody = r.Body
}
req, err := http.NewRequestWithContext(r.ctx, r.Method, url, bytes.NewBuffer(reqBody))
if err != nil {
return nil, err
}
for k, v := range r.Headers {
req.Header.Set(k, v)
}
now := time.Now()
res, err := r.client.Do(req)
if err != nil {
return nil, fmt.Errorf("error fetching %v : %v", url, err)
}
defer res.Body.Close()
dur := time.Since(now)
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body when fetching %v, status %v: error: %v", url, res.Status, err)
}
_response := &Response{
StatusCode: res.StatusCode,
Header: res.Header,
Body: body,
Duration: dur,
Request: r,
}
if r.ignoreStatusCodes {
return _response, nil
}
if res.StatusCode != 200 && res.StatusCode != 201 && res.StatusCode != 202 {
bodyStr := ""
if body != nil && r.errBodyLimit != nil {
bodyUpTo := min(len(body), *r.errBodyLimit) // limit to x characters
bodyStr = string(body[:bodyUpTo])
}
return _response, fmt.Errorf("response did not return status in 200 group while requesting %v, status: %v, body: %v", url, res.Status, bodyStr)
}
if body == nil {
return _response, fmt.Errorf("response returned empty body while requesting %v", url)
}
return _response, nil
}
func (r *Request) AsCURL() string {
var buf bytes.Buffer
buf.WriteString("curl")
hasOptions := false
// Add method if not GET
if r.Method != "" && r.Method != "GET" {
buf.WriteString(fmt.Sprintf(" -X %s \\\n", r.Method))
hasOptions = true
}
// Add headers
for k, v := range r.Headers {
buf.WriteString(fmt.Sprintf(" -H '%s: %s' \\\n", k, v))
hasOptions = true
}
// Add body if present
if len(r.Body) > 0 {
// Escape single quotes in the body
b := bytes.ReplaceAll(r.Body, []byte("'"), []byte("'\\''"))
buf.WriteString(fmt.Sprintf(" -d '%s' \\\n", string(b)))
hasOptions = true
}
// Add URL (always last, no trailing backslash)
if hasOptions {
buf.WriteString(fmt.Sprintf(" \"%s\"", r.URL))
} else {
buf.WriteString(fmt.Sprintf(" \"%s\"", r.URL))
}
return buf.String()
}
func (r *Response) Summary() string {
var sb strings.Builder
// Request section
sb.WriteString("───── REQUEST ─────────────────────────\n")
sb.WriteString(r.Request.AsCURL())
sb.WriteString("\n\n")
// Response section
sb.WriteString("───── RESPONSE ────────────────────────\n")
sb.WriteString(fmt.Sprintf("Status: %d\n", r.StatusCode))
sb.WriteString(fmt.Sprintf("Duration: %v\n", r.Duration))
// Headers
if len(r.Header) > 0 {
sb.WriteString("\nHeaders:\n")
for key, values := range r.Header {
sb.WriteString(fmt.Sprintf(" %s: %s\n", key, strings.Join(values, ", ")))
}
}
// Body
sb.WriteString("\nBody:\n")
bodyStr := r.formatBody()
for _, line := range strings.Split(bodyStr, "\n") {
if line != "" {
sb.WriteString(" " + line + "\n")
}
}
return sb.String()
}
func (r *Response) formatBody() string {
if r == nil {
return ""
}
data := r.Body
if len(data) == 0 {
return "(empty)"
}
// Trim whitespace to check actual content
trimmed := bytes.TrimSpace(data)
if len(trimmed) == 0 {
return "(empty)"
}
// Check Content-Type header first
contentType := r.Header.Get("Content-Type")
// Try JSON - check header or content structure
if strings.Contains(contentType, "application/json") ||
strings.Contains(contentType, "text/json") ||
bytes.HasPrefix(trimmed, []byte("{")) ||
bytes.HasPrefix(trimmed, []byte("[")) {
var obj any
if err := json.Unmarshal(trimmed, &obj); err == nil {
pretty, err := json.MarshalIndent(obj, "", " ")
if err == nil {
return string(pretty)
}
}
}
// Try XML - check header or content structure
if strings.Contains(contentType, "application/xml") ||
strings.Contains(contentType, "text/xml") ||
(bytes.HasPrefix(trimmed, []byte("<")) && bytes.HasSuffix(trimmed, []byte(">"))) {
// Additional check: verify it's not HTML
lowerContent := strings.ToLower(string(trimmed[:min(len(trimmed), 200)]))
isHTML := strings.Contains(lowerContent, "<!doctype html") || strings.Contains(lowerContent, "<html")
if !isHTML {
content, err := prettyPrintXML(string(data))
if err == nil {
return content
}
}
}
// Fall back to plain string
return string(data)
}
func prettyPrintXML(xmlString string) (string, error) {
// Create a decoder
decoder := xml.NewDecoder(strings.NewReader(xmlString))
// Read tokens and rebuild
var buf bytes.Buffer
encoder := xml.NewEncoder(&buf)
encoder.Indent("", " ")
for {
token, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
return "", err
}
if err := encoder.EncodeToken(token); err != nil {
return "", err
}
}
if err := encoder.Flush(); err != nil {
return "", err
}
return xml.Header + buf.String(), nil
}