email.go 1.7 KB
Newer Older
Sliver_Horn's avatar
Sliver_Horn 已提交
1 2 3
package middleware

import (
Mr.奇淼('s avatar
Mr.奇淼( 已提交
4
	"github.com/flipped-aurora/gin-vue-admin/plugin/email/utils"
Sliver_Horn's avatar
Sliver_Horn 已提交
5 6 7
	"io/ioutil"
	"strconv"
	"time"
S
songzhibin97 已提交
8 9 10 11 12 13 14

	"github.com/flipped-aurora/gin-vue-admin/global"
	"github.com/flipped-aurora/gin-vue-admin/model/system"
	"github.com/flipped-aurora/gin-vue-admin/model/system/request"
	"github.com/flipped-aurora/gin-vue-admin/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
Sliver_Horn's avatar
Sliver_Horn 已提交
15 16
)

17 18
var userService = service.ServiceGroupApp.SystemServiceGroup.UserService

Sliver_Horn's avatar
Sliver_Horn 已提交
19 20 21 22 23 24
func ErrorToEmail() gin.HandlerFunc {
	return func(c *gin.Context) {
		var username string
		if claims, ok := c.Get("claims"); ok {
			waitUse := claims.(*request.CustomClaims)
			username = waitUse.Username
25
		} else {
Sliver_Horn's avatar
Sliver_Horn 已提交
26
			id, _ := strconv.Atoi(c.Request.Header.Get("x-user-id"))
27
			err, user := userService.FindUserById(id)
28
			if err != nil {
Sliver_Horn's avatar
Sliver_Horn 已提交
29 30 31 32 33
				username = "Unknown"
			}
			username = user.Username
		}
		body, _ := ioutil.ReadAll(c.Request.Body)
Mr.奇淼('s avatar
Mr.奇淼( 已提交
34
		record := system.SysOperationRecord{
Sliver_Horn's avatar
Sliver_Horn 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47
			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.Now().Sub(now)
		status := c.Writer.Status()
		record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
48
		str := "接收到的请求为" + record.Body + "\n" + "请求方式为" + record.Method + "\n" + "报错信息如下" + record.ErrorMessage + "\n" + "耗时" + latency.String() + "\n"
49 50 51 52
		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.Any("err", err))
Sliver_Horn's avatar
Sliver_Horn 已提交
53 54 55 56
			}
		}
	}
}