cors.go 576 B

123456789101112131415161718192021222324
  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(c *gin.Context) {
  9. origin := c.GetHeader("Origin")
  10. //fmt.Println("origin", origin)
  11. c.Header("Access-Control-Allow-Origin", origin)
  12. c.Header("Access-Control-Allow-Headers", "api-token,content-type,authorization ")
  13. c.Header("Access-Control-Allow-Methods", c.Request.Method)
  14. c.Header("Access-Control-Allow-Credentials", "true")
  15. if c.Request.Method == "OPTIONS" {
  16. c.AbortWithStatus(http.StatusNoContent)
  17. return
  18. }
  19. c.Next()
  20. }
  21. }