forked from tavsec/gin-healthcheck
/
healthcheck_controller.go
76 lines (62 loc) · 1.5 KB
/
healthcheck_controller.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
package controllers
import (
"errors"
"sync"
"github.com/gin-gonic/gin"
"github.com/rsmnarts/gin-healthcheck/checks"
"github.com/rsmnarts/gin-healthcheck/config"
"golang.org/x/sync/errgroup"
)
type CheckStatus struct {
Name string `json:"name"`
Pass bool `json:"pass"`
}
var (
ErrHealthcheckFailed = errors.New("healthcheck failed")
lock sync.Mutex
failureInARow uint32
)
func Healthcheck(checks []checks.Check, config config.Config) (int, []CheckStatus) {
var (
eg errgroup.Group
statuses = make([]CheckStatus, len(checks))
httpStatus = config.StatusOK
)
for idx, check := range checks {
captureCheck := check
captureIdx := idx
eg.Go(func() error {
pass := captureCheck.Pass()
statuses[captureIdx] = CheckStatus{
Name: captureCheck.Name(),
Pass: pass,
}
if !pass {
return ErrHealthcheckFailed
}
return nil
})
}
lock.Lock()
if err := eg.Wait(); err != nil {
httpStatus = config.StatusNotOK
failureInARow += 1
if failureInARow >= config.FailureNotification.Threshold &&
config.FailureNotification.Chan != nil {
config.FailureNotification.Chan <- err
}
} else {
if failureInARow != 0 && config.FailureNotification.Chan != nil {
failureInARow = 0
config.FailureNotification.Chan <- nil
}
}
lock.Unlock()
return httpStatus, statuses
}
func HealthcheckController(checks []checks.Check, config config.Config) gin.HandlerFunc {
fn := func(c *gin.Context) {
c.JSON(Healthcheck(checks, config))
}
return gin.HandlerFunc(fn)
}