This repository has been archived by the owner on Apr 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
74 lines (61 loc) · 1.72 KB
/
http.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
package healthz
import (
"net/http"
"time"
)
// HTTPChecker checks if an HTTP endpoint is available and successfully responds.
type HTTPChecker struct {
url string
timeout time.Duration
method string
}
// HTTPCheckerOption configures how we check the HTTP endpoint.
type HTTPCheckerOption func(*HTTPChecker)
// WithHTTPTimeout returns an HTTPCheckerOption that specifies the timeout for HTTP requests.
//
// Setting a timeout is highly recommended, but it needs to be carefully chosen to avoid false results.
func WithHTTPTimeout(timeout time.Duration) HTTPCheckerOption {
return func(c *HTTPChecker) {
c.timeout = timeout
}
}
// WithHTTPMethod returns an HTTPCheckerOption that specifies the method for HTTP requests.
//
// The default method is "GET" which works in most of the cases, but another popular choice is "HEAD".
func WithHTTPMethod(method string) HTTPCheckerOption {
return func(c *HTTPChecker) {
c.method = method
}
}
// NewHTTPChecker creates a new HTTPChecker with a URL and optional configuration.
//
// Example:
// checker := healthz.NewHTTPChecker("http://example.com", healthz.WithHTTPTimeout(3*time.Second))
func NewHTTPChecker(url string, opts ...HTTPCheckerOption) *HTTPChecker {
checker := &HTTPChecker{
url: url,
method: http.MethodGet,
}
for _, opt := range opts {
opt(checker)
}
return checker
}
// Check implements the Checker interface and checks the HTTP endpoint status.
func (c *HTTPChecker) Check() error {
client := &http.Client{
Timeout: c.timeout,
}
req, err := http.NewRequest(c.method, c.url, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return ErrCheckFailed
}
return nil
}