feat: 完善后端脚手架基础能力
This commit is contained in:
+60
-13
@@ -1,29 +1,76 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"skeleton/database"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type systemResponse struct {
|
||||
Code int `json:"code" example:"200"`
|
||||
Message string `json:"message"`
|
||||
Data interface{} `json:"data"`
|
||||
}
|
||||
|
||||
type healthData struct {
|
||||
Status string `json:"status"`
|
||||
Database string `json:"database"`
|
||||
Redis string `json:"redis"`
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterPublic(registerHealthRoutes)
|
||||
}
|
||||
|
||||
func registerHealthRoutes(r *gin.RouterGroup) {
|
||||
r.GET("/ping", func(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"code": 200,
|
||||
"message": "pong",
|
||||
"data": nil,
|
||||
})
|
||||
})
|
||||
r.GET("/ping", ping)
|
||||
r.GET("/health", health)
|
||||
}
|
||||
|
||||
r.GET("/health", func(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"code": 200,
|
||||
"message": "ok",
|
||||
"data": nil,
|
||||
})
|
||||
// ping godoc
|
||||
// @Summary 服务连通性检查
|
||||
// @Tags system
|
||||
// @Produce json
|
||||
// @Success 200 {object} systemResponse
|
||||
// @Router /ping [get]
|
||||
func ping(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, gin.H{
|
||||
"code": 200,
|
||||
"message": "pong",
|
||||
"data": nil,
|
||||
})
|
||||
}
|
||||
|
||||
// health godoc
|
||||
// @Summary 服务健康检查
|
||||
// @Tags system
|
||||
// @Produce json
|
||||
// @Success 200 {object} systemResponse{data=healthData}
|
||||
// @Failure 503 {object} systemResponse{data=healthData}
|
||||
// @Router /health [get]
|
||||
func health(ctx *gin.Context) {
|
||||
checkCtx, cancel := context.WithTimeout(ctx.Request.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
data := healthData{Status: "ok", Database: "up", Redis: "disabled"}
|
||||
status := http.StatusOK
|
||||
if err := database.Ping(checkCtx); err != nil {
|
||||
data.Status = "degraded"
|
||||
data.Database = "down"
|
||||
status = http.StatusServiceUnavailable
|
||||
}
|
||||
if client := database.GetRedisClient(); client != nil {
|
||||
data.Redis = "up"
|
||||
if err := client.Ping(checkCtx); err != nil {
|
||||
data.Status = "degraded"
|
||||
data.Redis = "down"
|
||||
status = http.StatusServiceUnavailable
|
||||
}
|
||||
}
|
||||
|
||||
ctx.JSON(status, gin.H{"code": status, "message": data.Status, "data": data})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user