package handlers import ( "context" "encoding/json" "net/http" "time" "github.com/jmoiron/sqlx" ) type HealthHandler struct { db *sqlx.DB version string startedAt time.Time } func NewHealthHandler(db *sqlx.DB, version string) *HealthHandler { return &HealthHandler{db: db, version: version, startedAt: time.Now()} } func (h *HealthHandler) Healthz(w http.ResponseWriter, r *http.Request) { ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() dbOK := h.db.PingContext(ctx) == nil status := http.StatusOK if !dbOK { status = http.StatusServiceUnavailable } w.Header().Set("content-type", "application/json") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(map[string]any{ "ok": dbOK, "version": h.version, "uptime_s": int(time.Since(h.startedAt).Seconds()), "checked_at": time.Now().UTC().Format(time.RFC3339), }) }