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