-
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathclient.go
220 lines (188 loc) Β· 6.02 KB
/
client.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
package http
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"sort"
"strings"
)
type (
// Doer is the HTTP client interface.
Doer interface {
Do(*http.Request) (*http.Response, error)
}
// DebugDoer is a Doer that can print the low level HTTP details.
DebugDoer interface {
Doer
// Fprint prints the HTTP request and response details.
Fprint(io.Writer)
}
// debugDoer wraps a doer and implements DebugDoer.
debugDoer struct {
Doer
// Request is the captured request.
Request *http.Request
// Response is the captured response.
Response *http.Response
}
// ClientError is an error returned by a HTTP service client.
ClientError struct {
// Name is a name for this class of errors.
Name string
// Message contains the specific error details.
Message string
// Service is the name of the service.
Service string
// Method is the name of the service method.
Method string
// Is the error temporary?
Temporary bool
// Is the error a timeout?
Timeout bool
// Is the error a server-side fault?
Fault bool
}
)
// NewDebugDoer wraps the given doer and captures the request and response so
// they can be printed.
func NewDebugDoer(d Doer) DebugDoer {
return &debugDoer{Doer: d}
}
// Do captures the request and response.
func (dd *debugDoer) Do(req *http.Request) (*http.Response, error) {
var reqb []byte
if req.Body != nil {
reqb, _ := ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewBuffer(reqb))
}
resp, err := dd.Doer.Do(req)
if err != nil {
return nil, err
}
respb, err := ioutil.ReadAll(resp.Body)
if err != nil {
respb = []byte(fmt.Sprintf("!!failed to read response: %s", err))
}
resp.Body = ioutil.NopCloser(bytes.NewBuffer(respb))
dd.Response = resp
req.Body = ioutil.NopCloser(bytes.NewBuffer(reqb))
dd.Request = req
dd.Fprint(os.Stderr)
return resp, err
}
// Printf dumps the captured request and response details to w.
func (dd *debugDoer) Fprint(w io.Writer) {
if dd.Request == nil {
return
}
buf := &bytes.Buffer{}
buf.WriteString(fmt.Sprintf("> %s %s", dd.Request.Method, dd.Request.URL.String()))
keys := make([]string, len(dd.Request.Header))
i := 0
for k := range dd.Request.Header {
keys[i] = k
i++
}
sort.Strings(keys)
for _, k := range keys {
buf.WriteString(fmt.Sprintf("\n> %s: %s", k, strings.Join(dd.Request.Header[k], ", ")))
}
b, _ := ioutil.ReadAll(dd.Request.Body)
if len(b) > 0 {
dd.Request.Body = ioutil.NopCloser(bytes.NewBuffer(b)) // reset the request body
buf.WriteByte('\n')
buf.Write(b)
}
if dd.Response == nil {
w.Write(buf.Bytes())
return
}
buf.WriteString(fmt.Sprintf("\n< %s", dd.Response.Status))
keys = make([]string, len(dd.Response.Header))
i = 0
for k := range dd.Response.Header {
keys[i] = k
i++
}
sort.Strings(keys)
for _, k := range keys {
buf.WriteString(fmt.Sprintf("\n< %s: %s", k, strings.Join(dd.Response.Header[k], ", ")))
}
rb, _ := ioutil.ReadAll(dd.Response.Body) // this is reading from a memory buffer so safe to ignore errors
if len(rb) > 0 {
dd.Response.Body = ioutil.NopCloser(bytes.NewBuffer(rb)) // reset the response body
buf.WriteByte('\n')
buf.Write(rb)
}
w.Write(buf.Bytes())
w.Write([]byte{'\n'})
}
// Error builds an error message.
func (c *ClientError) Error() string {
return fmt.Sprintf("[%s %s]: %s", c.Service, c.Method, c.Message)
}
// ErrInvalidType is the error returned when the wrong type is given to a
// method function.
func ErrInvalidType(svc, m, expected string, actual interface{}) error {
msg := fmt.Sprintf("invalid value expected %s, got %v", expected, actual)
return &ClientError{Name: "invalid_type", Message: msg, Service: svc, Method: m}
}
// ErrEncodingError is the error returned when the encoder fails to encode the
// request body.
func ErrEncodingError(svc, m string, err error) error {
msg := fmt.Sprintf("failed to encode request body: %s", err)
return &ClientError{Name: "encoding_error", Message: msg, Service: svc, Method: m}
}
// ErrInvalidURL is the error returned when the URL computed for an method is
// invalid.
func ErrInvalidURL(svc, m, u string, err error) error {
msg := fmt.Sprintf("invalid URL %s: %s", u, err)
return &ClientError{Name: "invalid_url", Message: msg, Service: svc, Method: m}
}
// ErrDecodingError is the error returned when the decoder fails to decode the
// response body.
func ErrDecodingError(svc, m string, err error) error {
msg := fmt.Sprintf("failed to decode response body: %s", err)
return &ClientError{Name: "decoding_error", Message: msg, Service: svc, Method: m}
}
// ErrValidationError is the error returned when the response body is properly
// received and decoded but fails validation.
func ErrValidationError(svc, m string, err error) error {
msg := fmt.Sprintf("invalid response: %s", err)
return &ClientError{Name: "validation_error", Message: msg, Service: svc, Method: m}
}
// ErrInvalidResponse is the error returned when the service responded with an
// unexpected response status code.
func ErrInvalidResponse(svc, m string, code int, body string) error {
var b string
if body != "" {
b = ", body: "
}
msg := fmt.Sprintf("invalid response code %#v"+b+"%s", code, body)
temporary := code == http.StatusServiceUnavailable ||
code == http.StatusConflict ||
code == http.StatusTooManyRequests ||
code == http.StatusGatewayTimeout
timeout := code == http.StatusRequestTimeout ||
code == http.StatusGatewayTimeout
fault := code == http.StatusInternalServerError ||
code == http.StatusNotImplemented ||
code == http.StatusBadGateway
return &ClientError{Name: "invalid_response", Message: msg, Service: svc, Method: m,
Temporary: temporary, Timeout: timeout, Fault: fault}
}
// ErrRequestError is the error returned when the request fails to be sent.
func ErrRequestError(svc, m string, err error) error {
temporary := false
timeout := false
if nerr, ok := err.(net.Error); ok {
temporary = nerr.Temporary()
timeout = nerr.Timeout()
}
return &ClientError{Name: "request_error", Message: err.Error(), Service: svc, Method: m,
Temporary: temporary, Timeout: timeout}
}