tencent_ocr/.history/pkg/middleware/auth_20250115162833.go
2025-01-15 16:59:27 +08:00

37 lines
630 B
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
const (
APIKeyHeader = "X-API-Key"
)
// APIKeyAuth creates a middleware that validates the API key
func APIKeyAuth(validAPIKey string) gin.HandlerFunc {
return func(c *gin.Context) {
apiKey := c.GetHeader(APIKeyHeader)
if apiKey == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "API key is required",
})
c.Abort()
return
}
if apiKey != validAPIKey {
c.JSON(http.StatusUnauthorized, gin.H{
"success": false,
"error": "Invalid API key",
})
c.Abort()
return
}
c.Next()
}
}