cors.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package middleware
  2. import (
  3. "io/ioutil"
  4. "kpt-tmr-group/pkg/logger/zaplog"
  5. "net/http"
  6. "go.uber.org/zap"
  7. "github.com/gin-contrib/cors"
  8. "github.com/gin-gonic/gin"
  9. )
  10. // CORS enable CORS support
  11. func CORS(configs ...cors.Config) gin.HandlerFunc {
  12. if len(configs) != 0 {
  13. return cors.New(configs[0])
  14. }
  15. return func(c *gin.Context) {
  16. method := c.Request.Method
  17. origin := c.Request.Header.Get("Origin") //请求头部
  18. if origin != "" {
  19. //接收客户端发送的origin (重要!)
  20. c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
  21. //服务器支持的所有跨域请求的方法
  22. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  23. //允许跨域设置可以返回其他子段,可以自定义字段
  24. c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
  25. // 允许浏览器(客户端)可以解析的头部 (重要)
  26. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
  27. //设置缓存时间
  28. c.Header("Access-Control-Max-Age", "172800")
  29. //允许客户端传递校验信息比如 cookie (重要)
  30. c.Header("Access-Control-Allow-Credentials", "true")
  31. }
  32. //允许类型校验
  33. if method == "OPTIONS" {
  34. c.JSON(http.StatusOK, "ok!")
  35. return
  36. }
  37. defer func() {
  38. if err := recover(); err != nil {
  39. body, _ := ioutil.ReadAll(c.Request.Body)
  40. zaplog.Error("cors",
  41. zap.Any("recover", err),
  42. zap.Any("url", c.Request.URL),
  43. zap.Any("method", method),
  44. zap.Any("request", string(body)),
  45. )
  46. }
  47. }()
  48. c.Next()
  49. }
  50. }