forked from intel/trustauthority-client-for-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
76 lines (63 loc) · 1.86 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
/*
* Copyright (c) 2022-2023 Intel Corporation
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
package connector
import (
"crypto/tls"
"io"
"net/http"
"github.com/hashicorp/go-retryablehttp"
"github.com/pkg/errors"
)
// doRequest creates an API request, sends the API request and returns the API response
func doRequest(rclient retryablehttp.Client, tlsCfg *tls.Config,
newRequest func() (*http.Request, error),
queryParams map[string]string,
headers map[string]string,
processResponse func(*http.Response) error) error {
var req *http.Request
var err error
if req, err = newRequest(); err != nil {
return err
}
if queryParams != nil {
q := req.URL.Query()
for param, val := range queryParams {
q.Add(param, val)
}
req.URL.RawQuery = q.Encode()
}
for name, val := range headers {
req.Header.Add(name, val)
}
httpClient := &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsCfg,
Proxy: http.ProxyFromEnvironment,
},
}
rclient.HTTPClient = httpClient
var resp *http.Response
if resp, err = rclient.StandardClient().Do(req); err != nil {
return errors.Errorf("Request to %q failed: %s", req.URL, err)
}
if resp != nil {
defer func() {
err := resp.Body.Close()
if err != nil {
errors.Errorf("Failed to close response body")
}
}()
}
if resp.StatusCode != http.StatusOK || resp.ContentLength == 0 {
traceId, requestId := resp.Header.Get(HeaderTraceId), resp.Header.Get(HeaderRequestId)
response, err := io.ReadAll(resp.Body)
if err != nil {
return errors.Errorf("Failed to read response body: %s, Trace-Id = %s, Request-Id = %s", err, traceId, requestId)
}
return errors.Errorf("Request to %q failed: StatusCode = %d, Response = %s, Trace-Id = %s, Request-Id = %s", req.URL, resp.StatusCode, string(response), traceId, requestId)
}
return processResponse(resp)
}