operation.go 2.1 KB
Newer Older
G
Granty1 已提交
1 2 3 4 5 6
package middleware

import (
	"bytes"
	"io/ioutil"
	"net/http"
7
	"strconv"
G
Granty1 已提交
8
	"time"
S
songzhibin97 已提交
9

S
songzhibin97 已提交
10 11
	"github.com/flipped-aurora/gin-vue-admin/server/utils"

12 13 14
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/system"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
S
songzhibin97 已提交
15 16
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
G
Granty1 已提交
17 18
)

19 20
var operationRecordService = service.ServiceGroupApp.SystemServiceGroup.OperationRecordService

G
Granty1 已提交
21
func OperationRecord() gin.HandlerFunc {
G
Granty1 已提交
22
	return func(c *gin.Context) {
G
Granty1 已提交
23
		var body []byte
24
		var userId int
G
Granty1 已提交
25 26 27 28
		if c.Request.Method != http.MethodGet {
			var err error
			body, err = ioutil.ReadAll(c.Request.Body)
			if err != nil {
Sliver_Horn's avatar
Sliver_Horn 已提交
29
				global.GVA_LOG.Error("read body from request error:", zap.Error(err))
G
Granty1 已提交
30 31
			} else {
				c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
G
Granty1 已提交
32
			}
G
Granty1 已提交
33
		}
34
		claims, _ := utils.GetClaims(c)
35 36
		if claims.ID != 0 {
			userId = int(claims.ID)
37
		} else {
38 39 40 41 42
			id, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
			if err != nil {
				userId = 0
			}
			userId = id
G
Granty1 已提交
43
		}
Mr.奇淼('s avatar
Mr.奇淼( 已提交
44
		record := system.SysOperationRecord{
G
Granty1 已提交
45 46 47 48 49
			Ip:     c.ClientIP(),
			Method: c.Request.Method,
			Path:   c.Request.URL.Path,
			Agent:  c.Request.UserAgent(),
			Body:   string(body),
Mr.奇淼('s avatar
Mr.奇淼( 已提交
50
			UserID: userId,
G
Granty1 已提交
51
		}
52 53 54 55 56
		// 存在某些未知错误 TODO
		//values := c.Request.Header.Values("content-type")
		//if len(values) >0 && strings.Contains(values[0], "boundary") {
		//	record.Body = "file"
		//}
G
Granty1 已提交
57 58 59 60 61 62 63 64 65
		writer := responseBodyWriter{
			ResponseWriter: c.Writer,
			body:           &bytes.Buffer{},
		}
		c.Writer = writer
		now := time.Now()

		c.Next()

Mr.奇淼('s avatar
Mr.奇淼( 已提交
66
		latency := time.Since(now)
G
Granty1 已提交
67 68 69 70 71
		record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
		record.Status = c.Writer.Status()
		record.Latency = latency
		record.Resp = writer.body.String()

72
		if err := operationRecordService.CreateSysOperationRecord(record); err != nil {
Sliver_Horn's avatar
Sliver_Horn 已提交
73
			global.GVA_LOG.Error("create operation record error:", zap.Error(err))
G
Granty1 已提交
74 75 76 77
		}
	}
}

G
Granty1 已提交
78 79 80 81 82 83 84 85
type responseBodyWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (r responseBodyWriter) Write(b []byte) (int, error) {
	r.body.Write(b)
	return r.ResponseWriter.Write(b)
G
Granty1 已提交
86
}