cors.go 827 B

1234567891011121314151617181920212223242526
  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. method := c.Request.Method
  10. origin := c.Request.Header.Get("Origin")
  11. c.Header("Access-Control-Allow-Origin", origin)
  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. // 放行所有OPTIONS方法
  17. if method == "OPTIONS" {
  18. c.AbortWithStatus(http.StatusNoContent)
  19. }
  20. // 处理请求
  21. c.Next()
  22. }
  23. }