Files
ai_dianshang/server/internal/handler/health.go

94 lines
2.1 KiB
Go
Raw Normal View History

2025-11-17 13:32:54 +08:00
package handler
import (
"dianshang/pkg/response"
"net/http"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// HealthHandler 健康检查处理器
type HealthHandler struct {
db *gorm.DB
}
// NewHealthHandler 创建健康检查处理器
func NewHealthHandler(db *gorm.DB) *HealthHandler {
return &HealthHandler{
db: db,
}
}
// HealthResponse 健康检查响应结构
type HealthResponse struct {
Status string `json:"status"`
Timestamp time.Time `json:"timestamp"`
Version string `json:"version"`
Database string `json:"database"`
Uptime string `json:"uptime"`
}
var startTime = time.Now()
// Health 健康检查接口
// @Summary 健康检查
// @Description 检查服务是否正常运行,包括数据库连接状态
// @Tags 系统
// @Accept json
// @Produce json
// @Success 200 {object} response.Response{data=HealthResponse} "服务正常"
// @Failure 503 {object} response.Response "服务异常"
// @Router /health [get]
func (h *HealthHandler) Health(c *gin.Context) {
// 检查数据库连接
dbStatus := "connected"
if h.db != nil {
sqlDB, err := h.db.DB()
if err != nil || sqlDB.Ping() != nil {
dbStatus = "disconnected"
}
} else {
dbStatus = "not_configured"
}
// 计算运行时间
uptime := time.Since(startTime).String()
healthData := HealthResponse{
Status: "healthy",
Timestamp: time.Now(),
Version: "1.0.0",
Database: dbStatus,
Uptime: uptime,
}
// 如果数据库连接异常返回503状态码
if dbStatus != "connected" {
healthData.Status = "unhealthy"
c.JSON(http.StatusServiceUnavailable, response.Response{
Code: http.StatusServiceUnavailable,
Message: "服务异常",
Data: healthData,
})
return
}
response.SuccessWithMessage(c, "服务正常", healthData)
}
// Ping 简单的ping接口
// @Summary Ping检查
// @Description 简单的服务可用性检查
// @Tags 系统
// @Accept json
// @Produce json
// @Success 200 {object} response.Response "pong"
// @Router /ping [get]
func (h *HealthHandler) Ping(c *gin.Context) {
response.SuccessWithMessage(c, "pong", gin.H{
"timestamp": time.Now(),
"message": "服务运行正常",
})
}