wx-server/internal/middleware/cors/cors.go

30 lines
730 B
Go
Raw Normal View History

2024-06-04 21:22:50 +08:00
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()
}
}