...
1
2
3
4
5 package resty
6
7 import (
8 "encoding/json"
9 "fmt"
10 "io"
11 "net/http"
12 "strings"
13 "time"
14 )
15
16
17
18
19
20
21 type Response struct {
22 Request *Request
23 RawResponse *http.Response
24
25 body []byte
26 size int64
27 receivedAt time.Time
28 }
29
30
31
32
33 func (r *Response) Body() []byte {
34 if r.RawResponse == nil {
35 return []byte{}
36 }
37 return r.body
38 }
39
40
41
42 func (r *Response) Status() string {
43 if r.RawResponse == nil {
44 return ""
45 }
46 return r.RawResponse.Status
47 }
48
49
50
51 func (r *Response) StatusCode() int {
52 if r.RawResponse == nil {
53 return 0
54 }
55 return r.RawResponse.StatusCode
56 }
57
58
59 func (r *Response) Proto() string {
60 if r.RawResponse == nil {
61 return ""
62 }
63 return r.RawResponse.Proto
64 }
65
66
67 func (r *Response) Result() interface{} {
68 return r.Request.Result
69 }
70
71
72 func (r *Response) Error() interface{} {
73 return r.Request.Error
74 }
75
76
77 func (r *Response) Header() http.Header {
78 if r.RawResponse == nil {
79 return http.Header{}
80 }
81 return r.RawResponse.Header
82 }
83
84
85 func (r *Response) Cookies() []*http.Cookie {
86 if r.RawResponse == nil {
87 return make([]*http.Cookie, 0)
88 }
89 return r.RawResponse.Cookies()
90 }
91
92
93 func (r *Response) String() string {
94 if r.body == nil {
95 return ""
96 }
97 return strings.TrimSpace(string(r.body))
98 }
99
100
101
102
103
104 func (r *Response) Time() time.Duration {
105 if r.Request.clientTrace != nil {
106 return r.Request.TraceInfo().TotalTime
107 }
108 return r.receivedAt.Sub(r.Request.Time)
109 }
110
111
112 func (r *Response) ReceivedAt() time.Time {
113 return r.receivedAt
114 }
115
116
117
118
119 func (r *Response) Size() int64 {
120 return r.size
121 }
122
123
124
125
126
127
128 func (r *Response) RawBody() io.ReadCloser {
129 if r.RawResponse == nil {
130 return nil
131 }
132 return r.RawResponse.Body
133 }
134
135
136 func (r *Response) IsSuccess() bool {
137 return r.StatusCode() > 199 && r.StatusCode() < 300
138 }
139
140
141 func (r *Response) IsError() bool {
142 return r.StatusCode() > 399
143 }
144
145
146
147
148
149 func (r *Response) setReceivedAt() {
150 r.receivedAt = time.Now()
151 if r.Request.clientTrace != nil {
152 r.Request.clientTrace.endTime = r.receivedAt
153 }
154 }
155
156 func (r *Response) fmtBodyString(sl int64) string {
157 if r.body != nil {
158 if int64(len(r.body)) > sl {
159 return fmt.Sprintf("***** RESPONSE TOO LARGE (size - %d) *****", len(r.body))
160 }
161 ct := r.Header().Get(hdrContentTypeKey)
162 if IsJSONType(ct) {
163 out := acquireBuffer()
164 defer releaseBuffer(out)
165 err := json.Indent(out, r.body, "", " ")
166 if err != nil {
167 return fmt.Sprintf("*** Error: Unable to format response body - \"%s\" ***\n\nLog Body as-is:\n%s", err, r.String())
168 }
169 return out.String()
170 }
171 return r.String()
172 }
173
174 return "***** NO CONTENT *****"
175 }
176
View as plain text