corsMiddleware handles CORS
(config CORSConfig)
| 46 | |
| 47 | // corsMiddleware handles CORS |
| 48 | func corsMiddleware(config CORSConfig) gin.HandlerFunc { |
| 49 | return func(c *gin.Context) { |
| 50 | origin := c.Request.Header.Get("Origin") |
| 51 | |
| 52 | allowed := false |
| 53 | for _, allowedOrigin := range config.AllowOrigins { |
| 54 | if allowedOrigin == "*" || allowedOrigin == origin { |
| 55 | allowed = true |
| 56 | break |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | if allowed { |
| 61 | if len(config.AllowOrigins) == 1 && config.AllowOrigins[0] == "*" { |
| 62 | c.Header("Access-Control-Allow-Origin", "*") |
| 63 | } else { |
| 64 | c.Header("Access-Control-Allow-Origin", origin) |
| 65 | } |
| 66 | c.Header("Access-Control-Allow-Methods", strings.Join(config.AllowMethods, ", ")) |
| 67 | c.Header("Access-Control-Allow-Headers", strings.Join(config.AllowHeaders, ", ")) |
| 68 | if config.AllowCredentials { |
| 69 | c.Header("Access-Control-Allow-Credentials", "true") |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | if c.Request.Method == http.MethodOptions { |
| 74 | c.AbortWithStatus(http.StatusNoContent) |
| 75 | return |
| 76 | } |
| 77 | c.Next() |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // apiKeyAuthMiddleware validates API key |
| 82 | func apiKeyAuthMiddleware(config APIKeyConfig) gin.HandlerFunc { |
no test coverage detected