-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
86 lines (72 loc) · 2.32 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
package client
import (
"io"
"net/http"
"github.com/sirupsen/logrus"
internalHTTP "github.com/artii15/termination-detector/pkg/http"
"github.com/pkg/errors"
)
type RequestModifier interface {
ModifyRequest(request *http.Request) error
}
type RequestToNativeConverter interface {
ConvertRequestToNative()
}
type HTTPRequestDoer interface {
Do(request *http.Request) (*http.Response, error)
}
type Client struct {
requestDoer HTTPRequestDoer
baseURL string
requestModifiers []RequestModifier
}
func New(httpRequestDoer HTTPRequestDoer, baseURL string, requestModifiers ...RequestModifier) *Client {
return &Client{
requestDoer: httpRequestDoer,
baseURL: baseURL,
requestModifiers: requestModifiers,
}
}
func (executor *Client) ExecuteRequest(request internalHTTP.Request) (internalHTTP.Response, error) {
httpRequest, err := executor.buildHTTPRequest(request)
if err != nil {
return internalHTTP.Response{}, err
}
return executor.executeNativeRequest(httpRequest)
}
func (executor *Client) buildHTTPRequest(request internalHTTP.Request) (*http.Request, error) {
httpRequest, err := InternalRequestToNative(executor.baseURL, request)
if err != nil {
return nil, errors.Wrapf(err, "failed to convert request: %+v", request)
}
for _, requestModifier := range executor.requestModifiers {
if err := requestModifier.ModifyRequest(httpRequest); err != nil {
return nil, errors.Wrapf(err, "failed to modify request: %+v", httpRequest)
}
}
return httpRequest, nil
}
func (executor *Client) executeNativeRequest(request *http.Request) (internalHTTP.Response, error) {
response, err := executor.requestDoer.Do(request)
if err != nil {
return internalHTTP.Response{}, errors.Wrapf(err, "failed to execute request: %+v", request)
}
defer closeResponseBody(response.Body)
responseBody, err := readResponseBody(response.Body)
if err != nil {
return internalHTTP.Response{}, errors.Wrapf(err, "failed to read response body: %+v", response)
}
return internalHTTP.Response{
StatusCode: response.StatusCode,
Body: responseBody,
Headers: readHeaders(response.Header),
}, nil
}
func closeResponseBody(responseBody io.Closer) {
if responseBody == nil {
return
}
if err := responseBody.Close(); err != nil {
logrus.WithError(err).Error("failed to close http response body")
}
}