cors.go 865 B

123456789101112131415161718192021222324252627
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. )
  6. // Cors 处理跨域请求,支持options访问
  7. func Cors() gin.HandlerFunc {
  8. return func(c *gin.Context) {
  9. method := c.Request.Method
  10. c.Header("Access-Control-Allow-Origin", "*")
  11. //c.Header("Access-Control-Allow-Origin", c.Request.Referer())
  12. c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id,shareEmailId")
  13. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
  14. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
  15. c.Header("Access-Control-Allow-Credentials", "true")
  16. // 放行所有OPTIONS方法
  17. if method == "OPTIONS" {
  18. c.AbortWithStatus(http.StatusNoContent)
  19. }
  20. // 处理请求
  21. c.Next()
  22. }
  23. }