77 lines
1.7 KiB
Go
77 lines
1.7 KiB
Go
package healthimp
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.sendico.io/tech/sxchnge/product/app/health/status"
|
|
"git.sendico.io/tech/sxchnge/shared/logging"
|
|
"github.com/go-chi/chi/v5"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type Router struct {
|
|
logger mlogger.Logger
|
|
status *Status
|
|
}
|
|
|
|
func (hr *Router) SetStatus(status health.ServiceStatus) {
|
|
hr.SetStatusWithReason(status, defaultReason(status))
|
|
}
|
|
|
|
func (hr *Router) SetStatusWithReason(status health.ServiceStatus, reason string) {
|
|
previous, changed := hr.status.transition(status)
|
|
if !changed {
|
|
return
|
|
}
|
|
reason = strings.TrimSpace(reason)
|
|
if reason == "" {
|
|
reason = defaultReason(status)
|
|
}
|
|
hr.logger.Info("Health status changed",
|
|
zap.String("previous_status", string(previous)),
|
|
zap.String("status", string(status)),
|
|
zap.String("reason", reason),
|
|
)
|
|
}
|
|
|
|
func (hr *Router) Finish() {
|
|
hr.status.Finish()
|
|
hr.logger.Debug("Stopped")
|
|
}
|
|
|
|
func (hr *Router) handle(w http.ResponseWriter, r *http.Request) {
|
|
hr.status.healthHandler()(w, r)
|
|
}
|
|
|
|
func NewRouter(logger mlogger.Logger, router chi.Router, endpoint string) *Router {
|
|
hr := Router{
|
|
logger: logger.Named("health_check"),
|
|
}
|
|
hr.status = StatusHandler(hr.logger)
|
|
|
|
logger.Debug("Installing healthcheck middleware...")
|
|
router.Group(func(r chi.Router) {
|
|
ep := endpoint + "/health"
|
|
r.Get(ep, hr.handle)
|
|
logger.Info("Health handler installed", zap.String("endpoint", ep))
|
|
})
|
|
|
|
return &hr
|
|
}
|
|
|
|
func defaultReason(status health.ServiceStatus) string {
|
|
switch status {
|
|
case health.SSCreated:
|
|
return "service created"
|
|
case health.SSStarting:
|
|
return "service is starting"
|
|
case health.SSRunning:
|
|
return "service is ready"
|
|
case health.SSTerminating:
|
|
return "service is shutting down"
|
|
default:
|
|
return "service health status changed"
|
|
}
|
|
}
|