cors.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. // Cors 处理跨域请求,支持options访问
  6. //func Cors2() gin.HandlerFunc {
  7. // return func(c *gin.Context) {
  8. // method := c.Request.Method
  9. //
  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")
  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. //
  17. // // 放行所有OPTIONS方法
  18. // if method == "OPTIONS" {
  19. // c.AbortWithStatus(http.StatusNoContent)
  20. // }
  21. // // 处理请求
  22. // c.Next()
  23. // }
  24. //}
  25. func Cors() gin.HandlerFunc {
  26. return func(c *gin.Context) {
  27. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  28. c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
  29. c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
  30. c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
  31. //c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
  32. if c.Request.Method == "OPTIONS" {
  33. c.AbortWithStatus(200)
  34. return
  35. }
  36. c.Next()
  37. }
  38. }