32 lines
668 B
Go
32 lines
668 B
Go
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()
|
||
}
|
||
}
|