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.
go-library/utils/golog/gin.go

108 lines
2.3 KiB

2 years ago
package golog
import (
2 years ago
"bytes"
"encoding/json"
2 years ago
"errors"
2 years ago
"github.com/gin-gonic/gin"
"go.dtapp.net/library/utils/dorm"
2 years ago
"go.dtapp.net/library/utils/goip"
2 years ago
"gorm.io/gorm"
"os"
"runtime"
)
2 years ago
// GinClient 框架
type GinClient struct {
gormClient *gorm.DB // 驱动
2 years ago
mongoCollectionClient *dorm.MongoClient // 驱动(温馨提示:需要已选择库)
2 years ago
ipService *goip.Client // ip服务
2 years ago
config struct {
logType string // 日志类型
tableName string // 表名
insideIp string // 内网ip
hostname string // 主机名
goVersion string // go版本
} // 配置
2 years ago
}
2 years ago
// NewGinClient 创建框架实例化
func NewGinClient(attrs ...*OperationAttr) (*GinClient, error) {
2 years ago
c := &GinClient{}
for _, attr := range attrs {
2 years ago
if attr.gormClient != nil {
c.gormClient = attr.gormClient
c.config.logType = attr.logType
}
if attr.mongoCollectionClient != nil {
c.mongoCollectionClient = attr.mongoCollectionClient
c.config.logType = attr.logType
}
if attr.tableName != "" {
c.config.tableName = attr.tableName
}
2 years ago
if attr.ipService != nil {
c.ipService = attr.ipService
}
2 years ago
}
switch c.config.logType {
case logTypeGorm:
if c.gormClient == nil {
return nil, errors.New("驱动不能为空")
}
if c.config.tableName == "" {
return nil, errors.New("表名不能为空")
}
2 years ago
err := c.gormClient.Table(c.config.tableName).AutoMigrate(&apiPostgresqlLog{})
if err != nil {
return nil, errors.New("创建表失败:" + err.Error())
}
case logTypeMongo:
if c.mongoCollectionClient.Db == nil {
return nil, errors.New("驱动不能为空")
}
2 years ago
if c.config.tableName == "" {
return nil, errors.New("表名不能为空")
}
default:
return nil, errors.New("驱动为空")
2 years ago
}
2 years ago
hostname, _ := os.Hostname()
c.config.hostname = hostname
c.config.insideIp = goip.GetInsideIp()
2 years ago
c.config.goVersion = runtime.Version()
return c, nil
}
2 years ago
type bodyLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}
func (w bodyLogWriter) Write(b []byte) (int, error) {
w.body.Write(b)
return w.ResponseWriter.Write(b)
}
func (w bodyLogWriter) WriteString(s string) (int, error) {
w.body.WriteString(s)
return w.ResponseWriter.WriteString(s)
}
2 years ago
func (c *GinClient) jsonUnmarshal(data string) (result interface{}) {
_ = json.Unmarshal([]byte(data), &result)
return
}