0%

golang gin-cors

golang gin框架 跨域访问配置代码

中间件代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package middleware

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

// Cors 跨域配置
func Cors() gin.HandlerFunc {
config := cors.DefaultConfig()
config.AllowMethods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
config.AllowHeaders = []string{"Origin", "Content-Length", "Content-Type", "Cookie"}
if gin.Mode() == gin.ReleaseMode {
// 生产环境需要配置跨域域名,否则403
config.AllowOrigins = []string{"http://www.example.com"}
} else {
config.AllowOrigins = []string{"*"}
}
config.AllowCredentials = true
return cors.New(config)
}

路由配置

1
2
3
router := gin.Default()
// cors 跨域设置
router.Use(middleware.Cors())