导语:记录一下golang gin支持跨域请求。
中间件cors.go
package middleware
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"time"
)
func Cors() gin.HandlerFunc {
return cors.New(cors.Config{
AllowAllOrigins: true,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"*"},
ExposeHeaders: []string{"Content-Length", "Authorization", "Content-Type"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
},
)
}
//func Cors() gin.HandlerFunc {
// return func(c *gin.Context) {
// method := c.Request.Method
// origin := c.Request.Header.Get("Origin") //请求头部
// if origin != "" {
// // 当Access-Control-Allow-Credentials为true时
// c.Header("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, X-Extra-Header, 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", "true")
//
// }
//
// if method == "OPTIONS" {
// c.AbortWithStatus(http.StatusNoContent)
// }
//
// c.Next()
// }
//}
添加到main.go
func main() {
...
router := gin.Default()
router.Use(middleware.Cors())
...
}
gin的中间件可以添加到全局, 也可以添加到单个路由上。我之前做了routers分组,没有在main.go里添加,导致部分路由还是提示跨域。
参考
https://www.cnblogs.com/you-men/p/14054348.html