email.go 1.6 KB

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