使用gin框架开发的web程序如何配置接受跨域请求?

提问者:帅平 问题分类:go语言
使用gin框架开发的web程序如何配置接受跨域请求?
1 个回答
箫声断ツ何处莫凭栏
箫声断ツ何处莫凭栏
可以使用gin中间件的cors框架,首先安装cors
go get -u github.com/gin-contrib/cors

接着配置中间件,例如:
router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"https://www.baidu.com"},
    AllowMethods:     []string{"PUT", "PATCH"},
    AllowHeaders:     []string{"Origin"},
    ExposeHeaders:    []string{"Content-Length"},
    AllowCredentials: true,
    AllowOriginFunc: func(origin string) bool {
      return origin == "https://github.com"
    },
    MaxAge: 12 * time.Hour,
  }))
就可以了
发布于:5个月前 (11-27) IP属地:四川省
我来回答