欢迎来到代码驿站!

Golang

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

Golang gin跨域解决方案示例

时间:2022-06-08 09:20:52|栏目:Golang|点击:

gin跨域解决方案

cors1.go

package middlewares
import (
	"github.com/gin-gonic/gin"
	"net/http"
)
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		origin := c.Request.Header.Get("Origin")
		if origin != ""{
			c.Header("Access-Control-Allow-Origin", origin)
			//主要设置Access-Control-Allow-Origin
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "false")
			c.Set("content-type", "application/json")
		}
		if method == "OPTIONS"{
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	}
}

cors2.go

func Cors() gin.HandlerFunc {
	return cors.New(cors.Config{
		AllowAllOrigins: false,
		AllowOrigins:    nil,
		AllowOriginFunc: func(origin string) bool {
			return true
		},
		AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
		AllowHeaders:     []string{"Authorization", "ts", "Accept", "Origin", "DNT", "X-CustomHeader", "Keep-Alive", "User-Agent", "X-Requested-With", "If-Modified-Since", "Cache-Control", "Content-Type", "Content-Range", "Range"},
		AllowCredentials: true,
		MaxAge:           10 * time.Minute,
	})
}

使用中间件

package router
import (
    "github.com/gin-gonic/gin"
    "goproejct/controllers"
    "goproejct/middlewares"//引入中间件goproject是项目名 根据自己情况
)
func InitRouter() {
    router := gin.Default()
    router.Use(Cors())//使用中间件
    v1 := router.Group("v1")
    {
        v1.POST("/login", controllers.Login)
        v1.POST("/regist", controllers.Regist)
    }
    router.Run(":8000")
}

上一篇:基于gin的golang web开发:路由示例详解

栏    目:Golang

下一篇:没有了

本文标题:Golang gin跨域解决方案示例

本文地址:http://www.codeinn.net/misctech/204189.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有