-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
277 lines (234 loc) · 6.95 KB
/
response.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
package requests
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"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
BodyBytes []byte
Context context.Context
Client *Client
}
// 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()
} else {
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 {
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() // Use the buffer pool
defer PutBuffer(buf)
_, err := buf.ReadFrom(r.RawResponse.Body)
if err != nil {
return fmt.Errorf("%w: %v", ErrResponseReadFailed, err) //nolint:errorlint
}
_ = r.RawResponse.Body.Close()
r.RawResponse.Body = io.NopCloser(bytes.NewReader(buf.B))
r.BodyBytes = buf.B
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 {
if r.BodyBytes == nil {
return 0
}
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
}
// 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 interface{}) 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 interface{}) 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 interface{}) 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 interface{}) error {
if r.BodyBytes == nil {
return nil
}
return r.Client.YAMLDecoder.Decode(bytes.NewReader(r.BodyBytes), v)
}
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:
file := filepath.Clean(p)
dir := filepath.Dir(file)
// Create the directory if it doesn't exist
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)
}
}
// Create and open the file for writing
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 {
r.Client.Logger.Errorf("failed to close file: %v", err)
}
}()
// Write the response body to the file
_, err = io.Copy(outFile, bytes.NewReader(r.Body()))
if err != nil {
return fmt.Errorf("failed to write response body to file: %w", err)
}
return nil
case io.Writer:
// Write the response body directly to the provided io.Writer
_, err := io.Copy(p, bytes.NewReader(r.Body()))
if err != nil {
return fmt.Errorf("failed to write response body to io.Writer: %w", err)
}
// If the writer can be closed, close it
if pc, ok := p.(io.WriteCloser); ok {
if err := pc.Close(); err != nil {
r.Client.Logger.Errorf("failed to close io.Writer: %v", err)
}
}
return nil
default:
// Return an error if the provided type is not supported
return ErrNotSupportSaveMethod
}
}
// Close closes the response body.
func (r *Response) Close() error {
return r.RawResponse.Body.Close()
}