32 lines
668 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
const API_KEY_HEADER = "X-API-Key"
const APIKeyUserID = "api-key-user"
// AuthMiddleware 验证API密钥的中间件
func AuthMiddleware(apiKey string) gin.HandlerFunc {
return func(c *gin.Context) {
key := c.GetHeader(API_KEY_HEADER)
if key != apiKey {
c.JSON(http.StatusUnauthorized, gin.H{
"code": http.StatusUnauthorized,
"message": "未授权请在请求头中提供有效的API密钥",
"error": "Missing or invalid API key",
})
c.Abort()
return
}
c.Set(ContextKeyUserID, APIKeyUserID)
c.Set(ContextKeyUsername, "api-key-user")
c.Next()
}
}