| 705 | } |
| 706 | |
| 707 | func healthHandler(db *database.DB, rdb *redisclient.Client) http.HandlerFunc { |
| 708 | return func(w http.ResponseWriter, r *http.Request) { |
| 709 | ctx := r.Context() |
| 710 | dbOK := db.Health(ctx) == nil |
| 711 | redisOK := rdb != nil && rdb.Ping(ctx).Err() == nil |
| 712 | |
| 713 | allHealthy := dbOK && redisOK |
| 714 | |
| 715 | status := http.StatusOK |
| 716 | if !allHealthy { |
| 717 | status = http.StatusServiceUnavailable |
| 718 | } |
| 719 | |
| 720 | // Return structured JSON for monitoring tools. |
| 721 | // Accept header or ?format=json triggers JSON; plain "healthy"/"unhealthy" |
| 722 | // is kept for simple uptime checks (curl, Docker HEALTHCHECK). |
| 723 | if r.URL.Query().Get("format") == "json" || strings.Contains(r.Header.Get("Accept"), "application/json") { |
| 724 | w.Header().Set("Content-Type", "application/json") |
| 725 | w.WriteHeader(status) |
| 726 | _, _ = fmt.Fprintf(w, `{"status":%q,"database":%q,"redis":%q}`, |
| 727 | boolStatus(allHealthy), boolStatus(dbOK), boolStatus(redisOK)) |
| 728 | return |
| 729 | } |
| 730 | |
| 731 | w.WriteHeader(status) |
| 732 | if allHealthy { |
| 733 | _, _ = w.Write([]byte("healthy")) |
| 734 | } else { |
| 735 | _, _ = w.Write([]byte("unhealthy")) |
| 736 | } |
| 737 | } |
| 738 | } |
| 739 | |
| 740 | func boolStatus(ok bool) string { |
| 741 | if ok { |