/
health.go
65 lines (55 loc) · 1.38 KB
/
health.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
package health
import (
"context"
"time"
"github.com/AdmiralBulldogTv/VodApi/src/global"
"github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
)
func New(gCtx global.Context) <-chan struct{} {
server := fasthttp.Server{
Handler: func(ctx *fasthttp.RequestCtx) {
start := time.Now()
defer func() {
l := logrus.WithFields(logrus.Fields{
"status": ctx.Response.StatusCode(),
"duration": time.Since(start) / time.Millisecond,
"entrypoint": "health",
})
if err := recover(); err != nil {
l.Error("panic in handler: ", err)
} else {
l.Info("")
}
}()
ctx.SetStatusCode(200)
redisCtx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if err := gCtx.Inst().Redis.Ping(redisCtx); err != nil {
logrus.Error("redis down: ", err)
ctx.SetStatusCode(503)
return
}
mongoCtx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if err := gCtx.Inst().Mongo.Ping(mongoCtx); err != nil {
logrus.Error("mongo down: ", err)
ctx.SetStatusCode(503)
}
},
GetOnly: true,
DisableKeepalive: true,
}
go func() {
if err := server.ListenAndServe(gCtx.Config().Health.Bind); err != nil {
logrus.Fatal("failed to start health bind: ", err)
}
}()
done := make(chan struct{})
go func() {
<-gCtx.Done()
_ = server.Shutdown()
close(done)
}()
return done
}