cors.go 842 B

123456789101112131415161718192021222324
  1. package middlewares
  2. import "github.com/gin-gonic/gin"
  3. // CORSMiddleware 解决跨域问题的中间件
  4. func CORSMiddleware() gin.HandlerFunc {
  5. return func(c *gin.Context) {
  6. c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
  7. c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
  8. c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
  9. c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
  10. c.Writer.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
  11. c.Writer.Header().Set("Pragma", "no-cache")
  12. c.Writer.Header().Set("Expires", "0")
  13. c.Next()
  14. if c.Request.Method == "OPTIONS" {
  15. c.AbortWithStatus(204)
  16. return
  17. }
  18. c.Next()
  19. }
  20. }