cors.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package middleware
  2. import (
  3. "bytes"
  4. "io"
  5. "io/ioutil"
  6. "net/http"
  7. "runtime"
  8. "strings"
  9. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  10. "go.uber.org/zap"
  11. "github.com/gin-contrib/cors"
  12. "github.com/gin-gonic/gin"
  13. )
  14. // CORS enable CORS support
  15. func CORS(configs ...cors.Config) gin.HandlerFunc {
  16. if len(configs) != 0 {
  17. return cors.New(configs[0])
  18. }
  19. return func(c *gin.Context) {
  20. method := c.Request.Method
  21. origin := c.Request.Header.Get("Origin") //请求头部
  22. if origin != "" {
  23. //接收客户端发送的origin (重要!)
  24. c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
  25. //服务器支持的所有跨域请求的方法
  26. c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
  27. //允许跨域设置可以返回其他子段,可以自定义字段
  28. c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
  29. // 允许浏览器(客户端)可以解析的头部 (重要)
  30. c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
  31. //设置缓存时间
  32. c.Header("Access-Control-Max-Age", "172800")
  33. //允许客户端传递校验信息比如 cookie (重要)
  34. c.Header("Access-Control-Allow-Credentials", "true")
  35. }
  36. //允许类型校验
  37. if method == "OPTIONS" {
  38. c.JSON(http.StatusOK, "ok!")
  39. return
  40. }
  41. defer func() {
  42. if err := recover(); err != nil {
  43. body, _ := ioutil.ReadAll(c.Request.Body)
  44. // 获取 panic 发生的位置
  45. pc, file, line, ok := runtime.Caller(2)
  46. funcName := ""
  47. if ok {
  48. fn := runtime.FuncForPC(pc).Name()
  49. // 去除包路径,只保留函数名
  50. /*funcName = filepath.Base(fn)
  51. file = filepath.Base(file)*/
  52. parts := strings.Split(fn, "/")
  53. if len(parts) > 0 {
  54. lastPart := parts[len(parts)-1]
  55. parts = strings.Split(lastPart, ".")
  56. if len(parts) > 0 {
  57. funcName = parts[len(parts)-1]
  58. }
  59. }
  60. file = strings.TrimPrefix(file, c.Request.Context().Value(gin.ContextKey).(string)+"/") // 尝试去除项目路径前缀(可选)
  61. }
  62. zaplog.Error("cors",
  63. zap.Any("recover", err),
  64. zap.Any("url", c.Request.URL),
  65. zap.Any("method", method),
  66. zap.Any("file", file),
  67. zap.Any("line", line),
  68. zap.Any("func", funcName),
  69. zap.Any("request", string(body)),
  70. )
  71. c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
  72. c.JSON(http.StatusInternalServerError, gin.H{"err": "Internal Server Error"})
  73. }
  74. }()
  75. c.Next()
  76. }
  77. }