30 lines
730 B
Go
30 lines
730 B
Go
|
package cors
|
|||
|
|
|||
|
import (
|
|||
|
"net/http"
|
|||
|
|
|||
|
"github.com/gin-gonic/gin"
|
|||
|
)
|
|||
|
|
|||
|
func CorsMiddleware() gin.HandlerFunc {
|
|||
|
return func(c *gin.Context) {
|
|||
|
// 设置允许的方法
|
|||
|
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
|
|||
|
|
|||
|
// 设置允许的头
|
|||
|
c.Writer.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
|
|||
|
|
|||
|
// 设置允许的来源,* 表示允许所有来源
|
|||
|
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
|||
|
|
|||
|
// 如果是OPTIONS请求,直接返回,不继续处理
|
|||
|
if c.Request.Method == "OPTIONS" {
|
|||
|
c.AbortWithStatus(http.StatusOK)
|
|||
|
return
|
|||
|
}
|
|||
|
|
|||
|
// 继续处理请求
|
|||
|
c.Next()
|
|||
|
}
|
|||
|
}
|