cors.go 828 B

123456789101112131415161718192021222324
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "net/http"
  5. )
  6. func Cors() gin.HandlerFunc {
  7. return func(c *gin.Context) {
  8. method := c.Request.Method
  9. origin := c.Request.Header.Get("Origin")
  10. if origin != "" {
  11. c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
  12. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
  13. c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  14. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
  15. c.Header("Access-Control-Allow-Credentials", "true")
  16. }
  17. if method == "OPTIONS" {
  18. c.AbortWithStatus(http.StatusNoContent)
  19. }
  20. c.Next()
  21. }
  22. }