package handlers import ( "encoding/json" "net/http" "github.com/jackc/pgx/v5/pgxpool" "shop/internal/check" ) type HealthHandler struct { pool *pgxpool.Pool } func NewHealthHandler(pool *pgxpool.Pool) *HealthHandler { return &HealthHandler{pool: pool} } func (h *HealthHandler) Health(w http.ResponseWriter, r *http.Request) { ctx := r.Context() report, err := check.WithDatabase(ctx, h.pool) if err != nil { writeJSON(w, http.StatusServiceUnavailable, map[string]any{ "status": "error", "error": err.Error(), "version": report.AppVersion, }) return } status := "ok" code := http.StatusOK if !report.Healthy() { status = "degraded" code = http.StatusServiceUnavailable } writeJSON(w, code, map[string]any{ "status": status, "app_version": report.AppVersion, "go_version": report.GoVersion, "checks": report.Items, }) } func (h *HealthHandler) Version(w http.ResponseWriter, r *http.Request) { ctx := r.Context() report, _ := check.WithDatabase(ctx, h.pool) writeJSON(w, http.StatusOK, report) } func writeJSON(w http.ResponseWriter, code int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(code) _ = json.NewEncoder(w).Encode(v) }