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

import (
	"bytes"
	"gin-vue-admin/global"
G
granty1 已提交
6 7
	"gin-vue-admin/model"
	"gin-vue-admin/service"
G
Granty1 已提交
8 9 10
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
11
	"strconv"
G
Granty1 已提交
12
	"time"
G
Granty1 已提交
13 14
)

G
Granty1 已提交
15
func OperationRecord() gin.HandlerFunc {
G
Granty1 已提交
16
	return func(c *gin.Context) {
G
Granty1 已提交
17
		var body []byte
G
Granty1 已提交
18 19 20 21
		if c.Request.Method != http.MethodGet {
			var err error
			body, err = ioutil.ReadAll(c.Request.Body)
			if err != nil {
G
Granty1 已提交
22 23 24
				global.GVA_LOG.Error("read body from request error:", err)
			} else {
				c.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
G
Granty1 已提交
25
			}
G
Granty1 已提交
26 27 28 29 30 31 32 33 34 35 36
		}
		userId, err := strconv.Atoi(c.Request.Header.Get("x-user-id"))
		if err != nil {
			userId = 0
		}
		record := model.SysOperationRecord{
			Ip:     c.ClientIP(),
			Method: c.Request.Method,
			Path:   c.Request.URL.Path,
			Agent:  c.Request.UserAgent(),
			Body:   string(body),
Mr.奇淼('s avatar
Mr.奇淼( 已提交
37
			UserID: userId,
G
Granty1 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
		}
		writer := responseBodyWriter{
			ResponseWriter: c.Writer,
			body:           &bytes.Buffer{},
		}
		c.Writer = writer
		now := time.Now()

		c.Next()

		latency := time.Now().Sub(now)
		record.ErrorMessage = c.Errors.ByType(gin.ErrorTypePrivate).String()
		record.Status = c.Writer.Status()
		record.Latency = latency
		record.Resp = writer.body.String()

		if err := service.CreateSysOperationRecord(record); err != nil {
			global.GVA_LOG.Error("create operation record error:", err)
G
Granty1 已提交
56 57 58 59
		}
	}
}

G
Granty1 已提交
60 61 62 63 64 65 66 67
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 已提交
68
}