email.go 1.7 KB

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