From 03933888a0fa998f1874d939bcaf4b9164400f1d Mon Sep 17 00:00:00 2001 From: lin <550210817@qq.com> Date: Fri, 17 May 2024 16:52:20 +0800 Subject: [PATCH] =?UTF-8?q?feat:=E6=B7=BB=E5=8A=A0=E8=B7=A8=E5=9F=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/middleware/cors.go | 36 ++++++++++++++++++++++++++++++++++++ routes/init_router.go | 1 + 2 files changed, 37 insertions(+) create mode 100644 pkg/middleware/cors.go diff --git a/pkg/middleware/cors.go b/pkg/middleware/cors.go new file mode 100644 index 0000000..911dba8 --- /dev/null +++ b/pkg/middleware/cors.go @@ -0,0 +1,36 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "net/http" +) + +// Cors 跨域中间件 +func Cors() gin.HandlerFunc { + return func(c *gin.Context) { + method := c.Request.Method + origin := c.Request.Header.Get("Origin") + if origin != "" { + //接收客户端发送的origin (重要!) + c.Writer.Header().Set("Access-Control-Allow-Origin", origin) + //服务器支持的所有跨域请求的方法 + c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") + //允许跨域设置可以返回其他子段,可以自定义字段 + c.Header("Access-Control-Allow-Headers", "Authorization, content-type, Content-Length, X-CSRF-Token, Token,session,Access-Control-Allow-Headers,account") + // 允许浏览器(客户端)可以解析的头部 (重要) + c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers") + //设置缓存时间 + c.Header("Access-Control-Max-Age", "172800") + //允许客户端传递校验信息比如 cookie (重要) + c.Header("Access-Control-Allow-Credentials", "true") + c.Set("Content-Type", "application/json") + } + + //允许类型校验 + if method == "OPTIONS" { + c.JSON(http.StatusOK, "ok!") + } + + c.Next() + } +} diff --git a/routes/init_router.go b/routes/init_router.go index d9d7af5..fa6aaea 100644 --- a/routes/init_router.go +++ b/routes/init_router.go @@ -31,6 +31,7 @@ func initWebSocket() { func initGin() { router := gin.Default() router.Use(middleware.LoggerToFile()) + router.Use(middleware.Cors()) //添加swagger访问路由 router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // 不需要身份验证的路由