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.

27 lines
828 B

3 years ago
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  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. }