1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| package middleware
import ( "github.com/gin-gonic/gin" "net/http" )
func CorsMiddleware() gin.HandlerFunc{ return func(ctx *gin.Context) { ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*") ctx.Writer.Header().Set("Access-Control-Max-Age", "86400") ctx.Writer.Header().Set("Access-Control-Allow-Methods", "*") ctx.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, content-Type, Accept, Authorization") ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
//放行所有OPTIONS方法 if ctx.Request.Method == http.MethodOptions{ ctx.AbortWithStatus(http.StatusNoContent) } // 处理请求 ctx.Next() } } r:= gin.Default() r.Use(middleware.CorsMiddleware())//跨域处理接收数据
|