This repository has been archived by the owner on Oct 2, 2022. It is now read-only.
generated from ContainerSSH/library-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient_impl.go
240 lines (220 loc) · 5.33 KB
/
client_impl.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
package http
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/containerssh/log"
"github.com/gorilla/schema"
)
type client struct {
config ClientConfiguration
logger log.Logger
tlsConfig *tls.Config
extraHeaders map[string][]string
allowLaxDecoding bool
}
func (c *client) Put(
path string,
requestBody interface{},
responseBody interface{},
) (statusCode int, err error) {
return c.request(
http.MethodPut,
path,
requestBody,
responseBody,
)
}
func (c *client) Patch(
path string,
requestBody interface{},
responseBody interface{},
) (statusCode int, err error) {
return c.request(
http.MethodPatch,
path,
requestBody,
responseBody,
)
}
func (c *client) Delete(
path string,
requestBody interface{},
responseBody interface{},
) (statusCode int, err error) {
return c.request(
http.MethodDelete,
path,
requestBody,
responseBody,
)
}
func (c *client) Request(Method string, path string, requestBody interface{}, responseBody interface{}) (statusCode int, err error) {
return c.request(
Method,
path,
requestBody,
responseBody,
)
}
func (c *client) Get(path string, responseBody interface{}) (statusCode int, err error) {
return c.request(
http.MethodGet,
path,
nil,
responseBody,
)
}
func (c *client) Post(
path string,
requestBody interface{},
responseBody interface{},
) (
int,
error,
) {
return c.request(
http.MethodPost,
path,
requestBody,
responseBody,
)
}
func (c *client) request(
method string,
path string,
requestBody interface{},
responseBody interface{},
) (int, error) {
logger := c.logger.WithLabel("method", method).WithLabel("path", path)
httpClient := c.createHTTPClient(logger)
req, err := c.createRequest(method, path, requestBody, logger)
if err != nil {
return 0, err
}
logger.Debug(log.NewMessage(MClientRequest, "HTTP %s request to %s%s", method, c.config.URL, path))
resp, err := httpClient.Do(req)
if err != nil {
var typedError log.Message
if errors.As(err, &typedError) {
return 0, err
}
err = log.Wrap(err, EFailureConnectionFailed, "HTTP %s request to %s%s failed", method, c.config.URL, path)
logger.Debug(err)
return 0, err
}
defer func() { _ = resp.Body.Close() }()
logger.Debug(log.NewMessage(
MClientResponse,
"HTTP response with status %d",
resp.StatusCode,
).Label("statusCode", resp.StatusCode))
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
err = log.Wrap(err, EFailureConnectionFailed, "HTTP %s request to %s%s failed", method, c.config.URL, path)
logger.Debug(err)
return 0, err
}
if responseBody == nil {
return resp.StatusCode, nil
}
decoder := json.NewDecoder(bytes.NewReader(body))
if !c.allowLaxDecoding {
decoder.DisallowUnknownFields()
}
if err := decoder.Decode(responseBody); err != nil {
err = log.Wrap(err, EFailureDecodeFailed, "Failed to decode HTTP response")
logger.Debug(err)
return resp.StatusCode, err
}
return resp.StatusCode, nil
}
func (c *client) createRequest(method string, path string, requestBody interface{}, logger log.Logger) (
*http.Request,
error,
) {
buffer := &bytes.Buffer{}
switch c.config.RequestEncoding {
case RequestEncodingDefault:
fallthrough
case RequestEncodingJSON:
err := json.NewEncoder(buffer).Encode(requestBody)
if err != nil {
//This is a bug
err := log.Wrap(err, EFailureEncodeFailed, "BUG: HTTP request encoding failed")
logger.Critical(err)
return nil, err
}
case RequestEncodingWWWURLEncoded:
encoder := schema.NewEncoder()
form := url.Values{}
if err := encoder.Encode(requestBody, form); err != nil {
err := log.Wrap(err, EFailureEncodeFailed, "BUG: HTTP request encoding failed")
logger.Critical(err)
return nil, err
}
buffer.WriteString(form.Encode())
default:
panic(fmt.Errorf("invalid request encoding: %s", c.config.RequestEncoding))
}
req, err := http.NewRequest(
method,
fmt.Sprintf("%s%s", c.config.URL, path),
buffer,
)
if err != nil {
err := log.Wrap(err, EFailureEncodeFailed, "BUG: HTTP request encoding failed")
logger.Critical(err)
return nil, err
}
for header, values := range c.extraHeaders {
for i, value := range values {
if i == 0 {
req.Header.Set(header, value)
} else {
req.Header.Add(header, value)
}
}
}
switch c.config.RequestEncoding {
case RequestEncodingDefault:
fallthrough
case RequestEncodingJSON:
req.Header.Set("Content-Type", "application/json")
case RequestEncodingWWWURLEncoded:
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
default:
panic(fmt.Errorf("invalid request encoding: %s", c.config.RequestEncoding))
}
req.Header.Set("Accept", "application/json")
return req, nil
}
func (c *client) createHTTPClient(logger log.Logger) *http.Client {
transport := &http.Transport{
TLSClientConfig: c.tlsConfig,
}
httpClient := &http.Client{
Transport: transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if !c.config.AllowRedirects {
return log.NewMessage(
EClientRedirectsDisabled,
"Redirects disabled, server tried to redirect to %s", req.URL,
).Label("redirect", req.URL)
}
logger.Debug(
log.NewMessage(
MClientRedirect, "HTTP redirect to %s", req.URL,
).Label("redirect", req.URL),
)
return nil
},
Timeout: c.config.Timeout,
}
return httpClient
}