package health import ( "context" "net/http" "time" "github.com/xlgmokha/x/pkg/serde" "gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/db" ) type Controller struct { dbConnection *db.Connection } func New(dbConnection *db.Connection) *Controller { return &Controller{ dbConnection: dbConnection, } } func (c *Controller) MountTo(mux *http.ServeMux) { mux.Handle("GET /-/health", http.HandlerFunc(c.Health)) mux.Handle("GET /-/health/database", http.HandlerFunc(c.Database)) } func (c *Controller) Health(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) serde.ToHTTP(w, r, map[string]string{"status": "ok"}) } func (c *Controller) Database(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) defer cancel() if c.dbConnection.IsHealthy(ctx) { w.WriteHeader(http.StatusOK) serde.ToHTTP(w, r, map[string]string{"database": "ok"}) } else { w.WriteHeader(http.StatusServiceUnavailable) serde.ToHTTP(w, r, map[string]string{"database": "unavailable"}) } }