-
Notifications
You must be signed in to change notification settings - Fork 352
/
response.go
293 lines (262 loc) · 8.28 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package req
import (
"io"
"net/http"
"strings"
"time"
"github.com/imroc/req/v3/internal/header"
"github.com/imroc/req/v3/internal/util"
)
// Response is the http response.
type Response struct {
// The underlying http.Response is embed into Response.
*http.Response
// Err is the underlying error, not nil if some error occurs.
// Usually used in the ResponseMiddleware, you can skip logic in
// ResponseMiddleware that doesn't need to be executed when err occurs.
Err error
// Request is the Response's related Request.
Request *Request
body []byte
receivedAt time.Time
error interface{}
result interface{}
}
// IsSuccess method returns true if no error occurs and HTTP status `code >= 200 and <= 299`
// by default, you can also use Request.SetResultStateCheckFunc to customize the result
// state check logic.
//
// Deprecated: Use IsSuccessState instead.
func (r *Response) IsSuccess() bool {
return r.IsSuccessState()
}
// IsSuccessState method returns true if no error occurs and HTTP status `code >= 200 and <= 299`
// by default, you can also use Request.SetResultStateCheckFunc to customize the result state
// check logic.
func (r *Response) IsSuccessState() bool {
if r.Response == nil {
return false
}
return r.ResultState() == SuccessState
}
// IsError method returns true if no error occurs and HTTP status `code >= 400`
// by default, you can also use Request.SetResultStateCheckFunc to customize the result
// state check logic.
//
// Deprecated: Use IsErrorState instead.
func (r *Response) IsError() bool {
return r.IsErrorState()
}
// IsErrorState method returns true if no error occurs and HTTP status `code >= 400`
// by default, you can also use Request.SetResultStateCheckFunc to customize the result
// state check logic.
func (r *Response) IsErrorState() bool {
if r.Response == nil {
return false
}
return r.ResultState() == ErrorState
}
// GetContentType return the `Content-Type` header value.
func (r *Response) GetContentType() string {
if r.Response == nil {
return ""
}
return r.Header.Get(header.ContentType)
}
// ResultState returns the result state.
// By default, it returns SuccessState if HTTP status `code >= 400`, and returns
// ErrorState if HTTP status `code >= 400`, otherwise returns UnknownState.
// You can also use Request.SetResultStateCheckFunc or Client.SetResultStateCheckFunc
// to customize the result state check logic.
func (r *Response) ResultState() ResultState {
if r.Response == nil {
return UnknownState
}
var resultStateCheckFunc func(resp *Response) ResultState
if r.Request.client.resultStateCheckFunc != nil {
resultStateCheckFunc = r.Request.client.resultStateCheckFunc
} else {
resultStateCheckFunc = defaultResultStateChecker
}
return resultStateCheckFunc(r)
}
// Result returns the automatically unmarshalled object if Request.SetSuccessResult
// is called and ResultState returns SuccessState.
// Otherwise, return nil.
//
// Deprecated: Use SuccessResult instead.
func (r *Response) Result() interface{} {
return r.SuccessResult()
}
// SuccessResult returns the automatically unmarshalled object if Request.SetSuccessResult
// is called and ResultState returns SuccessState.
// Otherwise, return nil.
func (r *Response) SuccessResult() interface{} {
return r.result
}
// Error returns the automatically unmarshalled object when Request.SetErrorResult
// or Client.SetCommonErrorResult is called, and ResultState returns ErrorState.
// Otherwise, return nil.
//
// Deprecated: Use ErrorResult instead.
func (r *Response) Error() interface{} {
return r.error
}
// ErrorResult returns the automatically unmarshalled object when Request.SetErrorResult
// or Client.SetCommonErrorResult is called, and ResultState returns ErrorState.
// Otherwise, return nil.
func (r *Response) ErrorResult() interface{} {
return r.error
}
// TraceInfo returns the TraceInfo from Request.
func (r *Response) TraceInfo() TraceInfo {
return r.Request.TraceInfo()
}
// TotalTime returns the total time of the request, from request we sent to response we received.
func (r *Response) TotalTime() time.Duration {
if r.Request.trace != nil {
return r.Request.TraceInfo().TotalTime
}
if !r.receivedAt.IsZero() {
return r.receivedAt.Sub(r.Request.StartTime)
}
return r.Request.responseReturnTime.Sub(r.Request.StartTime)
}
// ReceivedAt returns the timestamp that response we received.
func (r *Response) ReceivedAt() time.Time {
return r.receivedAt
}
func (r *Response) setReceivedAt() {
r.receivedAt = time.Now()
if r.Request.trace != nil {
r.Request.trace.endTime = r.receivedAt
}
}
// UnmarshalJson unmarshalls JSON response body into the specified object.
func (r *Response) UnmarshalJson(v interface{}) error {
if r.Err != nil {
return r.Err
}
b, err := r.ToBytes()
if err != nil {
return err
}
return r.Request.client.jsonUnmarshal(b, v)
}
// UnmarshalXml unmarshalls XML response body into the specified object.
func (r *Response) UnmarshalXml(v interface{}) error {
if r.Err != nil {
return r.Err
}
b, err := r.ToBytes()
if err != nil {
return err
}
return r.Request.client.xmlUnmarshal(b, v)
}
// Unmarshal unmarshalls response body into the specified object according
// to response `Content-Type`.
func (r *Response) Unmarshal(v interface{}) error {
if r.Err != nil {
return r.Err
}
v = util.GetPointer(v)
contentType := r.Header.Get("Content-Type")
if strings.Contains(contentType, "json") {
return r.UnmarshalJson(v)
} else if strings.Contains(contentType, "xml") {
return r.UnmarshalXml(v)
}
return r.UnmarshalJson(v)
}
// Into unmarshalls response body into the specified object according
// to response `Content-Type`.
func (r *Response) Into(v interface{}) error {
return r.Unmarshal(v)
}
// Bytes return the response body as []bytes that have already been read, could be
// nil if not read, the following cases are already read:
// 1. `Request.SetResult` or `Request.SetError` is called.
// 2. `Client.DisableAutoReadResponse` and `Request.DisableAutoReadResponse` is not
// called, and also `Request.SetOutput` and `Request.SetOutputFile` is not called.
func (r *Response) Bytes() []byte {
return r.body
}
// String returns the response body as string that have already been read, could be
// nil if not read, the following cases are already read:
// 1. `Request.SetResult` or `Request.SetError` is called.
// 2. `Client.DisableAutoReadResponse` and `Request.DisableAutoReadResponse` is not
// called, and also `Request.SetOutput` and `Request.SetOutputFile` is not called.
func (r *Response) String() string {
return string(r.body)
}
// ToString returns the response body as string, read body if not have been read.
func (r *Response) ToString() (string, error) {
b, err := r.ToBytes()
return string(b), err
}
// ToBytes returns the response body as []byte, read body if not have been read.
func (r *Response) ToBytes() (body []byte, err error) {
if r.Err != nil {
return nil, r.Err
}
if r.body != nil {
return r.body, nil
}
if r.Response == nil || r.Response.Body == nil {
return []byte{}, nil
}
defer func() {
r.Body.Close()
if err != nil {
r.Err = err
}
r.body = body
}()
body, err = io.ReadAll(r.Body)
r.setReceivedAt()
if err == nil && r.Request.client.responseBodyTransformer != nil {
body, err = r.Request.client.responseBodyTransformer(body, r.Request, r)
}
return
}
// Dump return the string content that have been dumped for the request.
// `Request.Dump` or `Request.DumpXXX` MUST have been called.
func (r *Response) Dump() string {
return r.Request.getDumpBuffer().String()
}
// GetStatus returns the response status.
func (r *Response) GetStatus() string {
if r.Response == nil {
return ""
}
return r.Status
}
// GetStatusCode returns the response status code.
func (r *Response) GetStatusCode() int {
if r.Response == nil {
return 0
}
return r.StatusCode
}
// GetHeader returns the response header value by key.
func (r *Response) GetHeader(key string) string {
if r.Response == nil {
return ""
}
return r.Header.Get(key)
}
// GetHeaderValues returns the response header values by key.
func (r *Response) GetHeaderValues(key string) []string {
if r.Response == nil {
return nil
}
return r.Header.Values(key)
}
// HeaderToString get all header as string.
func (r *Response) HeaderToString() string {
if r.Response == nil {
return ""
}
return convertHeaderToString(r.Header)
}