You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

25 lines
752 B

  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. c.Header("Access-Control-Allow-Origin", "*")
  11. c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
  12. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
  13. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
  14. c.Header("Access-Control-Allow-Credentials", "true")
  15. // 放行所有OPTIONS方法
  16. if method == "OPTIONS" {
  17. c.AbortWithStatus(http.StatusNoContent)
  18. }
  19. // 处理请求
  20. c.Next()
  21. }
  22. }