gin的cors中间件
文档:https://godoc.org/github.com/gin-contrib/cors
细节:gin-contrib/cors已经对option请求做了处理
- https://github.com/gin-contrib/cors/blob/c43bb1592d752f004e1b0c7a9fe4da3934884cc7/config.go#L57
- https://github.com/gin-contrib/cors/issues/50
ps: 记录此篇,仅为了记录这个组织,这里面还有很多好用的repo
func Default() gin.HandlerFunc 默认中间件,允许all cors
func New(config Config) gin.HandlerFunc 新建一个中间件
type Config
cors所有可用选项
type Config struct {AllowAllOrigins bool// 允许哪些Origin,*代表所有// Default value is []AllowOrigins []string// AllowOriginFunc 自定义验证方案,返回ture是允许,false是拒绝,如果设置了,会忽略AllowOriginsAllowOriginFunc func(origin string) bool// 允许的MethodAllowMethods []string// 允许的HeaderAllowHeaders []string// 指示是否可以包含用户信息,如cookie等信息AllowCredentials bool// 指定哪些Header可以让客户端的js读取到ExposeHeaders []string// 表明在xxx秒内,不需要再发送预检验请求,可以缓存该结果MaxAge time.Duration// 使用通配符设置AllowOrigins 例如:http://some-domain/*, https://api.* or http://some.*.subdomain.comAllowWildcard bool// Allows usage of popular browser extensions schemasAllowBrowserExtensions bool// Allows usage of WebSocket protocolAllowWebSockets bool// Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's neededAllowFiles bool}
func (c Config) AddAllowHeaders(headers …string)
func (c Config) AddAllowMethods(methods …string)
func (c *Config) AddExposeHeaders(headers …string)
例子
package mainimport ("time""github.com/gin-contrib/cors""github.com/gin-gonic/gin")func main() {router := gin.Default()router.Use(cors.New(cors.Config{AllowOrigins: []string{"https://foo.com"},AllowMethods: []string{"PUT", "POST"},AllowHeaders: []string{"Origin"},ExposeHeaders: []string{"Content-Length","Token"},AllowCredentials: true,AllowOriginFunc: func(origin string) bool {return origin == "https://github.com"},MaxAge: 12 * time.Hour,}))router.Run()}
