mirror of
https://github.com/cowardmrx/gin_cors.git
synced 2025-01-18 10:53:40 +08:00
35 lines
1015 B
Go
35 lines
1015 B
Go
package gin_cors
|
|
|
|
import (
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
)
|
|
|
|
type Cors struct {
|
|
AccessControlAllowOrigins []string
|
|
AccessControlAllowHeaders string
|
|
AccessControlAllowMethods string
|
|
AccessControlExposeHeaders string
|
|
AccessControlAllowCredentials string
|
|
}
|
|
|
|
func (cors *Cors) CorsMiddleware() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
for _, v := range cors.AccessControlAllowOrigins {
|
|
if v == c.Request.Header.Get("Origin") {
|
|
c.Writer.Header().Set("Access-Control-Allow-Origin", v)
|
|
c.Writer.Header().Set("Access-Control-Allow-Headers", cors.AccessControlAllowHeaders)
|
|
c.Writer.Header().Set("Access-Control-Allow-Methods", cors.AccessControlAllowMethods)
|
|
c.Writer.Header().Set("Access-Control-Expose-Headers", cors.AccessControlExposeHeaders)
|
|
c.Writer.Header().Set("Access-Control-Allow-Credentials", cors.AccessControlAllowCredentials)
|
|
}
|
|
}
|
|
|
|
if c.Request.Method == http.MethodOptions {
|
|
c.AbortWithStatus(http.StatusNoContent)
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|