-
Notifications
You must be signed in to change notification settings - Fork 7
/
checks.go
49 lines (37 loc) · 1.18 KB
/
checks.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
package healthcheck
import (
"context"
"fmt"
"net/http"
"time"
"github.com/nexmoinc/gosrvlib/pkg/logging"
)
// HTTPClient contains the function that performs the actual HTTP request.
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
// CheckHTTPStatus checks if the given HTTP request responds with the expected status code.
func CheckHTTPStatus(ctx context.Context, httpClient HTTPClient, method string, url string, wantStatusCode int, timeout time.Duration, opts ...CheckOption) error {
cfg := checkConfig{}
for _, apply := range opts {
apply(&cfg)
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, url, nil)
if err != nil {
return fmt.Errorf("build request: %w", err)
}
if cfg.configureRequest != nil {
cfg.configureRequest(req)
}
resp, err := httpClient.Do(req) // nolint:bodyclose
if err != nil {
return fmt.Errorf("healthcheck request: %w", err)
}
defer logging.Close(ctx, resp.Body, "error while closing CheckHTTPStatus response body")
if resp.StatusCode != wantStatusCode {
return fmt.Errorf("unexpected healthcheck status code: %d", resp.StatusCode)
}
return nil
}