/
profiler.go
70 lines (59 loc) · 1.47 KB
/
profiler.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
package app
import (
"context"
"database/sql"
"fmt"
"net/http"
"time"
"github.com/labstack/echo/v4"
"github.com/typical-go/typical-go/pkg/typgo"
"github.com/typical-go/typical-rest-server/pkg/cachekit"
"github.com/typical-go/typical-rest-server/pkg/restkit"
"go.uber.org/dig"
)
type (
// HealthCheck ...
HealthCheck struct {
dig.In
PG *sql.DB `name:"pg"`
// MySQL *sql.DB `name:"mysql"`
Cache *cachekit.Store
}
)
const (
healthCheckPath = "/application/health"
)
// SetProfiler ...
func SetProfiler(e *echo.Echo, hc HealthCheck) {
e.GET(healthCheckPath, hc.Handle)
e.HEAD(healthCheckPath, hc.Handle)
e.GET("/debug/*", echo.WrapHandler(http.DefaultServeMux))
e.GET("/debug/*/*", echo.WrapHandler(http.DefaultServeMux))
}
//
// HealthCheck
//
// Handle echo function
func (h *HealthCheck) Handle(ec echo.Context) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
health := restkit.HealthMap{
"postgres": h.PG.Ping(),
// "mysql": h.MySQL.Ping(),
"cache": h.Cache.Ping(ctx).Err(),
}
status, ok := health.Status()
return ec.JSON(h.httpStatus(ok), h.response(status))
}
func (h *HealthCheck) httpStatus(ok bool) int {
if ok {
return http.StatusOK
}
return http.StatusServiceUnavailable
}
func (h *HealthCheck) response(status map[string]string) map[string]interface{} {
return map[string]interface{}{
"name": fmt.Sprintf("%s (%s)", typgo.ProjectName, typgo.ProjectVersion),
"status": status,
}
}