cors.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package middleware
  2. import (
  3. "net/http"
  4. "github.com/gin-contrib/cors"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // CORS enable CORS support
  8. func CORS(configs ...cors.Config) gin.HandlerFunc {
  9. if len(configs) != 0 {
  10. return cors.New(configs[0])
  11. }
  12. return func(c *gin.Context) {
  13. method := c.Request.Method
  14. origin := c.Request.Header.Get("Origin") //请求头部
  15. if origin != "" {
  16. //接收客户端发送的origin (重要!)
  17. c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
  18. //服务器支持的所有跨域请求的方法
  19. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  20. //允许跨域设置可以返回其他子段,可以自定义字段
  21. c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length")
  22. // 允许浏览器(客户端)可以解析的头部 (重要)
  23. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
  24. //设置缓存时间
  25. c.Header("Access-Control-Max-Age", "172800")
  26. //允许客户端传递校验信息比如 cookie (重要)
  27. c.Header("Access-Control-Allow-Credentials", "true")
  28. }
  29. //允许类型校验
  30. if method == "OPTIONS" {
  31. c.JSON(http.StatusOK, "ok!")
  32. return
  33. }
  34. c.Next()
  35. }
  36. }