目录

go gin 设置允许请求跨域

目录

go gin 设置允许请求跨域,默认情况下不允许跨域请求:从另外一个域名请求 go gin 程序服务

如果业务需求需要允许跨域请求,则可以放通允许跨域的域名

完整代码:

package main

import (
  "time"

  "github.com/gin-contrib/cors"
  "github.com/gin-gonic/gin"
)

func main() {
  router := gin.Default()
  // CORS for https://foo.com and https://github.com origins, allowing:
  // - PUT and PATCH methods
  // - Origin header
  // - Credentials share
  // - Preflight requests cached for 12 hours
  router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"https://foo.com"}, // 允许的域名
    AllowMethods:     []string{"PUT", "PATCH"}, // 允许的 HTTP 方法列表
    AllowHeaders:     []string{"Origin"}, // 允许的请求头列表
    ExposeHeaders:    []string{"Content-Length"}, // 允许浏览器访问的响应头列表
    AllowCredentials: true, // 是否允许发送凭据(cookies、HTTP认证等)
    AllowOriginFunc: func(origin string) bool { // 动态允许域名;对于大量允许的域名,AllowOriginFunc 的性能可能不如静态配置
      return strings.HasSuffix(origin, ".example.com") || 
           origin == "http://localhost:3000"
    },
    MaxAge: 12 * time.Hour, // 跨域预检请求结果缓存时间
  }))
  router.Run()
}

参考资料

GitHub - gin-contrib/cors: Official CORS gin's middleware