Golang设置跨域请求
net/http 包 #
func handler(w http.ResponseWriter, r _http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "_")
}
gin 包 #
gin/cros #
导入包
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
设置跨域中间件
r.Use(cors.Default())
自定义中间件 #
// 设置跨域请求的中间件
r.Use(func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, Authorization")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
})