package middleware import ( "net/http" "github.com/gin-gonic/gin" ) const ( API_KEY_HEADER = "X-API-Key" API_KEY_VALUE = "xn001624." ) // AuthMiddleware 验证API密钥的中间件 func AuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // 从请求头中获取API密钥 apiKey := c.GetHeader(API_KEY_HEADER) // 验证密钥是否正确 if apiKey != API_KEY_VALUE { c.JSON(http.StatusUnauthorized, gin.H{ "code": http.StatusUnauthorized, "message": "未授权:请在请求头中提供有效的API密钥", "error": "Missing or invalid API key", }) c.Abort() return } // 密钥验证通过,继续处理请求 c.Next() } }