APIKeyMiddleware validates API key for protected endpoints. Swagger documentation endpoints (/swagger/*) are exempt from authentication to allow users to browse and test the API documentation freely.
(apiKey string)
| 13 | // Swagger documentation endpoints (/swagger/*) are exempt from authentication |
| 14 | // to allow users to browse and test the API documentation freely. |
| 15 | func APIKeyMiddleware(apiKey string) gin.HandlerFunc { |
| 16 | return func(c *gin.Context) { |
| 17 | // Skip authentication for Swagger documentation endpoints |
| 18 | // This allows public access to API docs even when authentication is enabled |
| 19 | if strings.HasPrefix(c.Request.URL.Path, "/swagger/") { |
| 20 | c.Next() |
| 21 | return |
| 22 | } |
| 23 | |
| 24 | headerApiKey := c.GetHeader(APIKeyHeader) |
| 25 | |
| 26 | if headerApiKey == "" { |
| 27 | c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Missing API Key"}) |
| 28 | return |
| 29 | } |
| 30 | |
| 31 | if headerApiKey != apiKey { |
| 32 | c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Wrong API Key"}) |
| 33 | return |
| 34 | } |
| 35 | |
| 36 | c.Next() |
| 37 | } |
| 38 | } |