Some checks failed
CI / Lint + Build (push) Has been cancelled
审计修复: - CSP: unsafe-inline移除, nonce替代; unsafe-eval保留供Vditor使用 - HSTS: 始终启用(不再依赖release模式) - Controller Exp: common.GetGinExp包装, 不再直接读context - UID解析: common.ParseUIDParam统一, follow/admin controller改用 重构: - router/api.go(198行)拆为7个域文件: auth/settings/posts/comments/reactions/social/studio - 管理后台站点设置: 单页拆为4个子页(brand/security/registration/content)+子菜单 - 前台用户设置页: 1201行拆为6个独立模板+6个独立JS文件 新增: - DB健康检测中间件(middleware/db_health.go): 5s ping+降级页面 - 时区配置: config.yaml server.timezone→time.Local初始化 - .gitea/workflows/ci.yml: strict模式CI流水线
85 lines
2.4 KiB
Go
85 lines
2.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// dbHealthy 全局数据库健康状态(原子读写,默认为健康)
|
|
var dbHealthy atomic.Bool
|
|
|
|
func init() {
|
|
dbHealthy.Store(true)
|
|
}
|
|
|
|
// StartDBHealthCheck 启动定时 DB 健康检测(在 main goroutine 中调用)
|
|
// 每 5 秒 ping 一次,失败则标记不健康,恢复则重新标记健康
|
|
func StartDBHealthCheck(db *gorm.DB) {
|
|
go func() {
|
|
ticker := time.NewTicker(5 * time.Second)
|
|
defer ticker.Stop()
|
|
for range ticker.C {
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
dbHealthy.Store(false)
|
|
log.Printf("[DBHealth] 获取底层连接失败: %v", err)
|
|
continue
|
|
}
|
|
if err := sqlDB.Ping(); err != nil {
|
|
if dbHealthy.Swap(false) {
|
|
log.Printf("[DBHealth] 数据库不可达,整站进入降级模式: %v", err)
|
|
}
|
|
} else {
|
|
if !dbHealthy.Swap(true) {
|
|
log.Println("[DBHealth] 数据库已恢复,退出降级模式")
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
// DBHealthGuard 数据库健康检查中间件
|
|
// 检测到 DB 不可达时,返回固定维护页面,避免暴露内部堆栈信息
|
|
func DBHealthGuard() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
if dbHealthy.Load() {
|
|
c.Next()
|
|
return
|
|
}
|
|
|
|
path := c.Request.URL.Path
|
|
// 静态资源和 API 直接返回错误,不渲染页面
|
|
if isStaticPath(path) {
|
|
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{
|
|
"success": false,
|
|
"message": "服务暂时不可用,请稍后重试",
|
|
})
|
|
return
|
|
}
|
|
// 页面请求返回友好 HTML
|
|
c.AbortWithStatus(http.StatusServiceUnavailable)
|
|
c.Header("Content-Type", "text/html; charset=utf-8")
|
|
_, _ = c.Writer.WriteString(`<!DOCTYPE html>
|
|
<html lang="zh-CN">
|
|
<head><meta charset="UTF-8"><title>服务暂时不可用</title>
|
|
<style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#f5f5f5}
|
|
div{text-align:center;padding:2rem} h1{color:#333} p{color:#666}</style></head>
|
|
<body><div><h1>服务暂时不可用</h1><p>数据库连接异常,请稍后刷新页面重试</p></div></body></html>`)
|
|
}
|
|
}
|
|
|
|
// isStaticPath 判断是否为静态资源或 API 路径
|
|
func isStaticPath(path string) bool {
|
|
for _, prefix := range []string{"/static/", "/shared/", "/admin/static/", "/api/"} {
|
|
if len(path) >= len(prefix) && path[:len(prefix)] == prefix {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|