36 lines
867 B
Go
36 lines
867 B
Go
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
)
|
||
|
|
|
||
|
|
func CORS(allowOrigins []string) gin.HandlerFunc {
|
||
|
|
originSet := make(map[string]bool, len(allowOrigins))
|
||
|
|
for _, o := range allowOrigins {
|
||
|
|
originSet[o] = true
|
||
|
|
}
|
||
|
|
|
||
|
|
return func(c *gin.Context) {
|
||
|
|
origin := c.GetHeader("Origin")
|
||
|
|
|
||
|
|
if originSet["*"] || originSet[origin] {
|
||
|
|
c.Header("Access-Control-Allow-Origin", origin)
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
|
||
|
|
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, X-Request-ID")
|
||
|
|
c.Header("Access-Control-Expose-Headers", "X-Request-ID")
|
||
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
||
|
|
c.Header("Access-Control-Max-Age", "86400")
|
||
|
|
|
||
|
|
if c.Request.Method == http.MethodOptions {
|
||
|
|
c.AbortWithStatus(http.StatusNoContent)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Next()
|
||
|
|
}
|
||
|
|
}
|