feat: Initial commit

This commit is contained in:
engigu
2025-12-20 09:30:16 +08:00
commit 362237241e
189 changed files with 12035 additions and 0 deletions
+43
View File
@@ -0,0 +1,43 @@
package middleware
import (
"baihu/internal/constant"
"baihu/internal/utils"
"github.com/gin-gonic/gin"
)
// AuthRequired 认证中间件
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
token, err := c.Cookie(constant.CookieName)
if err != nil || token == "" {
utils.Unauthorized(c, "请先登录")
c.Abort()
return
}
// 验证 token
userID, username, err := utils.ParseToken(token)
if err != nil {
utils.Unauthorized(c, "登录已过期,请重新登录")
c.Abort()
return
}
// 将用户信息存入上下文
c.Set("userID", userID)
c.Set("username", username)
c.Next()
}
}
// SetAuthCookie 设置认证 Cookie
func SetAuthCookie(c *gin.Context, token string) {
c.SetCookie(constant.CookieName, token, constant.CookieMaxAge, "/", "", false, true)
}
// ClearAuthCookie 清除认证 Cookie
func ClearAuthCookie(c *gin.Context) {
c.SetCookie(constant.CookieName, "", -1, "/", "", false, true)
}
+54
View File
@@ -0,0 +1,54 @@
package middleware
import (
"fmt"
"time"
"baihu/internal/logger"
"github.com/gin-gonic/gin"
)
// GinLogger 返回使用 logrus 的 Gin 日志中间件
func GinLogger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
query := c.Request.URL.RawQuery
c.Next()
latency := time.Since(start)
status := c.Writer.Status()
clientIP := c.ClientIP()
method := c.Request.Method
if query != "" {
path = path + "?" + query
}
msg := fmt.Sprintf("%3d | %13v | %15s | %-7s %s",
status, latency, clientIP, method, path)
if status >= 500 {
logger.Error(msg)
} else if status >= 400 {
logger.Warn(msg)
} else {
logger.Info(msg)
}
}
}
// GinRecovery 返回使用 logrus 的 Gin 恢复中间件
func GinRecovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
logger.Errorf("Panic recovered: %v | path: %s", err, c.Request.URL.Path)
c.AbortWithStatus(500)
}
}()
c.Next()
}
}