在Go语言的Gin框架中加入CORS(跨源资源共享)支持

14 min read

要在Go语言的Gin框架中加入CORS支持,你可以使用github.com/gin-contrib/cors包。

首先,你需要在你的项目中导入该包:

import "github.com/gin-contrib/cors"

然后,使用Use()方法添加CORS中间件到Gin引擎中:

router := gin.Default()

config := cors.DefaultConfig()
config.AllowOrigins = []string{"http://example.com"} // 允许的源
config.AllowMethods = []string{"GET", "POST", "PUT", "DELETE"} // 允许的HTTP方法
config.AllowHeaders = []string{"Origin"} // 允许的请求头

router.Use(cors.New(config))

你可以根据需要配置AllowOriginsAllowMethodsAllowHeaders等选项,以满足你的应用程序需求。在上述例子中,我们允许了一个源(http://example.com),并且只允许GET、POST、PUT和DELETE这四种HTTP方法。

现在,你的Gin应用程序将具备CORS支持,可以处理跨源请求了。