-
Notifications
You must be signed in to change notification settings - Fork 0
/
health_checker.go
62 lines (56 loc) · 1.33 KB
/
health_checker.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
package http
import (
"context"
"fmt"
"io"
"net"
"net/http"
"time"
)
type HealthChecker struct {
name string
url string
timeout time.Duration
}
func NewHealthChecker(name, url string, options ...time.Duration) *HealthChecker {
if len(options) >= 1 && options[0] > 0 {
return &HealthChecker{name, url, options[0]}
} else {
return &HealthChecker{name, url, 4 * time.Second}
}
}
func (s *HealthChecker) Name() string {
return s.name
}
func (s *HealthChecker) Check(ctx context.Context) (map[string]interface{}, error) {
res := make(map[string]interface{})
client := http.Client{
Timeout: s.timeout,
// never follow redirects
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
resp, err := client.Get(s.url)
if e, ok := err.(net.Error); ok && e.Timeout() {
return res, fmt.Errorf("time out: %w", e)
} else if err != nil {
return res, err
}
_, _ = io.Copy(io.Discard, resp.Body)
_ = resp.Body.Close()
if resp.StatusCode >= 500 {
return res, fmt.Errorf("status code is: %d", resp.StatusCode)
}
return res, nil
}
func (s *HealthChecker) Build(ctx context.Context, data map[string]interface{}, err error) map[string]interface{} {
if err == nil {
return data
}
if data == nil {
data = make(map[string]interface{})
}
data["error"] = err.Error()
return data
}