72 lines
1.7 KiB
Go
72 lines
1.7 KiB
Go
|
package healthcheck
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"time"
|
||
|
|
||
|
"git.eeqj.de/sneak/gohttpserver/internal/config"
|
||
|
"git.eeqj.de/sneak/gohttpserver/internal/database"
|
||
|
"git.eeqj.de/sneak/gohttpserver/internal/globals"
|
||
|
"git.eeqj.de/sneak/gohttpserver/internal/logger"
|
||
|
"github.com/rs/zerolog"
|
||
|
"go.uber.org/fx"
|
||
|
)
|
||
|
|
||
|
type HealthcheckParams struct {
|
||
|
fx.In
|
||
|
Globals *globals.Globals
|
||
|
Config *config.Config
|
||
|
Logger *logger.Logger
|
||
|
Database *database.Database
|
||
|
}
|
||
|
|
||
|
type Healthcheck struct {
|
||
|
StartupTime time.Time
|
||
|
log *zerolog.Logger
|
||
|
params *HealthcheckParams
|
||
|
}
|
||
|
|
||
|
func New(lc fx.Lifecycle, params HealthcheckParams) (*Healthcheck, error) {
|
||
|
s := new(Healthcheck)
|
||
|
s.params = ¶ms
|
||
|
s.log = params.Logger.Get()
|
||
|
|
||
|
lc.Append(fx.Hook{
|
||
|
OnStart: func(ctx context.Context) error {
|
||
|
s.StartupTime = time.Now()
|
||
|
return nil
|
||
|
},
|
||
|
OnStop: func(ctx context.Context) error {
|
||
|
// FIXME do server shutdown here
|
||
|
return nil
|
||
|
},
|
||
|
})
|
||
|
return s, nil
|
||
|
}
|
||
|
|
||
|
type HealthcheckResponse struct {
|
||
|
Status string `json:"status"`
|
||
|
Now string `json:"now"`
|
||
|
UptimeSeconds int64 `json:"uptime_seconds"`
|
||
|
UptimeHuman string `json:"uptime_human"`
|
||
|
Version string `json:"version"`
|
||
|
Appname string `json:"appname"`
|
||
|
Maintenance bool `json:"maintenance_mode"`
|
||
|
}
|
||
|
|
||
|
func (s *Healthcheck) uptime() time.Duration {
|
||
|
return time.Since(s.StartupTime)
|
||
|
}
|
||
|
|
||
|
func (s *Healthcheck) Healthcheck() *HealthcheckResponse {
|
||
|
resp := &HealthcheckResponse{
|
||
|
Status: "ok",
|
||
|
Now: time.Now().UTC().Format(time.RFC3339Nano),
|
||
|
UptimeSeconds: int64(s.uptime().Seconds()),
|
||
|
UptimeHuman: s.uptime().String(),
|
||
|
Appname: s.params.Globals.Appname,
|
||
|
Version: s.params.Globals.Version,
|
||
|
}
|
||
|
return resp
|
||
|
}
|