当前位置:主页 > 脚本语言 > Golang >

解决golang gin框架跨域及注解的问题

时间:2021-08-20 10:05:20 | 栏目:Golang | 点击:

在golang的路上缓慢前进 Gin框架 跨域问题的解说与方法

代码如下:

package main 
import (
	"github.com/gin-gonic/gin"
	"awesomeProject/app/app_routers"
	"strings"
	"fmt"
	"net/http"
) 
 
/* 路由初始化*/
var (
	engine = gin.Default()
) 
func main() {
 
	// 允许使用跨域请求	 全局中间件
	engine.Use(Cors())
	//router.Use(cors.Default())
	// 传参 设定路由组 允许路由组使用路由
	app_routers.Router(engine)
	// 启动路由 设定端口
	Cors()
	engine.Run(":11000")	//运行启动端口 
} 
//
// 跨域
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method		//请求方法
		origin := c.Request.Header.Get("Origin")		//请求头部
		var headerKeys []string								// 声明请求头keys
		for k, _ := range c.Request.Header {
			headerKeys = append(headerKeys, k)
		}
		headerStr := strings.Join(headerKeys, ", ")
		if headerStr != "" {
			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
		} else {
			headerStr = "access-control-allow-origin, access-control-allow-headers"
		}
		if origin != "" {
			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Origin", "*")		// 这是允许访问所有域
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")		//服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
			// header的类型
			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
			//				允许跨域设置																										可以返回其他子段
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")		// 跨域关键设置 让浏览器可以解析
			c.Header("Access-Control-Max-Age", "172800")		// 缓存请求信息 单位为秒
			c.Header("Access-Control-Allow-Credentials", "false")		//	跨域请求是否需要带cookie信息 默认设置为true
			c.Set("content-type", "application/json")		// 设置返回格式是json
		}
 
		//放行所有OPTIONS方法
		if method == "OPTIONS" {
			c.JSON(http.StatusOK, "Options Request!")
		}
		// 处理请求
		c.Next()		//	处理请求
	}
}

补充:gin框架中间件解决跨域问题

代码如下:

func Cors(c *gin.Context) {
 c.Header("Access-Control-Allow-Origin", "*")
 c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
 c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
 c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
 c.Header("Access-Control-Allow-Credentials", "true")
 //这里是解决vue那个坑
 method := c.Request.Method
 // 放行所有OPTIONS方法,因为有的模板是要请求两次的
 if method == "OPTIONS" {
  c.AbortWithStatus(http.StatusNoContent)
 }
 // 处理请求
 c.Next()
}

您可能感兴趣的文章:

相关文章