Files
ai-ops/internal/handler/health_handler.go
2026-05-12 17:48:22 +08:00

63 lines
1.6 KiB
Go

package handler
import (
"net/http"
"github.com/company/ai-ops/internal/database"
"github.com/company/ai-ops/internal/redis"
"github.com/company/ai-ops/pkg/response"
)
// HealthHandler 是健康检查 HTTP 处理器
type HealthHandler struct{}
func NewHealthHandler() *HealthHandler {
return &HealthHandler{}
}
func (h *HealthHandler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /actuator/health", h.Health)
mux.HandleFunc("GET /actuator/health/live", h.Live)
mux.HandleFunc("GET /actuator/health/ready", h.Ready)
}
func (h *HealthHandler) Health(w http.ResponseWriter, r *http.Request) {
response.Success(w, map[string]any{
"status": "UP",
"components": map[string]any{
"self": map[string]any{"status": "UP"},
},
})
}
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
response.Success(w, map[string]any{"status": "UP"})
}
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
status := "UP"
components := map[string]any{
"self": map[string]any{"status": "UP"},
}
// 检查 DB 连接
if database.Pool == nil {
status = "DOWN"
components["database"] = map[string]any{"status": "DOWN", "detail": "not initialized"}
} else {
components["database"] = map[string]any{"status": "UP"}
}
// 检查 Redis 连接
if redis.Client == nil {
components["redis"] = map[string]any{"status": "DOWN", "detail": "not initialized"}
} else {
components["redis"] = map[string]any{"status": "UP"}
}
if status == "DOWN" {
w.WriteHeader(http.StatusServiceUnavailable)
}
response.Success(w, map[string]any{"status": status, "components": components})
}