82 lines
1.7 KiB
Go
82 lines
1.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"bytes"
|
|
"github.com/gin-gonic/gin"
|
|
"go_api_tmpl/core"
|
|
"go_api_tmpl/model"
|
|
"go_api_tmpl/repository"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// CheckDeviceId 检查是否存在设备指纹
|
|
func CheckDeviceId() gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
p := ctx.Request.URL.Path
|
|
if p == "/" {
|
|
ctx.Next()
|
|
return
|
|
}
|
|
// 取出设备指纹
|
|
deviceId := ctx.Request.Header.Get("di")
|
|
if deviceId == "" {
|
|
// 设备指纹不存在
|
|
core.R(ctx).FailWithMessageAndCode("请求不合法", http.StatusBadRequest)
|
|
ctx.Abort()
|
|
return
|
|
}
|
|
ctx.Next()
|
|
}
|
|
}
|
|
|
|
// SaveRequestLog 保存所有请求接口日志
|
|
func SaveRequestLog() gin.HandlerFunc {
|
|
return func(ctx *gin.Context) {
|
|
// 开始时间
|
|
start := time.Now()
|
|
// 取出接口
|
|
path := ctx.Request.URL.Path
|
|
// 取出参数
|
|
query := ctx.Request.URL.RawQuery
|
|
// body参数
|
|
body, err := ctx.GetRawData()
|
|
bodyStr := ""
|
|
if err == nil {
|
|
bodyStr = string(body)
|
|
ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(body))
|
|
}
|
|
// form参数
|
|
form := ctx.Request.Form.Encode()
|
|
// 取出请求方式
|
|
method := ctx.Request.Method
|
|
// 取出设备指纹
|
|
deviceId := ctx.Request.Header.Get("di")
|
|
// 取出IP
|
|
ip := ctx.ClientIP()
|
|
// UA
|
|
ua := ctx.Request.UserAgent()
|
|
ctx.Next()
|
|
// 计算耗时
|
|
cost := time.Since(start).Milliseconds()
|
|
// 组装实体
|
|
rlog := model.RequestLog{
|
|
Method: method,
|
|
Path: path,
|
|
Param: query,
|
|
Body: bodyStr,
|
|
Form: form,
|
|
Cost: cost,
|
|
StatusCode: ctx.Writer.Status(),
|
|
DeviceId: deviceId,
|
|
Ip: ip,
|
|
UserAgent: ua,
|
|
}
|
|
|
|
//global.Log.Debugf("接口请求结果: %v", rlog)
|
|
rlr := repository.NewRequestLogRepository()
|
|
rlr.SaveLog(&rlog)
|
|
}
|
|
}
|