官方 CORS gin 中间件
CORS (Cross-Origin Resource Sharing) 中间件用于 Gin。
go get github.com/gin-contrib/cors在 Go 代码中导入:
import "github.com/gin-contrib/cors"允许所有来源(默认):
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Use(cors.Default()) // All origins allowed by default
router.Run()
}⚠️ 警告: 允许所有来源会禁用客户端的 Cookie。对于具有凭证的请求,请不要 允许所有来源。
配置允许的源、方法、头等内容:
import (
"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", "PATCH"},
AllowHeaders: []string{"Origin"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
AllowOriginFunc: func(origin string) bool {
return origin == "https://github.com"
},
MaxAge: 12 * time.Hour,
}))
router.Run()
}暂无开放 Issues,或尚未同步最近议题。