cros.go 977 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. )
  6. // 处理跨域请求,支持options访问
  7. func Cors() gin.HandlerFunc {
  8. return func(c *gin.Context) {
  9. origin := c.GetHeader("Origin")
  10. if len(origin) == 0 {
  11. c.Next()
  12. return
  13. }
  14. // 同源直接过
  15. host := c.GetHeader("Host")
  16. if origin == "http://"+host || origin == "https://"+host {
  17. c.Next()
  18. return
  19. }
  20. c.Header("Access-Control-Allow-Origin", "*")
  21. c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
  22. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
  23. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
  24. c.Header("Access-Control-Allow-Credentials", "true")
  25. // OPTIONS 过
  26. method := c.Request.Method
  27. if method == "OPTIONS" {
  28. c.AbortWithStatus(http.StatusNoContent)
  29. c.Abort()
  30. }
  31. c.Next()
  32. }
  33. }