5

【代码】Gin设置允许跨域访问

 1 year ago
source link: https://loli.fj.cn/2023/03/27/Gin%E8%AE%BE%E7%BD%AE%E5%85%81%E8%AE%B8%E8%B7%A8%E5%9F%9F%E8%AE%BF%E9%97%AE/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【代码】Gin设置允许跨域访问

2023-03-27

Gin设置允许跨域访问的中间件

  • 在挂载路由之前设置允许跨域访问
func main() {
app := gin.Default()

// 设置允许跨域访问
app.Use(Cors())
// 挂载路由
...

app.Run()
}

// 允许跨域访问中间件
func Cors() gin.HandlerFunc {
return func(context *gin.Context) {
method := context.Request.Method
origin := context.Request.Header.Get("Origin")
var headerKeysArr []string
for key, _ := range context.Request.Header {
headerKeysArr = append(headerKeysArr, key)
}
headerKeysStr := strings.Join(headerKeysArr, ",")
if headerKeysStr != "" {
headerKeysStr = fmt.Sprint("access-control-allow-origin, access-control-allow-headers, %s", headerKeysStr)
} else {
headerKeysStr = "access-control-allow-origin, access-control-allow-headers"
}
if origin != "" {
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE, UPDATE")
context.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")
context.Header("Access-Control-Allow-Credentials", "false")
context.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")
context.Header("Access-Control-Max-Age", "172800")
context.Set("content-type", "application/json")

if method == "OPTIONS" {
context.JSON(200, "Options Request!")
}

context.Next()
}
}
}

哔哩哔哩——80技术
CSDN——私念


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK