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

import (
	"bytes"
5
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
G
Granty1 已提交
6 7
	"io/ioutil"
	"net/http"
8
	"strconv"
G
Granty1 已提交
9
	"time"
S
songzhibin97 已提交
10

11 12 13
	"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 已提交
14 15
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
G
Granty1 已提交
16 17
)

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

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

		c.Next()

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

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

G
Granty1 已提交
77 78 79 80 81 82 83 84
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 已提交
85
}