-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
193 lines (166 loc) · 4.4 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
package cantabularmetadata
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
dperrors "github.com/ONSdigital/dp-api-clients-go/v2/errors"
"github.com/ONSdigital/dp-api-clients-go/v2/health"
"github.com/ONSdigital/dp-healthcheck/healthcheck"
"github.com/ONSdigital/log.go/v2/log"
)
// Cantabular service names
const (
Service = "cantabularMetadata"
SoftwareVersion = "v10"
)
// Client is the client for interacting with the Cantabular API
type Client struct {
ua httpClient
host string
version string
}
// NewClient returns a new Client
func NewClient(cfg Config, ua httpClient) *Client {
c := &Client{
ua: ua,
host: cfg.Host,
version: SoftwareVersion,
}
return c
}
// httpGet makes a get request to the given url and returns the response
func (c *Client) httpGet(ctx context.Context, path string) (*http.Response, error) {
URL, err := url.Parse(path)
if err != nil {
return nil, dperrors.New(
fmt.Errorf("failed to parse url: %s", err),
http.StatusBadRequest,
log.Data{
"url": path,
},
)
}
path = URL.String()
resp, err := c.ua.Get(ctx, path)
if err != nil {
return nil, dperrors.New(
fmt.Errorf("failed to make request: %w", err),
http.StatusInternalServerError,
log.Data{
"url": path,
"method": "GET",
},
)
}
return resp, nil
}
// httpPost makes a post request to the given url and returns the response
func (c *Client) httpPost(ctx context.Context, path string, contentType string, body io.Reader) (*http.Response, error) {
URL, err := url.Parse(path)
if err != nil {
return nil, dperrors.New(
fmt.Errorf("failed to parse url: %s", err),
http.StatusBadRequest,
log.Data{
"url": path,
},
)
}
path = URL.String()
resp, err := c.ua.Post(ctx, path, contentType, body)
if err != nil {
return nil, dperrors.New(
fmt.Errorf("failed to make request: %w", err),
http.StatusInternalServerError,
log.Data{
"url": path,
"method": "post",
},
)
}
return resp, nil
}
// Checker contacts the /graphql endpoint with an empty query and updates the healthcheck state accordingly.
func (c *Client) Checker(ctx context.Context, state *healthcheck.CheckState) error {
reqURL := fmt.Sprintf("%s/graphql?query={}", c.host)
return c.checkHealth(ctx, state, Service, reqURL)
}
func (c *Client) checkHealth(ctx context.Context, state *healthcheck.CheckState, service, reqURL string) error {
logData := log.Data{
"service": service,
}
code := 0
res, err := c.httpGet(ctx, reqURL)
defer closeResponseBody(ctx, res)
if err != nil {
log.Error(ctx, "failed to request service health", err, logData)
} else {
code = res.StatusCode
}
switch code {
case 0: // When there is a problem with the client return error in message
return state.Update(healthcheck.StatusCritical, err.Error(), 0)
case 200:
message := service + health.StatusMessage[healthcheck.StatusOK]
return state.Update(healthcheck.StatusOK, message, code)
default:
message := service + health.StatusMessage[healthcheck.StatusCritical]
return state.Update(healthcheck.StatusCritical, message, code)
}
}
// errorResponse handles dealing with an error response from Cantabular
func (c *Client) errorResponse(url string, res *http.Response) error {
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return dperrors.New(
fmt.Errorf("failed to read error response body: %s", err),
res.StatusCode,
log.Data{
"url": url,
},
)
}
if len(b) == 0 {
b = []byte("[response body empty]")
}
var resp ErrorResponse
if err := json.Unmarshal(b, &resp); err != nil {
return dperrors.New(
fmt.Errorf("failed to unmarshal error response body: %s", err),
res.StatusCode,
log.Data{
"url": url,
"response_body": string(b),
},
)
}
return dperrors.New(
errors.New(resp.Message),
res.StatusCode,
log.Data{
"url": url,
},
)
}
// StatusCode provides a callback function whereby users can check a returned
// error for an embedded HTTP status code
func (c *Client) StatusCode(err error) int {
var cerr coder
if errors.As(err, &cerr) {
return cerr.Code()
}
return 0
}
// closeResponseBody closes the response body and logs an error if unsuccessful
func closeResponseBody(ctx context.Context, resp *http.Response) {
if resp != nil && resp.Body != nil {
if err := resp.Body.Close(); err != nil {
log.Error(ctx, "error closing http response body", err)
}
}
}