You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
golog/gin.go

209 lines
5.7 KiB

2 years ago
package golog
import (
2 years ago
"bytes"
2 years ago
"context"
2 years ago
"encoding/json"
"errors"
"github.com/gin-gonic/gin"
"go.dtapp.net/dorm"
2 years ago
"go.dtapp.net/goip"
2 years ago
"go.dtapp.net/gorequest"
"go.dtapp.net/gotime"
"go.dtapp.net/gotrace_id"
"io/ioutil"
"net"
2 years ago
)
2 years ago
// GinClientFun *GinClient 驱动
2 years ago
type GinClientFun func() *GinClient
// GinClientJsonFun *GinClient 驱动
2 years ago
// jsonStatus bool json状态
2 years ago
type GinClientJsonFun func() (*GinClient, bool)
2 years ago
2 years ago
// GinClient 框架
type GinClient struct {
2 years ago
gormClient *dorm.GormClient // 数据库驱动
ipService *goip.Client // ip服务
zapLog *ZapLog // 日志服务
logDebug bool // 日志开关
gormConfig struct {
2 years ago
tableName string // 表名
}
2 years ago
config struct {
2 years ago
systemHostName string // 主机名
systemInsideIp string // 内网ip
systemOs string // 系统类型
systemArch string // 系统架构
goVersion string // go版本
sdkVersion string // sdk版本
systemOutsideIp string // 外网ip
jsonStatus bool // json状态
2 years ago
}
2 years ago
}
2 years ago
// GinClientConfig 框架实例配置
type GinClientConfig struct {
2 years ago
IpService *goip.Client // ip服务
GormClientFun dorm.GormClientTableFun // 日志配置
Debug bool // 日志开关
ZapLog *ZapLog // 日志服务
JsonStatus bool // json状态
2 years ago
}
// NewGinClient 创建框架实例化
// client 数据库服务
2 years ago
// tableName 表名
// ipService ip服务
2 years ago
func NewGinClient(config *GinClientConfig) (*GinClient, error) {
var ctx = context.Background()
2 years ago
2 years ago
c := &GinClient{}
2 years ago
c.zapLog = config.ZapLog
2 years ago
c.logDebug = config.Debug
2 years ago
c.config.jsonStatus = config.JsonStatus
2 years ago
gormClient, gormTableName := config.GormClientFun()
2 years ago
2 years ago
if gormClient == nil || gormClient.Db == nil {
2 years ago
return nil, errors.New("没有设置驱动")
}
2 years ago
2 years ago
if gormClient != nil || gormClient.Db != nil {
2 years ago
2 years ago
c.gormClient = gormClient
2 years ago
2 years ago
if gormTableName == "" {
return nil, errors.New("没有设置表名")
}
c.gormConfig.tableName = gormTableName
2 years ago
2 years ago
c.ipService = config.IpService
2 years ago
2 years ago
err := c.gormAutoMigrate()
2 years ago
if err != nil {
return nil, errors.New("创建表失败:" + err.Error())
}
2 years ago
}
2 years ago
2 years ago
// 配置信息
c.setConfig(ctx)
2 years ago
return c, nil
}
2 years ago
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
2 years ago
}
2 years ago
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
2 years ago
}
2 years ago
func (w bodyLogWriter) WriteString(s string) (int, error) {
w.body.WriteString(s)
return w.ResponseWriter.WriteString(s)
2 years ago
}
2 years ago
func (c *GinClient) jsonUnmarshal(data string) (result interface{}) {
_ = json.Unmarshal([]byte(data), &result)
return
}
2 years ago
// Middleware 中间件
func (c *GinClient) Middleware() gin.HandlerFunc {
return func(ginCtx *gin.Context) {
// 开始时间
startTime := gotime.Current().TimestampWithMillisecond()
requestTime := gotime.Current().Time
// 获取
data, _ := ioutil.ReadAll(ginCtx.Request.Body)
// 复用
ginCtx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data))
blw := &bodyLogWriter{body: bytes.NewBufferString(""), ResponseWriter: ginCtx.Writer}
ginCtx.Writer = blw
// 处理请求
ginCtx.Next()
// 响应
responseCode := ginCtx.Writer.Status()
responseBody := blw.body.String()
//结束时间
endTime := gotime.Current().TimestampWithMillisecond()
go func() {
var dataJson = true
// 解析请求内容
var jsonBody map[string]interface{}
// 判断是否有内容
if len(data) > 0 {
err := json.Unmarshal(data, &jsonBody)
if err != nil {
dataJson = false
}
}
clientIp := gorequest.ClientIp(ginCtx.Request)
2 years ago
var requestClientIpCountry string
var requestClientIpProvince string
var requestClientIpCity string
var requestClientIpIsp string
var requestClientIpLocationLatitude float64
var requestClientIpLocationLongitude float64
2 years ago
if c.ipService != nil {
if net.ParseIP(clientIp).To4() != nil {
// IPv4
2 years ago
info := c.ipService.Analyse(clientIp)
requestClientIpCountry = info.Ip2regionV2info.Country
requestClientIpProvince = info.Ip2regionV2info.Province
requestClientIpCity = info.Ip2regionV2info.City
requestClientIpIsp = info.Ip2regionV2info.Operator
2 years ago
requestClientIpLocationLatitude = info.GeoipInfo.Location.Latitude
requestClientIpLocationLongitude = info.GeoipInfo.Location.Longitude
2 years ago
} else if net.ParseIP(clientIp).To16() != nil {
// IPv6
2 years ago
info := c.ipService.Analyse(clientIp)
requestClientIpCountry = info.Ipv6wryInfo.Country
requestClientIpProvince = info.Ipv6wryInfo.Province
requestClientIpCity = info.Ipv6wryInfo.City
2 years ago
requestClientIpLocationLatitude = info.GeoipInfo.Location.Latitude
requestClientIpLocationLongitude = info.GeoipInfo.Location.Longitude
2 years ago
}
}
var traceId = gotrace_id.GetGinTraceId(ginCtx)
// 记录
2 years ago
if dataJson {
if c.logDebug {
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.Middleware]准备使用{gormRecordJson}保存数据:%s", data)
2 years ago
}
2 years ago
c.gormRecordJson(ginCtx, traceId, requestTime, data, responseCode, responseBody, startTime, endTime, clientIp, requestClientIpCountry, requestClientIpProvince, requestClientIpCity, requestClientIpIsp, requestClientIpLocationLatitude, requestClientIpLocationLongitude)
} else {
if c.logDebug {
c.zapLog.WithTraceIdStr(traceId).Sugar().Infof("[golog.gin.Middleware]准备使用{gormRecordXml}保存数据:%s", data)
2 years ago
}
2 years ago
c.gormRecordXml(ginCtx, traceId, requestTime, data, responseCode, responseBody, startTime, endTime, clientIp, requestClientIpCountry, requestClientIpProvince, requestClientIpCity, requestClientIpIsp, requestClientIpLocationLatitude, requestClientIpLocationLongitude)
2 years ago
}
}()
}
}