cors.go 865 B

12345678910111213141516171819202122232425
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. )
  6. // Cors 跨域处理
  7. func Cors() gin.HandlerFunc {
  8. return func(context *gin.Context) {
  9. method := context.Request.Method
  10. origin := context.Request.Header.Get("Origin")
  11. context.Header("Access-Control-Allow-Origin", origin)
  12. context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
  13. context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
  14. context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
  15. context.Header("Access-Control-Allow-Credentials", "true")
  16. //放行所有的option方法
  17. if method == "OPTIONS" {
  18. context.AbortWithStatus(http.StatusNoContent)
  19. }
  20. //处理请求
  21. context.Next()
  22. }
  23. }