重命名 api 文件夹为 backend
This commit is contained in:
64
backend/api/handlers/health.go
Normal file
64
backend/api/handlers/health.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// HealthResponse 健康检查响应
|
||||
type HealthResponse struct {
|
||||
Status string `json:"status"`
|
||||
Time string `json:"time"`
|
||||
Services map[string]string `json:"services"`
|
||||
}
|
||||
|
||||
// HealthCheck 健康检查
|
||||
func (h *Handler) HealthCheck(c *gin.Context) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
response := HealthResponse{
|
||||
Status: "ok",
|
||||
Time: time.Now().Format(time.RFC3339),
|
||||
Services: make(map[string]string),
|
||||
}
|
||||
|
||||
// 检查数据库连接
|
||||
sqlDB, err := h.cfg.DB.DB()
|
||||
if err != nil {
|
||||
response.Services["database"] = "error: " + err.Error()
|
||||
response.Status = "degraded"
|
||||
} else {
|
||||
if err := sqlDB.PingContext(ctx); err != nil {
|
||||
response.Services["database"] = "error: " + err.Error()
|
||||
response.Status = "degraded"
|
||||
} else {
|
||||
response.Services["database"] = "ok"
|
||||
}
|
||||
}
|
||||
|
||||
// 检查 Redis 连接
|
||||
if err := h.cfg.Redis.Ping(ctx).Err(); err != nil {
|
||||
response.Services["redis"] = "error: " + err.Error()
|
||||
response.Status = "degraded"
|
||||
} else {
|
||||
response.Services["redis"] = "ok"
|
||||
}
|
||||
|
||||
if response.Status == "ok" {
|
||||
c.JSON(http.StatusOK, response)
|
||||
} else {
|
||||
c.JSON(http.StatusServiceUnavailable, response)
|
||||
}
|
||||
}
|
||||
|
||||
// Ping 简单的 ping 测试
|
||||
func (h *Handler) Ping(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"message": "pong",
|
||||
"time": time.Now().Format(time.RFC3339),
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user