项目初始化

This commit is contained in:
2025-12-10 19:03:24 +08:00
commit 04d920aa92
14 changed files with 909 additions and 0 deletions

23
middleware/cors.go Normal file
View File

@@ -0,0 +1,23 @@
package middleware
import (
"github.com/gin-gonic/gin"
)
// CORS 跨域中间件
func CORS() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}

37
middleware/logger.go Normal file
View File

@@ -0,0 +1,37 @@
package middleware
import (
"time"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// Logger 日志中间件
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
c.Next()
latency := time.Since(start)
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
if raw != "" {
path = path + "?" + raw
}
logrus.WithFields(logrus.Fields{
"status_code": statusCode,
"latency": latency,
"client_ip": clientIP,
"method": method,
"path": path,
}).Info("HTTP Request")
}
}

21
middleware/recovery.go Normal file
View File

@@ -0,0 +1,21 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
)
// Recovery 恢复中间件
func Recovery() gin.HandlerFunc {
return gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
logrus.Errorf("Panic recovered: %v", recovered)
c.JSON(http.StatusInternalServerError, gin.H{
"code": 500,
"message": "服务器内部错误",
})
c.Abort()
})
}