-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathresponse.go
More file actions
330 lines (279 loc) · 8.38 KB
/
response.go
File metadata and controls
330 lines (279 loc) · 8.38 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
package requests
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"iter"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
// Response represents an HTTP response.
type Response struct {
stream StreamCallback
streamErr StreamErrCallback
streamDone StreamDoneCallback
RawResponse *http.Response // RawResponse is the underlying HTTP response.
BodyBytes []byte // BodyBytes contains the buffered response body for non-streaming responses.
Context context.Context // Context is the request context associated with the response.
Client *Client // Client is the client that created the response.
}
// NewResponse creates a new wrapped response object, leveraging the buffer pool for efficient memory usage.
func NewResponse(
ctx context.Context,
resp *http.Response,
client *Client,
stream StreamCallback,
streamErr StreamErrCallback,
streamDone StreamDoneCallback,
) (*Response, error) {
response := &Response{
RawResponse: resp,
Context: ctx,
BodyBytes: nil,
stream: stream,
streamErr: streamErr,
streamDone: streamDone,
Client: client,
}
if response.stream != nil {
go response.handleStream()
return response, nil
}
if err := response.handleNonStream(); err != nil {
return nil, err
}
return response, nil
}
// handleStream processes the HTTP response as a stream.
func (r *Response) handleStream() {
defer func() {
if err := r.RawResponse.Body.Close(); err != nil {
if r.Client.Logger != nil {
r.Client.Logger.Errorf("failed to close response body: %v", err)
}
}
}()
scanner := bufio.NewScanner(r.RawResponse.Body)
scanBuf := make([]byte, 0, MaxStreamBufferSize)
scanner.Buffer(scanBuf, MaxStreamBufferSize)
for scanner.Scan() {
if err := r.stream(scanner.Bytes()); err != nil {
break
}
}
if err := scanner.Err(); err != nil && r.streamErr != nil {
r.streamErr(err)
}
if r.streamDone != nil {
r.streamDone()
}
}
// handleNonStream reads the HTTP response body into a buffer for non-streaming responses.
func (r *Response) handleNonStream() error {
buf := GetBuffer()
defer PutBuffer(buf)
_, err := buf.ReadFrom(r.RawResponse.Body)
if err != nil {
return fmt.Errorf("%w: %w", ErrResponseReadFailed, err)
}
_ = r.RawResponse.Body.Close()
// Copy data before returning buffer to pool to prevent data race.
// Without this, concurrent goroutines could get the same pooled buffer,
// causing one goroutine's response data to be overwritten by another.
r.BodyBytes = bytes.Clone(buf.B)
r.RawResponse.Body = io.NopCloser(bytes.NewReader(r.BodyBytes))
return nil
}
// StatusCode returns the HTTP status code of the response.
func (r *Response) StatusCode() int {
return r.RawResponse.StatusCode
}
// Status returns the status string of the response (e.g., "200 OK").
func (r *Response) Status() string {
return r.RawResponse.Status
}
// Header returns the response headers.
func (r *Response) Header() http.Header {
return r.RawResponse.Header
}
// Cookies parses and returns the cookies set in the response.
func (r *Response) Cookies() []*http.Cookie {
return r.RawResponse.Cookies()
}
// Location returns the URL redirected address.
func (r *Response) Location() (*url.URL, error) {
return r.RawResponse.Location()
}
// URL returns the request URL that elicited the response.
func (r *Response) URL() *url.URL {
return r.RawResponse.Request.URL
}
// ContentType returns the value of the "Content-Type" header.
func (r *Response) ContentType() string {
return r.Header().Get("Content-Type")
}
// IsContentType checks if the response Content-Type header matches a given content type.
func (r *Response) IsContentType(contentType string) bool {
return strings.Contains(r.ContentType(), contentType)
}
// IsJSON checks if the response Content-Type indicates JSON.
func (r *Response) IsJSON() bool {
return r.IsContentType("application/json")
}
// IsXML checks if the response Content-Type indicates XML.
func (r *Response) IsXML() bool {
return r.IsContentType("application/xml")
}
// IsYAML checks if the response Content-Type indicates YAML.
func (r *Response) IsYAML() bool {
return r.IsContentType("application/yaml")
}
// ContentLength returns the length of the response body.
func (r *Response) ContentLength() int {
return len(r.BodyBytes)
}
// IsEmpty checks if the response body is empty.
func (r *Response) IsEmpty() bool {
return r.ContentLength() == 0
}
// IsSuccess checks if the response status code indicates success (200 - 299).
func (r *Response) IsSuccess() bool {
code := r.StatusCode()
return code >= 200 && code <= 299
}
// IsError checks if the response status code indicates an error (>= 400).
func (r *Response) IsError() bool {
return r.StatusCode() >= 400
}
// IsClientError checks if the response status code indicates a client error (400 - 499).
func (r *Response) IsClientError() bool {
code := r.StatusCode()
return code >= 400 && code < 500
}
// IsServerError checks if the response status code indicates a server error (>= 500).
func (r *Response) IsServerError() bool {
return r.StatusCode() >= 500
}
// IsRedirect checks if the response status code indicates a redirect (300 - 399).
func (r *Response) IsRedirect() bool {
code := r.StatusCode()
return code >= 300 && code < 400
}
// Body returns the response body as a byte slice.
func (r *Response) Body() []byte {
return r.BodyBytes
}
// String returns the response body as a string.
func (r *Response) String() string {
return string(r.BodyBytes)
}
// Scan attempts to unmarshal the response body based on its content type.
func (r *Response) Scan(v any) error {
switch {
case r.IsJSON():
return r.ScanJSON(v)
case r.IsXML():
return r.ScanXML(v)
case r.IsYAML():
return r.ScanYAML(v)
}
return fmt.Errorf("%w: %s", ErrUnsupportedContentType, r.ContentType())
}
// ScanJSON unmarshals the response body into a struct via JSON decoding.
func (r *Response) ScanJSON(v any) error {
if r.BodyBytes == nil {
return nil
}
return r.Client.JSONDecoder.Decode(bytes.NewReader(r.BodyBytes), v)
}
// ScanXML unmarshals the response body into a struct via XML decoding.
func (r *Response) ScanXML(v any) error {
if r.BodyBytes == nil {
return nil
}
return r.Client.XMLDecoder.Decode(bytes.NewReader(r.BodyBytes), v)
}
// ScanYAML unmarshals the response body into a struct via YAML decoding.
func (r *Response) ScanYAML(v any) error {
if r.BodyBytes == nil {
return nil
}
return r.Client.YAMLDecoder.Decode(bytes.NewReader(r.BodyBytes), v)
}
// DirPermissions is the permission mode used when Save creates parent directories.
const DirPermissions = 0o750
// Save saves the response body to a file or io.Writer.
func (r *Response) Save(v any) error {
switch p := v.(type) {
case string:
return r.saveToFile(p)
case io.Writer:
return r.saveToWriter(p)
default:
return ErrNotSupportSaveMethod
}
}
func (r *Response) saveToFile(path string) error {
file := filepath.Clean(path)
dir := filepath.Dir(file)
if _, err := os.Stat(dir); err != nil {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to check directory: %w", err)
}
if err = os.MkdirAll(dir, DirPermissions); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
}
outFile, err := os.Create(file)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer func() {
if err := outFile.Close(); err != nil {
if r.Client.Logger != nil {
r.Client.Logger.Errorf("failed to close file: %v", err)
}
}
}()
if _, err = io.Copy(outFile, bytes.NewReader(r.Body())); err != nil {
return fmt.Errorf("failed to write response body to file: %w", err)
}
return nil
}
func (r *Response) saveToWriter(w io.Writer) error {
if _, err := io.Copy(w, bytes.NewReader(r.Body())); err != nil {
return fmt.Errorf("failed to write response body to io.Writer: %w", err)
}
if wc, ok := w.(io.WriteCloser); ok {
if err := wc.Close(); err != nil {
if r.Client.Logger != nil {
r.Client.Logger.Errorf("failed to close io.Writer: %v", err)
}
}
}
return nil
}
// Lines returns an iterator over the buffered response body lines.
func (r *Response) Lines() iter.Seq[[]byte] {
return func(yield func([]byte) bool) {
if r.BodyBytes == nil {
return
}
scanner := bufio.NewScanner(bytes.NewReader(r.BodyBytes))
for scanner.Scan() {
if !yield(scanner.Bytes()) {
break
}
}
}
}
// Close closes the response body.
func (r *Response) Close() error {
return r.RawResponse.Body.Close()
}