/
request.go
353 lines (297 loc) · 9.33 KB
/
request.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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
/*******************************************************************************
* Copyright 2019 Dell Inc.
* Copyright 2019 Joan Duran
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package clients
import (
"bytes"
"context"
"encoding/json"
"github.com/google/uuid"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"path/filepath"
"strconv"
"github.com/edgexfoundry/go-mod-core-contracts/clients/interfaces"
"github.com/edgexfoundry/go-mod-core-contracts/clients/types"
)
// Helper method to get the body from the response after making the request
func getBody(resp *http.Response) ([]byte, error) {
body, err := ioutil.ReadAll(resp.Body)
return body, err
}
// Helper method to make the request and return the response
func makeRequest(req *http.Request) (*http.Response, error) {
client := &http.Client{}
resp, err := client.Do(req)
return resp, err
}
// GetRequest will make a GET request to the specified URL with the root URL retrieved by the URLClient prepended.
// It returns the body as a byte array if successful and an error otherwise.
func GetRequest(ctx context.Context, urlSuffix string, urlClient interfaces.URLClient) ([]byte, error) {
urlPrefix, err := urlClient.Prefix()
if err != nil {
return nil, err
}
return GetRequestWithURL(ctx, urlPrefix+urlSuffix)
}
// GetRequestWithURL will make a GET request to the specified URL.
// It returns the body as a byte array if successful and an error otherwise.
func GetRequestWithURL(ctx context.Context, url string) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
c := NewCorrelatedRequest(ctx, req)
resp, err := makeRequest(c.Request)
if err != nil {
return nil, err
}
if resp == nil {
return nil, types.ErrResponseNil{}
}
defer resp.Body.Close()
bodyBytes, err := getBody(resp)
if err != nil {
return nil, err
}
if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) {
return nil, types.NewErrServiceClient(resp.StatusCode, bodyBytes)
}
return bodyBytes, nil
}
// Helper method to make the count request
func CountRequest(ctx context.Context, urlSuffix string, urlClient interfaces.URLClient) (int, error) {
// do not get URLPrefix here since GetRequest does it
data, err := GetRequest(ctx, urlSuffix, urlClient)
if err != nil {
return 0, err
}
count, err := strconv.Atoi(string(data))
if err != nil {
return 0, err
}
return count, nil
}
// Helper method to make the post JSON request and return the body
func PostJSONRequest(
ctx context.Context,
urlSuffix string,
data interface{},
urlClient interfaces.URLClient) (string, error) {
jsonStr, err := json.Marshal(data)
if err != nil {
return "", err
}
ctx = context.WithValue(ctx, ContentType, ContentTypeJSON)
// do not get URLPrefix here since PostRequest does it
return PostRequest(ctx, urlSuffix, jsonStr, urlClient)
}
// PostJSONRequestWithURL will make a POST request to the specified URL with the object passed in
// marshaled into a JSON formatted byte array.
// It returns the body on success and an error otherwise.
func PostJSONRequestWithURL(ctx context.Context, url string, data interface{}) (string, error) {
jsonStr, err := json.Marshal(data)
if err != nil {
return "", err
}
ctx = context.WithValue(ctx, ContentType, ContentTypeJSON)
return PostRequestWithURL(ctx, url, jsonStr)
}
// Helper method to make the post request and return the body
func PostRequest(ctx context.Context, urlSuffix string, data []byte, urlClient interfaces.URLClient) (string, error) {
urlPrefix, err := urlClient.Prefix()
if err != nil {
return "", err
}
return PostRequestWithURL(ctx, urlPrefix+urlSuffix, data)
}
// PostRequestWithURL will make a POST request to the specified URL.
// It returns the body as a byte array if successful and an error otherwise.
func PostRequestWithURL(ctx context.Context, url string, data []byte) (string, error) {
content := FromContext(ctx, ContentType)
if content == "" {
content = ContentTypeJSON
}
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
if err != nil {
return "", err
}
req.Header.Set(ContentType, content)
c := NewCorrelatedRequest(ctx, req)
resp, err := makeRequest(c.Request)
if err != nil {
return "", err
}
if resp == nil {
return "", types.ErrResponseNil{}
}
defer resp.Body.Close()
bodyBytes, err := getBody(resp)
if err != nil {
return "", err
}
if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) {
return "", types.NewErrServiceClient(resp.StatusCode, bodyBytes)
}
bodyString := string(bodyBytes)
return bodyString, nil
}
// Helper method to make a post request in order to upload a file and return the request body
func UploadFileRequest(
ctx context.Context,
urlSuffix string,
filePath string,
urlClient interfaces.URLClient) (string, error) {
fileContents, err := ioutil.ReadFile(filePath)
if err != nil {
return "", err
}
// Create multipart/form-data request
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
formFileWriter, err := writer.CreateFormFile("file", filepath.Base(filePath))
if err != nil {
return "", err
}
_, err = io.Copy(formFileWriter, bytes.NewReader(fileContents))
if err != nil {
return "", err
}
writer.Close()
urlPrefix, err := urlClient.Prefix()
if err != nil {
return "", err
}
req, err := http.NewRequest(http.MethodPost, urlPrefix+urlSuffix, body)
if err != nil {
return "", err
}
req.Header.Add(ContentType, writer.FormDataContentType())
c := NewCorrelatedRequest(ctx, req)
resp, err := makeRequest(c.Request)
if err != nil {
return "", err
}
if resp == nil {
return "", types.ErrResponseNil{}
}
defer resp.Body.Close()
bodyBytes, err := getBody(resp)
if err != nil {
return "", err
}
if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) {
return "", types.NewErrServiceClient(resp.StatusCode, bodyBytes)
}
bodyString := string(bodyBytes)
return bodyString, nil
}
// Helper method to make the update request
func UpdateRequest(ctx context.Context, urlSuffix string, data interface{}, urlClient interfaces.URLClient) error {
jsonStr, err := json.Marshal(data)
if err != nil {
return err
}
// do not get URLPrefix here since PutRequest does it
_, err = PutRequest(ctx, urlSuffix, jsonStr, urlClient)
return err
}
// Helper method to make the put request
func PutRequest(ctx context.Context, urlSuffix string, body []byte, urlClient interfaces.URLClient) (string, error) {
var err error
var req *http.Request
urlPrefix, err := urlClient.Prefix()
if err != nil {
return "", err
}
if body != nil {
req, err = http.NewRequest(http.MethodPut, urlPrefix+urlSuffix, bytes.NewReader(body))
if err != nil {
return "", err
}
content := FromContext(ctx, ContentType)
if content == "" {
content = ContentTypeJSON
}
req.Header.Set(ContentType, content)
} else {
req, err = http.NewRequest(http.MethodPut, urlPrefix+urlSuffix, nil)
}
if err != nil {
return "", err
}
c := NewCorrelatedRequest(ctx, req)
resp, err := makeRequest(c.Request)
if err != nil {
return "", err
}
if resp == nil {
return "", types.ErrResponseNil{}
}
defer resp.Body.Close()
bodyBytes, err := getBody(resp)
if err != nil {
return "", err
}
if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) {
return "", types.NewErrServiceClient(resp.StatusCode, bodyBytes)
}
bodyString := string(bodyBytes)
return bodyString, nil
}
// Helper method to make the delete request
func DeleteRequest(ctx context.Context, urlSuffix string, urlClient interfaces.URLClient) error {
urlPrefix, err := urlClient.Prefix()
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodDelete, urlPrefix+urlSuffix, nil)
if err != nil {
return err
}
c := NewCorrelatedRequest(ctx, req)
resp, err := makeRequest(c.Request)
if err != nil {
return err
}
if resp == nil {
return types.ErrResponseNil{}
}
defer resp.Body.Close()
if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusAccepted) {
bodyBytes, err := getBody(resp)
if err != nil {
return err
}
return types.NewErrServiceClient(resp.StatusCode, bodyBytes)
}
return nil
}
// CorrelatedRequest is a wrapper type for use in managing Correlation IDs during service to service API calls.
type CorrelatedRequest struct {
*http.Request
}
// NewCorrelatedRequest will add the Correlation ID header to the supplied request. If no Correlation ID header is
// present in the supplied context, one will be created along with a value.
func NewCorrelatedRequest(ctx context.Context, req *http.Request) CorrelatedRequest {
c := CorrelatedRequest{Request: req}
correlation := FromContext(ctx, CorrelationHeader)
if len(correlation) == 0 {
correlation = uuid.New().String()
}
c.Header.Set(CorrelationHeader, correlation)
return c
}