cors.go 577 B

1234567891011121314151617181920212223242526272829
  1. package middware
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func Cors() gin.HandlerFunc {
  7. return func(c *gin.Context) {
  8. method := c.Request.Method
  9. c.Header("Access-Control-Allow-Origin", "*")
  10. c.Header("Access-Control-Allow-Headers", "*")
  11. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
  12. c.Header(
  13. "Access-Control-Expose-Headers",
  14. "*",
  15. )
  16. c.Header("Access-Control-Allow-Credentials", "true")
  17. // 放行所有OPTIONS方法
  18. if method == "OPTIONS" {
  19. c.AbortWithStatus(http.StatusNoContent)
  20. }
  21. // 处理请求
  22. c.Next()
  23. }
  24. }