gin的cors中间件
文档:https://godoc.org/github.com/gin-contrib/cors
细节:gin-contrib/cors已经对option请求做了处理

ps: 记录此篇,仅为了记录这个组织,这里面还有很多好用的repo

func Default() gin.HandlerFunc 默认中间件,允许all cors
func New(config Config) gin.HandlerFunc 新建一个中间件

type Config

cors所有可用选项

  1. type Config struct {
  2. AllowAllOrigins bool
  3. // 允许哪些Origin,*代表所有
  4. // Default value is []
  5. AllowOrigins []string
  6. // AllowOriginFunc 自定义验证方案,返回ture是允许,false是拒绝,如果设置了,会忽略AllowOrigins
  7. AllowOriginFunc func(origin string) bool
  8. // 允许的Method
  9. AllowMethods []string
  10. // 允许的Header
  11. AllowHeaders []string
  12. // 指示是否可以包含用户信息,如cookie等信息
  13. AllowCredentials bool
  14. // 指定哪些Header可以让客户端的js读取到
  15. ExposeHeaders []string
  16. // 表明在xxx秒内,不需要再发送预检验请求,可以缓存该结果
  17. MaxAge time.Duration
  18. // 使用通配符设置AllowOrigins 例如:http://some-domain/*, https://api.* or http://some.*.subdomain.com
  19. AllowWildcard bool
  20. // Allows usage of popular browser extensions schemas
  21. AllowBrowserExtensions bool
  22. // Allows usage of WebSocket protocol
  23. AllowWebSockets bool
  24. // Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed
  25. AllowFiles bool
  26. }

func (c Config) AddAllowHeaders(headers …string)
func (c
Config) AddAllowMethods(methods …string)
func (c *Config) AddExposeHeaders(headers …string)

例子

  1. package main
  2. import (
  3. "time"
  4. "github.com/gin-contrib/cors"
  5. "github.com/gin-gonic/gin"
  6. )
  7. func main() {
  8. router := gin.Default()
  9. router.Use(cors.New(cors.Config{
  10. AllowOrigins: []string{"https://foo.com"},
  11. AllowMethods: []string{"PUT", "POST"},
  12. AllowHeaders: []string{"Origin"},
  13. ExposeHeaders: []string{"Content-Length","Token"},
  14. AllowCredentials: true,
  15. AllowOriginFunc: func(origin string) bool {
  16. return origin == "https://github.com"
  17. },
  18. MaxAge: 12 * time.Hour,
  19. }))
  20. router.Run()
  21. }