parent
221a820e72
commit
9eefb9eef1
@ -0,0 +1,31 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/dtapps/go-library"
|
||||
"github.com/dtapps/go-library/utils/goip"
|
||||
"go.mongodb.org/mongo-driver/version"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func (c *ApiClient) setConfig(ctx context.Context) {
|
||||
|
||||
info := getSystem()
|
||||
|
||||
c.config.systemHostname = info.SystemHostname
|
||||
c.config.systemOs = info.SystemOs
|
||||
c.config.systemVersion = info.SystemVersion
|
||||
c.config.systemKernel = info.SystemKernel
|
||||
c.config.systemKernelVersion = info.SystemKernelVersion
|
||||
c.config.systemBootTime = info.SystemBootTime
|
||||
c.config.cpuCores = info.CpuCores
|
||||
c.config.cpuModelName = info.CpuModelName
|
||||
c.config.cpuMhz = info.CpuMhz
|
||||
|
||||
c.config.systemInsideIp = goip.GetInsideIp(ctx)
|
||||
|
||||
c.config.sdkVersion = go_library.Version()
|
||||
c.config.goVersion = runtime.Version()
|
||||
|
||||
c.config.mongoSdkVersion = version.Driver
|
||||
}
|
@ -0,0 +1,8 @@
|
||||
package golog
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
currentIpNoConfig = errors.New("请配置 CurrentIp")
|
||||
dbClientFunNoConfig = errors.New("请配置 GormClientFun 或 MongoClientFun")
|
||||
)
|
@ -0,0 +1,31 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/dtapps/go-library"
|
||||
"github.com/dtapps/go-library/utils/goip"
|
||||
"go.mongodb.org/mongo-driver/version"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
func (c *GinClient) setConfig(ctx context.Context) {
|
||||
|
||||
info := getSystem()
|
||||
|
||||
c.config.systemHostname = info.SystemHostname
|
||||
c.config.systemOs = info.SystemOs
|
||||
c.config.systemVersion = info.SystemVersion
|
||||
c.config.systemKernel = info.SystemKernel
|
||||
c.config.systemKernelVersion = info.SystemKernelVersion
|
||||
c.config.systemBootTime = info.SystemBootTime
|
||||
c.config.cpuCores = info.CpuCores
|
||||
c.config.cpuModelName = info.CpuModelName
|
||||
c.config.cpuMhz = info.CpuMhz
|
||||
|
||||
c.config.systemInsideIp = goip.GetInsideIp(ctx)
|
||||
|
||||
c.config.sdkVersion = go_library.Version()
|
||||
c.config.goVersion = runtime.Version()
|
||||
|
||||
c.config.mongoSdkVersion = version.Driver
|
||||
}
|
@ -1,191 +1,247 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"github.com/dtapps/go-library"
|
||||
"context"
|
||||
"github.com/dtapps/go-library/utils/dorm"
|
||||
"github.com/dtapps/go-library/utils/goip"
|
||||
"github.com/dtapps/go-library/utils/gotime"
|
||||
"github.com/dtapps/go-library/utils/gotrace_id"
|
||||
"github.com/dtapps/go-library/utils/gourl"
|
||||
"github.com/dtapps/go-library/utils/goxml"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ginMongoLogRequestIpLocationLocation struct {
|
||||
Type string `json:"type,omitempty" bson:"type,omitempty"` // GeoJSON类型
|
||||
Coordinates []float64 `json:"coordinates,omitempty" bson:"coordinates,omitempty"` // 经度,纬度
|
||||
}
|
||||
|
||||
// 模型结构体
|
||||
type ginMongoLog struct {
|
||||
LogId primitive.ObjectID `json:"log_id,omitempty" bson:"_id,omitempty"` //【记录】编号
|
||||
TraceId string `json:"trace_id,omitempty" bson:"trace_id,omitempty"` //【系统】链编号
|
||||
RequestTime int64 `json:"request_time,omitempty" bson:"request_time,omitempty"` //【请求】时间
|
||||
RequestUri string `json:"request_uri,omitempty" bson:"request_uri,omitempty"` //【请求】请求链接 域名+路径+参数
|
||||
RequestUrl string `json:"request_url,omitempty" bson:"request_url,omitempty"` //【请求】请求链接 域名+路径
|
||||
RequestApi string `json:"request_api,omitempty" bson:"request_api,omitempty"` //【请求】请求接口 路径
|
||||
RequestMethod string `json:"request_method,omitempty" bson:"request_method,omitempty"` //【请求】请求方式
|
||||
RequestProto string `json:"request_proto,omitempty" bson:"request_proto,omitempty"` //【请求】请求协议
|
||||
RequestUa string `json:"request_ua,omitempty" bson:"request_ua,omitempty"` //【请求】请求UA
|
||||
RequestReferer string `json:"request_referer,omitempty" bson:"request_referer,omitempty"` //【请求】请求referer
|
||||
RequestBody interface{} `json:"request_body,omitempty" bson:"request_body,omitempty"` //【请求】请求主体
|
||||
RequestUrlQuery interface{} `json:"request_url_query,omitempty" bson:"request_url_query,omitempty"` //【请求】请求URL参数
|
||||
RequestIp string `json:"request_ip,omitempty" bson:"request_ip,omitempty"` //【请求】请求客户端Ip
|
||||
RequestIpCountry string `json:"request_ip_country,omitempty" bson:"request_ip_country,omitempty"` //【请求】请求客户端城市
|
||||
RequestIpRegion string `json:"request_ip_region,omitempty" bson:"request_ip_region,omitempty"` //【请求】请求客户端区域
|
||||
RequestIpProvince string `json:"request_ip_province,omitempty" bson:"request_ip_province,omitempty"` //【请求】请求客户端省份
|
||||
RequestIpCity string `json:"request_ip_city,omitempty" bson:"request_ip_city,omitempty"` //【请求】请求客户端城市
|
||||
RequestIpIsp string `json:"request_ip_isp,omitempty" bson:"request_ip_isp,omitempty"` //【请求】请求客户端运营商
|
||||
RequestHeader interface{} `json:"request_header,omitempty" bson:"request_header,omitempty"` //【请求】请求头
|
||||
ResponseTime int64 `json:"response_time,omitempty" bson:"response_time,omitempty"` //【返回】时间
|
||||
ResponseCode int `json:"response_code,omitempty" bson:"response_code,omitempty"` //【返回】状态码
|
||||
ResponseMsg string `json:"response_msg,omitempty" bson:"response_msg,omitempty"` //【返回】描述
|
||||
ResponseData interface{} `json:"response_data,omitempty" bson:"response_data,omitempty"` //【返回】数据
|
||||
CostTime int64 `json:"cost_time,omitempty" bson:"cost_time,omitempty"` //【系统】花费时间
|
||||
SystemHostName string `json:"system_host_name,omitempty" bson:"system_host_name,omitempty"` //【系统】主机名
|
||||
SystemInsideIp string `json:"system_inside_ip,omitempty" bson:"system_inside_ip,omitempty"` //【系统】内网ip
|
||||
GoVersion string `json:"go_version,omitempty" bson:"go_version,omitempty"` //【程序】Go版本
|
||||
SdkVersion string `json:"sdk_version,omitempty" bson:"sdk_version,omitempty"` //【程序】Sdk版本
|
||||
LogId primitive.ObjectID `json:"log_id,omitempty" bson:"_id,omitempty"` //【记录】编号
|
||||
TraceId string `json:"trace_id,omitempty" bson:"trace_id,omitempty"` //【记录】跟踪编号
|
||||
RequestTime string `json:"request_time,omitempty" bson:"request_time,omitempty"` //【请求】时间
|
||||
RequestUri string `json:"request_uri,omitempty" bson:"request_uri,omitempty"` //【请求】请求链接 域名+路径+参数
|
||||
RequestUrl string `json:"request_url,omitempty" bson:"request_url,omitempty"` //【请求】请求链接 域名+路径
|
||||
RequestApi string `json:"request_api,omitempty" bson:"request_api,omitempty"` //【请求】请求接口 路径
|
||||
RequestMethod string `json:"request_method,omitempty" bson:"request_method,omitempty"` //【请求】请求方式
|
||||
RequestProto string `json:"request_proto,omitempty" bson:"request_proto,omitempty"` //【请求】请求协议
|
||||
RequestUa string `json:"request_ua,omitempty" bson:"request_ua,omitempty"` //【请求】请求UA
|
||||
RequestReferer string `json:"request_referer,omitempty" bson:"request_referer,omitempty"` //【请求】请求referer
|
||||
RequestBody interface{} `json:"request_body,omitempty" bson:"request_body,omitempty"` //【请求】请求主体
|
||||
RequestUrlQuery interface{} `json:"request_url_query,omitempty" bson:"request_url_query,omitempty"` //【请求】请求URL参数
|
||||
RequestIp struct {
|
||||
Ip string `json:"ip,omitempty" bson:"ip,omitempty"` //【请求】请求客户端Ip
|
||||
Continent string `json:"continent,omitempty" bson:"continent,omitempty"` //【请求】请求客户端大陆
|
||||
Country string `json:"country,omitempty" bson:"country,omitempty"` //【请求】请求客户端国家
|
||||
Province string `json:"province,omitempty" bson:"province,omitempty"` //【请求】请求客户端省份
|
||||
City string `json:"city,omitempty" bson:"city,omitempty"` //【请求】请求客户端城市
|
||||
Isp string `json:"isp,omitempty" bson:"isp,omitempty"` //【请求】请求客户端运营商
|
||||
} `json:"request_ip,omitempty" bson:"request_ip,omitempty"` //【请求】请求客户端信息
|
||||
RequestIpLocation interface{} `json:"request_ip_location,omitempty" bson:"request_ip_location,omitempty"` //【请求】请求客户端位置
|
||||
RequestHeader interface{} `json:"request_header,omitempty" bson:"request_header,omitempty"` //【请求】请求头
|
||||
ResponseTime string `json:"response_time,omitempty" bson:"response_time,omitempty"` //【返回】时间
|
||||
ResponseCode int `json:"response_code,omitempty" bson:"response_code,omitempty"` //【返回】状态码
|
||||
ResponseMsg string `json:"response_msg,omitempty" bson:"response_msg,omitempty"` //【返回】描述
|
||||
ResponseData interface{} `json:"response_data,omitempty" bson:"response_data,omitempty"` //【返回】数据
|
||||
CostTime int64 `json:"cost_time,omitempty" bson:"cost_time,omitempty"` //【系统】花费时间
|
||||
System struct {
|
||||
Hostname string `json:"hostname" bson:"hostname"` //【系统】主机名
|
||||
Os string `json:"os" bson:"os"` //【系统】系统类型
|
||||
Version string `json:"version" bson:"version"` //【系统】系统版本
|
||||
Kernel string `json:"kernel" bson:"kernel"` //【系统】系统内核
|
||||
KernelVersion string `json:"kernel_version" bson:"kernel_version"` //【系统】系统内核版本
|
||||
BootTime string `json:"boot_time" bson:"boot_time"` //【系统】系统开机时间
|
||||
CpuCores int `json:"cpu_cores,omitempty" bson:"cpu_cores,omitempty"` //【系统】CPU核数
|
||||
CpuModelName string `json:"cpu_model_name,omitempty" bson:"cpu_model_name,omitempty"` //【系统】CPU型号名称
|
||||
CpuMhz float64 `json:"cpu_mhz,omitempty" bson:"cpu_mhz,omitempty"` //【系统】CPU兆赫
|
||||
InsideIp string `json:"inside_ip" bson:"inside_ip"` //【系统】内网ip
|
||||
OutsideIp string `json:"outside_ip" bson:"outside_ip"` //【系统】外网ip
|
||||
GoVersion string `json:"go_version,omitempty" bson:"go_version,omitempty"` //【系统】go版本
|
||||
SdkVersion string `json:"sdk_version,omitempty" bson:"sdk_version,omitempty"` //【系统】sdk版本
|
||||
MongoVersion string `json:"mongo_version,omitempty" bson:"mongo_version,omitempty"` //【系统】mongo版本
|
||||
MongoSdkVersion string `json:"mongo_sdk_version,omitempty" bson:"mongo_sdk_version,omitempty"` //【系统】mongo sdk版本
|
||||
} `json:"system,omitempty" bson:"system,omitempty"` //【系统】信息
|
||||
}
|
||||
|
||||
// 记录日志
|
||||
func (c *GinClient) mongoRecord(mongoLog ginMongoLog) error {
|
||||
// 创建集合
|
||||
func (c *GinClient) mongoCreateCollection(ctx context.Context) {
|
||||
err := c.mongoClient.Database(c.mongoConfig.databaseName).CreateCollection(ctx, c.mongoConfig.collectionName, options.CreateCollection().SetCollation(&options.Collation{
|
||||
Locale: "request_time",
|
||||
Strength: -1,
|
||||
}))
|
||||
if err != nil {
|
||||
c.zapLog.WithTraceId(ctx).Sugar().Error("创建集合:", err)
|
||||
}
|
||||
}
|
||||
|
||||
mongoLog.SystemHostName = c.config.hostname
|
||||
if mongoLog.SystemInsideIp == "" {
|
||||
mongoLog.SystemInsideIp = c.config.insideIp
|
||||
// 创建索引
|
||||
func (c *GinClient) mongoCreateIndexes(ctx context.Context) {
|
||||
_, err := c.mongoClient.Database(c.mongoConfig.databaseName).Collection(c.mongoConfig.collectionName).CreateManyIndexes(ctx, []mongo.IndexModel{
|
||||
{
|
||||
Keys: bson.D{{
|
||||
Key: "trace_id",
|
||||
Value: -1,
|
||||
}},
|
||||
}, {
|
||||
Keys: bson.D{{
|
||||
Key: "request_time",
|
||||
Value: -1,
|
||||
}},
|
||||
}, {
|
||||
Keys: bson.D{{
|
||||
Key: "request_method",
|
||||
Value: 1,
|
||||
}},
|
||||
}, {
|
||||
Keys: bson.D{{
|
||||
Key: "response_time",
|
||||
Value: -1,
|
||||
}},
|
||||
}, {
|
||||
Keys: bson.D{{
|
||||
Key: "response_code",
|
||||
Value: 1,
|
||||
}},
|
||||
}, {
|
||||
Keys: bson.D{{
|
||||
Key: "request_ip_location",
|
||||
Value: "2dsphere",
|
||||
}},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
c.zapLog.WithTraceId(ctx).Sugar().Errorf("创建索引:%s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// MongoDelete 删除
|
||||
func (c *GinClient) MongoDelete(ctx context.Context, hour int64) (*mongo.DeleteResult, error) {
|
||||
filter := bson.D{{"request_time", bson.D{{"$lt", gotime.SetCurrent(gotime.Current().BeforeHour(hour).Time)}}}}
|
||||
return c.mongoClient.Database(c.mongoConfig.databaseName).Collection(c.mongoConfig.collectionName).DeleteMany(ctx, filter)
|
||||
}
|
||||
|
||||
// 记录日志
|
||||
func (c *GinClient) mongoRecord(ctx context.Context, data ginMongoLog) {
|
||||
|
||||
data.LogId = primitive.NewObjectID() //【记录】编号
|
||||
data.System.Hostname = c.config.systemHostname //【系统】主机名
|
||||
data.System.Os = c.config.systemOs //【系统】系统类型
|
||||
data.System.Version = c.config.systemVersion //【系统】系统版本
|
||||
data.System.Kernel = c.config.systemKernel //【系统】系统内核
|
||||
data.System.KernelVersion = c.config.systemKernelVersion //【系统】系统内核版本
|
||||
data.System.BootTime = gotime.SetCurrent(gotime.SetCurrentUnix(int64(c.config.systemBootTime)).Time).Format() //【系统】系统开机时间
|
||||
data.System.CpuCores = c.config.cpuCores //【系统】CPU核数
|
||||
data.System.CpuModelName = c.config.cpuModelName //【程序】CPU型号名称
|
||||
data.System.CpuMhz = c.config.cpuMhz //【系统】CPU兆赫
|
||||
data.System.InsideIp = c.config.systemInsideIp //【系统】内网ip
|
||||
data.System.OutsideIp = c.config.systemOutsideIp //【系统】外网ip
|
||||
data.System.GoVersion = c.config.goVersion //【系统】Go版本
|
||||
data.System.SdkVersion = c.config.sdkVersion //【系统】Sdk版本
|
||||
data.System.MongoVersion = c.config.mongoVersion //【系统】mongo版本
|
||||
data.System.MongoSdkVersion = c.config.mongoSdkVersion //【系统】mongo sdk版本
|
||||
|
||||
_, err := c.mongoClient.Database(c.mongoConfig.databaseName).Collection(c.mongoConfig.collectionName).InsertOne(ctx, data)
|
||||
if err != nil {
|
||||
c.zapLog.WithTraceIdStr(data.TraceId).Sugar().Errorf("保存框架日志错误:%s", err)
|
||||
c.zapLog.WithTraceIdStr(data.TraceId).Sugar().Errorf("保存框架日志数据:%+v", data)
|
||||
}
|
||||
mongoLog.GoVersion = c.config.goVersion
|
||||
}
|
||||
|
||||
mongoLog.SdkVersion = go_library.Version()
|
||||
func (c *GinClient) mongoRecordJson(ginCtx *gin.Context, traceId string, requestTime time.Time, requestBody []byte, responseCode int, responseBody string, startTime, endTime int64, ipInfo goip.AnalyseResult) {
|
||||
|
||||
var ctx = gotrace_id.SetGinTraceIdContext(context.Background(), ginCtx)
|
||||
|
||||
data := ginMongoLog{
|
||||
TraceId: traceId, //【记录】跟踪编号
|
||||
RequestTime: gotime.SetCurrent(requestTime).Format(), //【请求】时间
|
||||
RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口
|
||||
RequestMethod: ginCtx.Request.Method, //【请求】请求方式
|
||||
RequestProto: ginCtx.Request.Proto, //【请求】请求协议
|
||||
RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA
|
||||
RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer
|
||||
RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数
|
||||
RequestHeader: ginCtx.Request.Header, //【请求】请求头
|
||||
ResponseTime: gotime.Current().Format(), //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: dorm.JsonDecodeNoError([]byte(responseBody)), //【返回】数据
|
||||
CostTime: endTime - startTime, //【系统】花费时间
|
||||
}
|
||||
if ginCtx.Request.TLS == nil {
|
||||
data.RequestUri = "http://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
} else {
|
||||
data.RequestUri = "https://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
}
|
||||
|
||||
mongoLog.LogId = primitive.NewObjectID()
|
||||
if len(requestBody) > 0 {
|
||||
data.RequestBody = dorm.JsonDecodeNoError(requestBody) //【请求】请求主体
|
||||
}
|
||||
|
||||
_, err := c.mongoClient.Database(c.config.databaseName).Collection(c.config.collectionName).InsertOne(mongoLog)
|
||||
//【请求】请求客户端信息
|
||||
data.RequestIp.Ip = ipInfo.Ip
|
||||
data.RequestIp.Continent = ipInfo.Continent
|
||||
data.RequestIp.Country = ipInfo.Country
|
||||
data.RequestIp.Province = ipInfo.Province
|
||||
data.RequestIp.City = ipInfo.City
|
||||
data.RequestIp.Isp = ipInfo.Isp
|
||||
if ipInfo.LocationLatitude != 0 && ipInfo.LocationLongitude != 0 {
|
||||
data.RequestIpLocation = ginMongoLogRequestIpLocationLocation{
|
||||
Type: "Point",
|
||||
Coordinates: []float64{ipInfo.LocationLongitude, ipInfo.LocationLatitude},
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
c.mongoRecord(ctx, data)
|
||||
}
|
||||
|
||||
// MongoQuery 查询
|
||||
func (c *GinClient) MongoQuery() *dorm.MongoClient {
|
||||
return c.mongoClient.Database(c.config.databaseName).Collection(c.config.collectionName)
|
||||
}
|
||||
func (c *GinClient) mongoRecordXml(ginCtx *gin.Context, traceId string, requestTime time.Time, requestBody []byte, responseCode int, responseBody string, startTime, endTime int64, ipInfo goip.AnalyseResult) {
|
||||
|
||||
var ctx = gotrace_id.SetGinTraceIdContext(context.Background(), ginCtx)
|
||||
|
||||
data := ginMongoLog{
|
||||
TraceId: traceId, //【记录】跟踪编号
|
||||
RequestTime: gotime.SetCurrent(requestTime).Format(), //【请求】时间
|
||||
RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口
|
||||
RequestMethod: ginCtx.Request.Method, //【请求】请求方式
|
||||
RequestProto: ginCtx.Request.Proto, //【请求】请求协议
|
||||
RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA
|
||||
RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer
|
||||
RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数
|
||||
RequestHeader: ginCtx.Request.Header, //【请求】请求头
|
||||
ResponseTime: gotime.Current().Format(), //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: dorm.JsonDecodeNoError([]byte(responseBody)), //【返回】数据
|
||||
CostTime: endTime - startTime, //【系统】花费时间
|
||||
}
|
||||
if ginCtx.Request.TLS == nil {
|
||||
data.RequestUri = "http://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
} else {
|
||||
data.RequestUri = "https://" + ginCtx.Request.Host + ginCtx.Request.RequestURI //【请求】请求链接
|
||||
}
|
||||
|
||||
// MongoMiddleware 中间件
|
||||
func (c *GinClient) MongoMiddleware() 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 xmlBody map[string]string
|
||||
var jsonBody map[string]interface{}
|
||||
_ = json.Unmarshal(data, &jsonBody)
|
||||
if len(jsonBody) <= 0 {
|
||||
xmlBody = goxml.XmlDecode(string(data))
|
||||
}
|
||||
|
||||
requestClientIpCountry, requestClientIpRegion, requestClientIpProvince, requestClientIpCity, requestClientIpIsp := "", "", "", "", ""
|
||||
if c.ipService != nil {
|
||||
if net.ParseIP(ginCtx.ClientIP()).To4() != nil {
|
||||
// 判断是不是IPV4
|
||||
_, info := c.ipService.Ipv4(ginCtx.ClientIP())
|
||||
requestClientIpCountry = info.Country
|
||||
requestClientIpRegion = info.Region
|
||||
requestClientIpProvince = info.Province
|
||||
requestClientIpCity = info.City
|
||||
requestClientIpIsp = info.ISP
|
||||
} else if net.ParseIP(ginCtx.ClientIP()).To16() != nil {
|
||||
// 判断是不是IPV6
|
||||
info := c.ipService.Ipv6(ginCtx.ClientIP())
|
||||
requestClientIpCountry = info.Country
|
||||
requestClientIpProvince = info.Province
|
||||
requestClientIpCity = info.City
|
||||
}
|
||||
}
|
||||
|
||||
// 记录
|
||||
if c.mongoClient != nil {
|
||||
host := ""
|
||||
if ginCtx.Request.TLS == nil {
|
||||
host = "http://" + ginCtx.Request.Host
|
||||
} else {
|
||||
host = "https://" + ginCtx.Request.Host
|
||||
}
|
||||
if len(jsonBody) > 0 {
|
||||
c.mongoRecord(ginMongoLog{
|
||||
TraceId: gotrace_id.GetGinTraceId(ginCtx), //【系统】链编号
|
||||
RequestTime: gotime.SetCurrent(requestTime).Timestamp(), //【请求】时间
|
||||
RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口
|
||||
RequestMethod: ginCtx.Request.Method, //【请求】请求方式
|
||||
RequestProto: ginCtx.Request.Proto, //【请求】请求协议
|
||||
RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA
|
||||
RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer
|
||||
RequestBody: jsonBody, //【请求】请求主体
|
||||
RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数
|
||||
RequestIp: ginCtx.ClientIP(), //【请求】请求客户端Ip
|
||||
RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市
|
||||
RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域
|
||||
RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份
|
||||
RequestIpCity: requestClientIpCity, //【请求】请求客户端城市
|
||||
RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商
|
||||
RequestHeader: ginCtx.Request.Header, //【请求】请求头
|
||||
ResponseTime: gotime.SetCurrent(gotime.Current().Time).Timestamp(), //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据
|
||||
CostTime: endTime - startTime, //【系统】花费时间
|
||||
})
|
||||
} else {
|
||||
c.mongoRecord(ginMongoLog{
|
||||
TraceId: gotrace_id.GetGinTraceId(ginCtx), //【系统】链编号
|
||||
RequestTime: gotime.SetCurrent(requestTime).Timestamp(), //【请求】时间
|
||||
RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接
|
||||
RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口
|
||||
RequestMethod: ginCtx.Request.Method, //【请求】请求方式
|
||||
RequestProto: ginCtx.Request.Proto, //【请求】请求协议
|
||||
RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA
|
||||
RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer
|
||||
RequestBody: xmlBody, //【请求】请求主体
|
||||
RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数
|
||||
RequestIp: ginCtx.ClientIP(), //【请求】请求客户端Ip
|
||||
RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市
|
||||
RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域
|
||||
RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份
|
||||
RequestIpCity: requestClientIpCity, //【请求】请求客户端城市
|
||||
RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商
|
||||
RequestHeader: ginCtx.Request.Header, //【请求】请求头
|
||||
ResponseTime: gotime.SetCurrent(gotime.Current().Time).Timestamp(), //【返回】时间
|
||||
ResponseCode: responseCode, //【返回】状态码
|
||||
ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据
|
||||
CostTime: endTime - startTime, //【系统】花费时间
|
||||
})
|
||||
}
|
||||
}
|
||||
}()
|
||||
if len(requestBody) > 0 {
|
||||
data.RequestBody = dorm.XmlDecodeNoError(requestBody) //【请求】请求主体
|
||||
}
|
||||
|
||||
//【请求】请求客户端信息
|
||||
data.RequestIp.Ip = ipInfo.Ip
|
||||
data.RequestIp.Continent = ipInfo.Continent
|
||||
data.RequestIp.Country = ipInfo.Country
|
||||
data.RequestIp.Province = ipInfo.Province
|
||||
data.RequestIp.City = ipInfo.City
|
||||
data.RequestIp.Isp = ipInfo.Isp
|
||||
if ipInfo.LocationLatitude != 0 && ipInfo.LocationLongitude != 0 {
|
||||
data.RequestIpLocation = ginMongoLogRequestIpLocationLocation{
|
||||
Type: "Point",
|
||||
Coordinates: []float64{ipInfo.LocationLongitude, ipInfo.LocationLatitude},
|
||||
}
|
||||
}
|
||||
|
||||
c.mongoRecord(ctx, data)
|
||||
}
|
||||
|
@ -1,8 +0,0 @@
|
||||
package golog
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
func JsonEncodeNoError(data interface{}) string {
|
||||
jsons, _ := json.Marshal(data)
|
||||
return string(jsons)
|
||||
}
|
@ -1,53 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"github.com/dtapps/go-library/utils/dorm"
|
||||
"github.com/dtapps/go-library/utils/goip"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
logTypeGorm = "gorm"
|
||||
logTypeMongo = "mongo"
|
||||
)
|
||||
|
||||
// OperationAttr 操作属性
|
||||
type OperationAttr struct {
|
||||
gormClient *gorm.DB // 数据库驱动
|
||||
mongoClient *dorm.MongoClient // 数据库驱动
|
||||
ipService *goip.Client // ip服务
|
||||
logType string // 类型
|
||||
tableName string // 表名
|
||||
databaseName string // 库名
|
||||
collectionName string // 表名
|
||||
}
|
||||
|
||||
// WithGormClient 设置数据库驱动
|
||||
func WithGormClient(client *gorm.DB) *OperationAttr {
|
||||
return &OperationAttr{gormClient: client, logType: logTypeGorm}
|
||||
}
|
||||
|
||||
// WithMongoClient 设置数据库驱动
|
||||
func WithMongoClient(client *dorm.MongoClient) *OperationAttr {
|
||||
return &OperationAttr{mongoClient: client, logType: logTypeMongo}
|
||||
}
|
||||
|
||||
// WithTableName 设置表名
|
||||
func WithTableName(tableName string) *OperationAttr {
|
||||
return &OperationAttr{tableName: tableName}
|
||||
}
|
||||
|
||||
// WithDatabaseName 设置库名
|
||||
func WithDatabaseName(databaseName string) *OperationAttr {
|
||||
return &OperationAttr{databaseName: databaseName}
|
||||
}
|
||||
|
||||
// WithCollectionName 设置表名
|
||||
func WithCollectionName(collectionName string) *OperationAttr {
|
||||
return &OperationAttr{collectionName: collectionName}
|
||||
}
|
||||
|
||||
// WithIpService 设置ip服务
|
||||
func WithIpService(ipService *goip.Client) *OperationAttr {
|
||||
return &OperationAttr{ipService: ipService}
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
||||
type System struct {
|
||||
Variable []string // 环境变量
|
||||
Hostname string // 主机名
|
||||
Twd string // 当前目录
|
||||
Uid int // 用户ID
|
||||
EUid int // 有效用户ID
|
||||
Gid int // 组ID
|
||||
EGid int // 有效组ID
|
||||
Pid int // 进程ID
|
||||
PPid int // 父进程ID
|
||||
Version string // 版本
|
||||
}
|
||||
|
||||
func (s *System) Init() *System {
|
||||
s.Variable = os.Environ()
|
||||
s.Hostname, _ = os.Hostname()
|
||||
s.Twd, _ = os.Getwd()
|
||||
s.Uid = os.Getuid()
|
||||
s.EUid = os.Geteuid()
|
||||
s.Gid = os.Getgid()
|
||||
s.EGid = os.Getegid()
|
||||
s.Pid = os.Getpid()
|
||||
s.PPid = os.Getppid()
|
||||
s.Version = runtime.Version()
|
||||
return s
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/dtapps/go-library/utils/gotime"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/schema"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TimeString struct {
|
||||
Time time.Time
|
||||
}
|
||||
|
||||
// Value 插入数据,把时间转字符串
|
||||
func (t TimeString) Value() (driver.Value, error) {
|
||||
return gotime.SetCurrent(t.Time).Format(), nil
|
||||
}
|
||||
|
||||
// Scan 查询数据,把字符串转时间
|
||||
func (t *TimeString) Scan(value interface{}) error {
|
||||
|
||||
// 如果是空值,直接返回
|
||||
data, ok := value.(string)
|
||||
if !ok {
|
||||
return errors.New(fmt.Sprint("无法解析:", value))
|
||||
}
|
||||
|
||||
// 解析时间
|
||||
result := gotime.SetCurrentParse(data)
|
||||
|
||||
*t = TimeString{
|
||||
Time: result.Time,
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON JSON序列化
|
||||
func (t TimeString) MarshalJSON() ([]byte, error) {
|
||||
return []byte(fmt.Sprintf(`"%s"`, gotime.SetCurrent(t.Time).Format())), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON JSON反序列化
|
||||
func (t *TimeString) UnmarshalJSON(data []byte) (err error) {
|
||||
// 删除双引号
|
||||
if data[0] == '"' && data[len(data)-1] == '"' {
|
||||
data = data[1 : len(data)-1]
|
||||
}
|
||||
result := gotime.SetCurrentParse(string(data))
|
||||
*t = TimeString{
|
||||
Time: result.Time,
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (t TimeString) GormDBDataType(db *gorm.DB, field *schema.Field) string {
|
||||
// 使用 field.Tag、field.TagSettings 获取字段的 tag
|
||||
// 查看 https://github.com/go-gorm/gorm/blob/master/schema/field.go 获取全部的选项
|
||||
|
||||
// 根据不同的数据库驱动返回不同的数据类型
|
||||
switch db.Dialector.Name() {
|
||||
case "mysql", "sqlite":
|
||||
return "varchar"
|
||||
case "postgres":
|
||||
return "text"
|
||||
}
|
||||
return ""
|
||||
}
|
@ -0,0 +1,137 @@
|
||||
package golog
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/dtapps/go-library/utils/gotime"
|
||||
"github.com/dtapps/go-library/utils/gotrace_id"
|
||||
"github.com/natefinch/lumberjack"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ZapLogConfig struct {
|
||||
LogPath string // 日志文件路径
|
||||
LogName string // 日志文件名
|
||||
MaxSize int // 单位为MB,默认为512MB
|
||||
MaxBackups int // 保留旧文件的最大个数
|
||||
MaxAge int // 文件最多保存多少天 0=不删除
|
||||
LocalTime bool // 采用本地时间
|
||||
Compress bool // 是否压缩日志
|
||||
JsonFormat bool // 是否输出为json格式
|
||||
ShowLine bool // 显示代码行
|
||||
LogInConsole bool // 是否同时输出到控制台
|
||||
}
|
||||
|
||||
type ZapLog struct {
|
||||
config *ZapLogConfig
|
||||
logger *zap.Logger
|
||||
zapCore zapcore.Core
|
||||
}
|
||||
|
||||
func NewZapLog(config *ZapLogConfig) *ZapLog {
|
||||
|
||||
zl := &ZapLog{config: config}
|
||||
|
||||
var syncer zapcore.WriteSyncer
|
||||
|
||||
if zl.config.LogPath != "" && zl.config.LogName != "" {
|
||||
// 定义日志切割配置
|
||||
hook := lumberjack.Logger{
|
||||
Filename: zl.config.LogPath + zl.config.LogName, // ⽇志⽂件路径
|
||||
MaxSize: zl.config.MaxSize, // 单位为MB,默认为512MB
|
||||
MaxBackups: zl.config.MaxBackups, // 保留旧文件的最大个数
|
||||
LocalTime: zl.config.LocalTime, // 采用本地时间
|
||||
Compress: zl.config.Compress, // 是否压缩日志
|
||||
}
|
||||
if zl.config.MaxAge > 0 {
|
||||
// 文件最多保存多少天
|
||||
hook.MaxAge = zl.config.MaxAge
|
||||
}
|
||||
if zl.config.LogInConsole {
|
||||
// 在控制台和文件输出日志
|
||||
syncer = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(&hook))
|
||||
} else {
|
||||
// 在文件输出日志
|
||||
syncer = zapcore.AddSync(&hook)
|
||||
}
|
||||
} else {
|
||||
// 在控制台输出日志
|
||||
syncer = zapcore.NewMultiWriteSyncer()
|
||||
}
|
||||
|
||||
// 自定义时间输出格式
|
||||
customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
|
||||
enc.AppendString(t.Format(gotime.DateTimeFormat))
|
||||
}
|
||||
|
||||
// 自定义日志级别显示
|
||||
customLevelEncoder := func(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
|
||||
enc.AppendString(level.CapitalString())
|
||||
}
|
||||
|
||||
// 定义zap配置信息
|
||||
encoderConf := zapcore.EncoderConfig{
|
||||
CallerKey: "caller_line", // 打印文件名和行数
|
||||
LevelKey: "level_name",
|
||||
MessageKey: "msg",
|
||||
TimeKey: "time",
|
||||
NameKey: "logger",
|
||||
StacktraceKey: "stacktrace",
|
||||
LineEnding: zapcore.DefaultLineEnding,
|
||||
EncodeTime: customTimeEncoder, // 自定义时间格式
|
||||
EncodeLevel: customLevelEncoder, // 小写编码器
|
||||
EncodeCaller: zapcore.ShortCallerEncoder, // 全路径编码器
|
||||
EncodeDuration: zapcore.SecondsDurationEncoder,
|
||||
EncodeName: zapcore.FullNameEncoder,
|
||||
}
|
||||
|
||||
// 判断是否json格式输出
|
||||
if zl.config.JsonFormat {
|
||||
zl.zapCore = zapcore.NewCore(zapcore.NewJSONEncoder(encoderConf),
|
||||
syncer, zap.NewAtomicLevelAt(zapcore.InfoLevel))
|
||||
} else {
|
||||
zl.zapCore = zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConf),
|
||||
syncer, zap.NewAtomicLevelAt(zapcore.InfoLevel))
|
||||
}
|
||||
|
||||
zl.logger = zl.withShowLine(zap.New(zl.zapCore))
|
||||
|
||||
return zl
|
||||
}
|
||||
|
||||
// 判断是否显示代码行号
|
||||
func (zl *ZapLog) withShowLine(logger *zap.Logger) *zap.Logger {
|
||||
if zl.config.ShowLine {
|
||||
logger = logger.WithOptions(zap.AddCaller())
|
||||
}
|
||||
return logger
|
||||
}
|
||||
|
||||
// WithLogger 跟踪编号
|
||||
func (zl *ZapLog) WithLogger() *zap.Logger {
|
||||
return zl.logger
|
||||
}
|
||||
|
||||
// WithTraceId 跟踪编号
|
||||
func (zl *ZapLog) WithTraceId(ctx context.Context) *zap.Logger {
|
||||
logger := zl.logger
|
||||
logger = logger.With(zapcore.Field{
|
||||
Key: "trace_id",
|
||||
Type: zapcore.StringType,
|
||||
String: gotrace_id.GetTraceIdContext(ctx),
|
||||
})
|
||||
return logger
|
||||
}
|
||||
|
||||
// WithTraceIdStr 跟踪编号
|
||||
func (zl *ZapLog) WithTraceIdStr(traceId string) *zap.Logger {
|
||||
logger := zl.logger
|
||||
logger = logger.With(zapcore.Field{
|
||||
Key: "trace_id",
|
||||
Type: zapcore.StringType,
|
||||
String: traceId,
|
||||
})
|
||||
return logger
|
||||
}
|
@ -0,0 +1,24 @@
|
||||
package gophp
|
||||
|
||||
// ChunkSplit 将字符串拆分成更小的块
|
||||
func ChunkSplit(body string, chunklen uint, end string) string {
|
||||
if end == "" {
|
||||
end = "\r\n"
|
||||
}
|
||||
runes, erunes := []rune(body), []rune(end)
|
||||
l := uint(len(runes))
|
||||
if l <= 1 || l < chunklen {
|
||||
return body + end
|
||||
}
|
||||
ns := make([]rune, 0, len(runes)+len(erunes))
|
||||
var i uint
|
||||
for i = 0; i < l; i += chunklen {
|
||||
if i+chunklen > l {
|
||||
ns = append(ns, runes[i:]...)
|
||||
} else {
|
||||
ns = append(ns, runes[i:i+chunklen]...)
|
||||
}
|
||||
ns = append(ns, erunes...)
|
||||
}
|
||||
return string(ns)
|
||||
}
|
@ -0,0 +1,65 @@
|
||||
package gorequest
|
||||
|
||||
// HeaderIsImg 判断是否为图片
|
||||
func (r *Response) HeaderIsImg() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "image/jpeg" || r.ResponseHeader.Get("Content-Type") == "image/png" || r.ResponseHeader.Get("Content-Type") == "image/jpg" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HeaderIsJpeg 判断是否为jpeg图片
|
||||
func (r *Response) HeaderIsJpeg() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "image/jpeg" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HeaderIsPng 判断是否为Png图片
|
||||
func (r *Response) HeaderIsPng() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "image/png" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HeaderIsJpg 判断是否为Jpg图片
|
||||
func (r *Response) HeaderIsJpg() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "image/jpg" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HeaderJson 判断是否为Json数据
|
||||
func (r *Response) HeaderJson() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "application/json" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HeaderHtml 判断是否为Html
|
||||
func (r *Response) HeaderHtml() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "text/html" || r.ResponseHeader.Get("Content-Type") == "application/xhtml+xml" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HeaderTextHtml 判断是否为Html
|
||||
func (r *Response) HeaderTextHtml() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "text/html" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// HeaderXHtml 判断是否为Html
|
||||
func (r *Response) HeaderXHtml() bool {
|
||||
if r.ResponseHeader.Get("Content-Type") == "application/xhtml+xml" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
@ -0,0 +1,78 @@
|
||||
package gorequest
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type UriParse struct {
|
||||
uri string
|
||||
}
|
||||
|
||||
func NewUri(uri string) *UriParse {
|
||||
return &UriParse{uri: uri}
|
||||
}
|
||||
|
||||
// ResponseUrlParse 返回参数
|
||||
type ResponseUrlParse struct {
|
||||
Uri string `json:"uri"` // URI
|
||||
Urn string `json:"urn"` // URN
|
||||
Url string `json:"url"` // URL
|
||||
Scheme string `json:"scheme"` // 协议
|
||||
Host string `json:"host"` // 主机
|
||||
Hostname string `json:"hostname"` // 主机名
|
||||
Port string `json:"port"` // 端口
|
||||
Path string `json:"path"` // 路径
|
||||
RawQuery string `json:"raw_query"` // 参数 ?
|
||||
Fragment string `json:"fragment"` // 片段 #
|
||||
}
|
||||
|
||||
// Parse 解析URl
|
||||
func (u *UriParse) Parse() (resp ResponseUrlParse) {
|
||||
parse, err := url.Parse(u.uri)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resp.Uri = u.uri
|
||||
resp.Urn = parse.Host + parse.Path
|
||||
resp.Url = parse.Scheme + "://" + parse.Host + parse.Path
|
||||
resp.Scheme = parse.Scheme
|
||||
resp.Host = parse.Host
|
||||
resp.Hostname = parse.Hostname()
|
||||
resp.Port = parse.Port()
|
||||
resp.Path = parse.Path
|
||||
resp.RawQuery = parse.RawQuery
|
||||
resp.Fragment = parse.Fragment
|
||||
return
|
||||
}
|
||||
|
||||
// UriFilterExcludeQueryString 过滤掉url中的参数
|
||||
func (u *UriParse) UriFilterExcludeQueryString(uri string) string {
|
||||
URL, _ := url.Parse(uri)
|
||||
clearUri := strings.ReplaceAll(uri, URL.RawQuery, "")
|
||||
clearUri = strings.TrimRight(clearUri, "?")
|
||||
return strings.TrimRight(clearUri, "/")
|
||||
}
|
||||
|
||||
// LenCode 编码
|
||||
func LenCode(s string) string {
|
||||
escape := url.QueryEscape(s)
|
||||
return escape
|
||||
}
|
||||
|
||||
// DeCode 解码
|
||||
func DeCode(s string) string {
|
||||
unescape, _ := url.QueryUnescape(s)
|
||||
return unescape
|
||||
}
|
||||
|
||||
// ParseQuery 获取URL参数 https://studygolang.com/articles/2876
|
||||
func ParseQuery(s string) map[string][]string {
|
||||
u, err := url.Parse(s)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
urlParam := u.RawQuery
|
||||
m, _ := url.ParseQuery(urlParam)
|
||||
return m
|
||||
}
|
Loading…
Reference in new issue