登录
首页 >  Golang >  Go教程

Golang gin跨域解决方案示例

来源:脚本之家

时间:2023-02-19 21:02:13 426浏览 收藏

IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《Golang gin跨域解决方案示例》,聊聊Gin、跨域、方案,我们一起来看看吧!

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的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>