email.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package middleware
  2. import (
  3. "bytes"
  4. "io"
  5. "strconv"
  6. "time"
  7. "github.com/flipped-aurora/gin-vue-admin/server/plugin/email/utils"
  8. utils2 "github.com/flipped-aurora/gin-vue-admin/server/utils"
  9. "github.com/flipped-aurora/gin-vue-admin/server/global"
  10. "github.com/flipped-aurora/gin-vue-admin/server/model/system"
  11. "github.com/gin-gonic/gin"
  12. "go.uber.org/zap"
  13. )
  14. func ErrorToEmail() gin.HandlerFunc {
  15. return func(c *gin.Context) {
  16. var username string
  17. claims, _ := utils2.GetClaims(c)
  18. if claims.Username != "" {
  19. username = claims.Username
  20. } else {
  21. id, _ := strconv.Atoi(c.Request.Header.Get("x-user-id"))
  22. var u system.SysUser
  23. err := global.GVA_DB.Where("id = ?", id).First(&u).Error
  24. if err != nil {
  25. username = "Unknown"
  26. }
  27. username = u.Username
  28. }
  29. body, _ := io.ReadAll(c.Request.Body)
  30. // 再重新写回请求体body中,ioutil.ReadAll会清空c.Request.Body中的数据
  31. c.Request.Body = io.NopCloser(bytes.NewBuffer(body))
  32. record := system.SysOperationRecord{
  33. Ip: c.ClientIP(),
  34. Method: c.Request.Method,
  35. Path: c.Request.URL.Path,
  36. Agent: c.Request.UserAgent(),
  37. Body: string(body),
  38. }
  39. now := time.Now()
  40. c.Next()
  41. latency := time.Since(now)
  42. status := c.Writer.Status()
  43. record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
  44. str := "接收到的请求为" + record.Body + "\n" + "请求方式为" + record.Method + "\n" + "报错信息如下" + record.ErrorMessage + "\n" + "耗时" + latency.String() + "\n"
  45. if status != 200 {
  46. subject := username + "" + record.Ip + "调用了" + record.Path + "报错了"
  47. if err := utils.ErrorToEmail(subject, str); err != nil {
  48. global.GVA_LOG.Error("ErrorToEmail Failed, err:", zap.Error(err))
  49. }
  50. }
  51. }
  52. }