12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- package middleware
- import (
- db "Medical_ERP/common/initialize"
- "Medical_ERP/models"
- "encoding/json"
- "fmt"
- "github.com/go-basic/uuid"
- "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth/beegouser"
- "strconv"
- "strings"
- "time"
- adapter "github.com/beego/beego/v2/adapter"
- "github.com/beego/beego/v2/adapter/context"
- context2 "github.com/beego/beego/v2/server/web/context"
- )
- type OperationLogDetailed struct {
- Input string `json:"input"`
- Data string `json:"data"`
- Path string `json:"path"`
- Method string `json:"method"`
- Ip string `json:"ip"`
- Username string `json:"username"`
- RequestTime string `json:"request_time"`
- }
- // LogMiddle 中间件
- var filterLog = func(ctx *context.Context) {
- if ctx.Input.URL() != "/api/home/chart" && ctx.Input.URL() != "/api/home/list" {
- var name, username string
- //非登录接口从token中获取用户name
- if len(ctx.Request.Header["Authorization"]) != 0 {
- username = beegouser.GetUserName((*context2.Context)(ctx))
- }
- //获取url类型
- urlKey := strings.Replace(ctx.Input.URL(), "/", "_", -1)
- //传递name
- detailedStruct := getRequestDetailed(ctx)
- detailedStruct.Username = username
- detailedJsonByte, err := json.Marshal(detailedStruct) //转换成JSON返回的是byte[]
- if err != nil {
- fmt.Println(err.Error())
- }
- //组合描述
- describe := name + "-send:" + detailedStruct.Path
- var uuid = uuid.New()
- logData := models.OperationLog{
- ID: uuid,
- UrlKey: urlKey,
- Describe: describe,
- DataID: "",
- Detailed: string(detailedJsonByte),
- }
- if err := db.DB.Create(&logData).Error; err != nil {
- fmt.Println("log insert fail")
- }
- }
- }
- // 获取请求详细数据
- func getRequestDetailed(ctx *context.Context) *OperationLogDetailed {
- var jsonDataMap map[string]interface{}
- _ = json.Unmarshal(ctx.Input.RequestBody, &jsonDataMap)
- // 将 JSON 对象压缩为字节切片
- compressedData, _ := json.Marshal(jsonDataMap)
- //获取起始时间
- startTime := ctx.Request.Header.Get("req_start_time")
- //string转int
- startTimeInt, _ := strconv.Atoi(startTime)
- reqTimeInt := int(time.Now().UnixNano()/1e6) - startTimeInt
- var detailedStruct OperationLogDetailed
- detailedStruct.Input = string(compressedData)
- detailedStruct.Path = ctx.Input.URL()
- detailedStruct.Method = ctx.Request.Method
- detailedStruct.Ip = ctx.Input.IP()
- detailedStruct.RequestTime = strconv.Itoa(reqTimeInt)
- return &detailedStruct
- }
- // 将开始时间放入cookie
- var getStartTime = func(ctx *context.Context) {
- startTime := time.Now().UnixNano() / 1e6
- startTimeStr := strconv.FormatInt(startTime, 10)
- ctx.Request.Header.Set("req_start_time", startTimeStr)
- }
- func LogMiddle() {
- adapter.InsertFilter("/*", adapter.FinishRouter, filterLog, false)
- adapter.InsertFilter("/*", adapter.BeforeRouter, getStartTime, false)
- }
|