package utils import ( "fmt" "github.com/fatih/color" "github.com/gin-gonic/gin" "net/http" "time" ) func CORSMiddleware() 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, Authorization, X-Requested-With, X-CSRF-Token, Accept, Origin") // 允许的HTTP方法 c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH") // 处理预检请求 if c.Request.Method == "OPTIONS" { c.AbortWithStatus(http.StatusOK) return } // 继续处理非预检请求 c.Next() } } func CustomLogger() gin.HandlerFunc { return func(c *gin.Context) { // 获取开始时间 start := time.Now() // 处理请求 c.Next() // 获取状态码、耗时、客户端IP、方法、路径 statusCode := c.Writer.Status() latency := time.Since(start) clientIP := c.ClientIP() method := c.Request.Method path := c.Request.URL.Path // 颜色设置 statusColor := color.New(color.FgGreen).SprintFunc() if statusCode >= 400 && statusCode < 500 { statusColor = color.New(color.FgYellow).SprintFunc() } else if statusCode >= 500 { statusColor = color.New(color.FgRed).SprintFunc() } methodColor := color.New(color.FgCyan).SprintFunc() // 打印彩色日志 fmt.Printf("[GIN] %v | %s | %s | %13v | %s | %s\n", time.Now().Format("2006/01/02 - 15:04:05"), statusColor(statusCode), clientIP, latency, methodColor(method), path, ) } } func NotFoundHandler(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{"code": 404, "msg": "无效路径!"}) } func NotMethodHandler(c *gin.Context) { c.JSON(http.StatusMethodNotAllowed, gin.H{"code": 404, "msg": "请求方法错误!"}) }