@@ -41,6 +41,6 @@ nginx.conf | |||
.devcontainer/Dockerfile | |||
.devcontainer/sources.list | |||
/t1.go | |||
/tmp/* | |||
/test/tmp/* | |||
.idea/* | |||
/.idea/modules.xml |
@@ -0,0 +1,44 @@ | |||
# 智莺生活 mysql 模型库 | |||
## 项目概述 | |||
集成智莺生活Saas项目所用到的所有数据库、表,并提供类ORM操作类。 | |||
------------- | |||
## 项目结构 | |||
如下: | |||
1. **文档** | |||
- `README.md` - 项目的入口点和概述。 | |||
- `LICENSE` - 项目的许可证。 | |||
2. **源代码** | |||
- `src` - 主代码目录。 | |||
- `dao` - dao包(接口类)。 | |||
- `models` - mysql表模型。 | |||
- `implement` - 实现包(实现所有接口)。 | |||
3. **测试用例** | |||
- `****_test.go` - 测试对应orm类功能。 | |||
- `md` - 测试用例所需结构体 | |||
- `tmp` - 运行临时日志 | |||
4. **工具类** | |||
- `logx` - 日志输出用到。 | |||
- `*****.go` - 其他常用工具函数。 | |||
5. **配置文件** | |||
- `etc` | |||
- `db_tpl` - 数据库模板文件 | |||
- `cfg.yml` - 配置文件。 | |||
6. **脚手架脚本** | |||
- `cmd_db.bat` - 作用于 windows 系统自动生成models目录下的模型 | |||
- `cmd_db.sh` - 作用于 linux 系统自动生成models目录下的模型 | |||
## 安装和运行 | |||
确保安装了所需的依赖,然后运行以下命令: | |||
```bash | |||
pip install -r requirements.txt | |||
python main.py |
@@ -0,0 +1,25 @@ | |||
@echo off | |||
set Table=* | |||
set TName="" | |||
set one=%1 | |||
if "%one%" NEQ "" ( | |||
set Table=%one% | |||
set TName="^%one%$" | |||
) | |||
set BasePath="./" | |||
set DBUSER="root" | |||
set DBPSW="Fnuo123com@" | |||
set DBNAME="fnuoos_test1" | |||
set DBHOST="119.23.182.117" | |||
set DBPORT="3306" | |||
del "app\db\model\%Table%.go" | |||
echo start reverse table %Table% | |||
xorm reverse mysql "%DBUSER%:%DBPSW%@tcp(%DBHOST%:%DBPORT%)/%DBNAME%?charset=utf8" %BasePath%/etc/db_tpl %BasePath%/src/models/ %TName% | |||
echo end |
@@ -0,0 +1,21 @@ | |||
#!/bin/bash | |||
# 使用方法, 直接执行该脚本更新所有表, cmd_db.sh 表名, 如 ./cmd_db.sh tableName | |||
Table=* | |||
TName="" | |||
if [ "$1" ] ;then | |||
Table=$1 | |||
TName="^$1$" | |||
fi | |||
BasePath="./" | |||
DBUSER="root" | |||
DBPSW="Fnuo123com@" | |||
DBNAME="fnuoos_test1" | |||
DBHOST="119.23.182.117" | |||
DBPORT="3306" | |||
rm -rf $BasePath/app/db/model/$Table.go && \ | |||
xorm reverse mysql "$DBUSER:$DBPSW@tcp($DBHOST:$DBPORT)/$DBNAME?charset=utf8" $BasePath/etc/db_tpl $BasePath/src/models/ $TName |
@@ -0,0 +1,7 @@ | |||
lang=go | |||
genJson=1 | |||
prefix=cos_ | |||
ignoreColumnsJSON= | |||
created= | |||
updated= | |||
deleted= |
@@ -0,0 +1,17 @@ | |||
package {{.Models}} | |||
{{$ilen := len .Imports}} | |||
{{if gt $ilen 0}} | |||
import ( | |||
{{range .Imports}}"{{.}}"{{end}} | |||
) | |||
{{end}} | |||
{{range .Tables}} | |||
type {{Mapper .Name}} struct { | |||
{{$table := .}} | |||
{{range .ColumnsSeq}}{{$col := $table.GetColumn .}} {{Mapper $col.Name}} {{Type $col}} {{Tag $table $col}} | |||
{{end}} | |||
} | |||
{{end}} | |||
@@ -1,5 +1,27 @@ | |||
module code.fnuoos.com/go_rely_warehouse/test.git | |||
go 1.16 | |||
go 1.19 | |||
require code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git v0.2.1 | |||
require ( | |||
github.com/gin-gonic/gin v1.9.1 | |||
go.uber.org/zap v1.13.0 | |||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 | |||
gopkg.in/yaml.v3 v3.0.1 | |||
xorm.io/xorm v1.3.1 | |||
) | |||
require ( | |||
filippo.io/edwards25519 v1.1.0 // indirect | |||
github.com/go-sql-driver/mysql v1.8.1 // indirect | |||
github.com/goccy/go-json v0.10.2 // indirect | |||
github.com/golang/snappy v0.0.4 // indirect | |||
github.com/json-iterator/go v1.1.12 // indirect | |||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect | |||
github.com/modern-go/reflect2 v1.0.2 // indirect | |||
github.com/syndtr/goleveldb v1.0.0 // indirect | |||
go.uber.org/atomic v1.6.0 // indirect | |||
go.uber.org/multierr v1.5.0 // indirect | |||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de // indirect | |||
golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 // indirect | |||
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect | |||
) |
@@ -1,18 +0,0 @@ | |||
package main | |||
import ( | |||
"code.fnuoos.com/go_rely_warehouse/zyos_go_pay.git/pay" | |||
"fmt" | |||
) | |||
func main() { | |||
err := pay.Init("119.23.182.117:3306", "zyos_website", "root", "Fnuo123com@") | |||
if err != nil { | |||
fmt.Println(">>>>>>>>>>>>>>>", err) | |||
} | |||
channel, err := pay.JudgePayChannel("35618318", "mall") | |||
if err != nil { | |||
fmt.Println("<<<<<<<<<<<<<<<<", err) | |||
} | |||
fmt.Println(channel) | |||
} |
@@ -0,0 +1,10 @@ | |||
package dao | |||
import ( | |||
"code.fnuoos.com/go_rely_warehouse/test.git/src/models" | |||
) | |||
type HappyOrchardRewardExchangeRecordsDao interface { | |||
GetHappyOrchardRewardExchangeRecords(id int) (m *models.HappyOrchardRewardExchangeRecords, err error) | |||
FindHappyOrchardRewardExchangeRecordsByUid(uid int) (mm *[]models.HappyOrchardRewardExchangeRecords, err error) | |||
} |
@@ -0,0 +1,38 @@ | |||
package implement | |||
import ( | |||
"code.fnuoos.com/go_rely_warehouse/test.git/src/dao" | |||
"code.fnuoos.com/go_rely_warehouse/test.git/src/models" | |||
"code.fnuoos.com/go_rely_warehouse/test.git/utils/logx" | |||
"xorm.io/xorm" | |||
) | |||
type happyOrchardRewardExchangeRecordsDao struct { | |||
Db *xorm.Engine | |||
} | |||
func NewHappyOrchardRewardExchangeRecordsDao(engine *xorm.Engine) dao.HappyOrchardRewardExchangeRecordsDao { | |||
return &happyOrchardRewardExchangeRecordsDao{Db: engine} | |||
} | |||
func (h happyOrchardRewardExchangeRecordsDao) GetHappyOrchardRewardExchangeRecords(id int) (m *models.HappyOrchardRewardExchangeRecords, err error) { | |||
//TODO implement me | |||
m = new(models.HappyOrchardRewardExchangeRecords) | |||
has, err := h.Db.Where("id =?", id).Get(m) | |||
if err != nil { | |||
return nil, zhios_order_relate_logx.Error(err) | |||
} | |||
if has == false { | |||
return nil, nil | |||
} | |||
return m, nil | |||
} | |||
func (h happyOrchardRewardExchangeRecordsDao) FindHappyOrchardRewardExchangeRecordsByUid(uid int) (mm *[]models.HappyOrchardRewardExchangeRecords, err error) { | |||
//TODO implement me | |||
var m []models.HappyOrchardRewardExchangeRecords | |||
if err := h.Db.Where("uid =?", uid).Desc("id").Find(&m); err != nil { | |||
return nil, zhios_order_relate_logx.Error(err) | |||
} | |||
return &m, nil | |||
} |
@@ -0,0 +1,36 @@ | |||
package models | |||
type HappyOrchardBasicSetting struct { | |||
Id int `json:"id" xorm:"not null pk autoincr INT(11)"` | |||
IsOpen int `json:"is_open" xorm:"not null default 1 comment('是否开启(1:开启 0:关闭)') TINYINT(1)"` | |||
ActivityStartTime string `json:"activity_start_time" xorm:"not null default '0000-00-00 00:00:00' comment('活动时间-开始') CHAR(50)"` | |||
ActivityEndTime string `json:"activity_end_time" xorm:"not null default '0000-00-00 00:00:00' comment('活动时间-结束') CHAR(50)"` | |||
ActivityName string `json:"activity_name" xorm:"not null default '' comment('活动名称') CHAR(50)"` | |||
IsOpenAdRotation int `json:"is_open_ad_rotation" xorm:"not null default 1 comment('是否广告轮播(1:开启 0:关闭)') TINYINT(1)"` | |||
AdRotationData int `json:"ad_rotation_data" xorm:"not null default 1 comment('广告轮播数据(1:仅读取真实数据 2:仅读取虚拟数据 3:两者都读取)') TINYINT(1)"` | |||
IsOpenSevenDaysSign int `json:"is_open_seven_days_sign" xorm:"not null default 1 comment('是否开启7日签到(1:开启 0:关闭)') TINYINT(1)"` | |||
SevenDaysSignRewardData string `json:"seven_days_sign_reward_data" xorm:"not null comment('7日签到奖励数据') TEXT"` | |||
IsOpenTimerSign int `json:"is_open_timer_sign" xorm:"not null default 1 comment('是否开启定时签到(1:开启 0:关闭)') TINYINT(1)"` | |||
TimerSignRewardData string `json:"timer_sign_reward_data" xorm:"not null comment('定时签到奖励数据') TEXT"` | |||
IsOpenPlaceOrderReward int `json:"is_open_place_order_reward" xorm:"not null default 1 comment('是否下单获得奖励(1:开启 0:关闭)') TINYINT(1)"` | |||
PlaceOrderRewardData string `json:"place_order_reward_data" xorm:"not null comment('下单获得奖励数据') TEXT"` | |||
IsOpenSharingAssistance int `json:"is_open_sharing_assistance" xorm:"not null default 1 comment('是否分享助力(1:开启 0:关闭)') TINYINT(1)"` | |||
SharingAssistanceRewardData string `json:"sharing_assistance_reward_data" xorm:"not null comment('分享助力奖励数据') TEXT"` | |||
IsOpenInvitingNewPlayers int `json:"is_open_inviting_new_players" xorm:"not null default 1 comment('是否邀请新玩家(1:开启 0:关闭)') TINYINT(1)"` | |||
InvitingNewPlayersRewardData string `json:"inviting_new_players_reward_data" xorm:"not null comment('邀请新玩家奖励数据') TEXT"` | |||
IsOpenBrowsingInterface int `json:"is_open_browsing_interface" xorm:"not null default 1 comment('是否浏览界面(1:开启 0:关闭)') TINYINT(1)"` | |||
BrowsingInterfaceRewardData string `json:"browsing_interface_reward_data" xorm:"not null comment('浏览界面奖励数据') TEXT"` | |||
IsOpenPlayGoldenEggGame int `json:"is_open_play_golden_egg_game" xorm:"not null default 1 comment('是否玩金蛋游戏(1:开启 0:关闭)') TINYINT(1)"` | |||
PlayGoldenEggGameRewardData string `json:"play_golden_egg_game_reward_data" xorm:"not null comment('玩金蛋奖励数据') TEXT"` | |||
IsOpenPlayRaffleGame int `json:"is_open_play_raffle_game" xorm:"not null default 1 comment('是否玩抽奖游戏(1:开启 0:关闭)') TINYINT(1)"` | |||
PlayRaffleGameRewardData string `json:"play_raffle_game_reward_data" xorm:"not null comment('玩抽奖游戏奖励数据') TEXT"` | |||
InitialWaterDroplet int `json:"initial_water_droplet" xorm:"not null default 0 comment('初始水滴') INT(11)"` | |||
WateringEveryTimeWaterDroplet int `json:"watering_every_time_water_droplet" xorm:"not null default 0 comment('每次浇水水滴') INT(11)"` | |||
UpgradeRewardWaterDroplet int `json:"upgrade_reward_water_droplet" xorm:"not null default 0 comment('升级奖励水滴') INT(11)"` | |||
ReplaceSeedNums int `json:"replace_seed_nums" xorm:"not null default 0 comment('更换种子次数') INT(11)"` | |||
StageNameCustom string `json:"stage_name_custom" xorm:"not null comment('阶段自定义') TEXT"` | |||
LevelRules string `json:"level_rules" xorm:"not null comment('等级规则') TEXT"` | |||
VirtualRewardIsAutoSend int `json:"virtual_reward_is_auto_send" xorm:"not null default 0 comment('虚拟奖品是否自动发放(1:是 2:否)') TINYINT(1)"` | |||
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` | |||
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' DATETIME"` | |||
} |
@@ -0,0 +1,19 @@ | |||
package models | |||
type HappyOrchardRewardExchangeRecords struct { | |||
Id int `json:"id" xorm:"not null pk autoincr comment('自增id') INT(11)"` | |||
Uid int `json:"uid" xorm:"not null default 0 comment('uid') INT(11)"` | |||
RewardId int `json:"reward_id" xorm:"not null default 0 comment('奖品id') INT(11)"` | |||
RewardName string `json:"reward_name" xorm:"default '' comment('奖品名称') VARCHAR(255)"` | |||
RewardKind int `json:"reward_kind" xorm:"not null default 1 comment('奖品类型(1:赠送商品 2:虚拟商品)') TINYINT(1)"` | |||
SeedId int `json:"seed_id" xorm:"not null default 0 comment('种子id') INT(11)"` | |||
SeedName string `json:"seed_name" xorm:"not null default '' comment('种子名称') VARCHAR(255)"` | |||
WaterNums int `json:"water_nums" xorm:"not null default 0 comment('所需水滴数') INT(11)"` | |||
State int `json:"state" xorm:"not null default 0 comment('兑换状态(1:未发放 2:已发放)') TINYINT(1)"` | |||
LogisticCompany string `json:"logistic_company" xorm:"not null default '' comment('物流公司') VARCHAR(255)"` | |||
LogisticCompanyCode string `json:"logistic_company_code" xorm:"not null default '' comment('物流公司代号') CHAR(50)"` | |||
LogisticNum string `json:"logistic_num" xorm:"default '' comment('物流单号') VARCHAR(255)"` | |||
DeliveryAt string `json:"delivery_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('发货时间') DATETIME"` | |||
CreateAt string `json:"create_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('创建时间') DATETIME"` | |||
UpdateAt string `json:"update_at" xorm:"not null default 'CURRENT_TIMESTAMP' comment('更新时间') DATETIME"` | |||
} |
@@ -0,0 +1,76 @@ | |||
package test | |||
import ( | |||
"code.fnuoos.com/go_rely_warehouse/test.git/test/md" | |||
"flag" | |||
"fmt" | |||
_ "github.com/go-sql-driver/mysql" | |||
"gopkg.in/yaml.v3" | |||
"io/ioutil" | |||
"os" | |||
"time" | |||
"xorm.io/xorm" | |||
"xorm.io/xorm/log" | |||
) | |||
var Db *xorm.Engine | |||
// 初始化配置文件,将cfg.yml读入到内存 | |||
func Init() { | |||
//用指定的名称、默认值、使用信息注册一个string类型flag。 | |||
path := flag.String("c", "../etc/cfg.yml", "config file") | |||
//解析命令行参数写入注册的flag里。 | |||
//解析之后,flag的值可以直接使用。 | |||
flag.Parse() | |||
var ( | |||
c []byte | |||
err error | |||
conf *md.Config | |||
) | |||
if c, err = ioutil.ReadFile(*path); err != nil { | |||
panic(err) | |||
} | |||
//yaml.Unmarshal反序列化映射到Config | |||
if err = yaml.Unmarshal(c, &conf); err != nil { | |||
panic(err) | |||
} | |||
//数据读入内存 | |||
err = InitDB(&conf.DB) | |||
if err != nil { | |||
panic(err.Error()) | |||
} | |||
} | |||
func InitDB(c *md.DBCfg) error { | |||
var ( | |||
err error | |||
f *os.File | |||
) | |||
//创建Orm引擎 | |||
if Db, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4", c.User, c.Psw, c.Host, c.Name)); err != nil { | |||
return err | |||
} | |||
Db.SetConnMaxLifetime(time.Duration(c.MaxLifetime) * time.Second) //设置最长连接时间 | |||
Db.SetMaxOpenConns(c.MaxOpenConns) //设置最大打开连接数 | |||
Db.SetMaxIdleConns(c.MaxIdleConns) //设置连接池的空闲数大小 | |||
if err = Db.Ping(); err != nil { //尝试ping数据库 | |||
return err | |||
} | |||
if c.ShowLog { //根据配置文件设置日志 | |||
Db.ShowSQL(true) //设置是否打印sql | |||
Db.Logger().SetLevel(0) //设置日志等级 | |||
//修改日志文件存放路径文件名是%s.log | |||
path := fmt.Sprintf(c.Path, c.Name) | |||
f, err = os.OpenFile(path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777) | |||
if err != nil { | |||
os.RemoveAll(c.Path) | |||
if f, err = os.OpenFile(c.Path, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777); err != nil { | |||
return err | |||
} | |||
} | |||
logger := log.NewSimpleLogger(f) | |||
logger.ShowSQL(true) | |||
Db.SetLogger(logger) | |||
} | |||
return nil | |||
} |
@@ -0,0 +1,18 @@ | |||
package md | |||
type Config struct { | |||
DB DBCfg `yaml:"db"` | |||
} | |||
// 数据库配置结构体 | |||
type DBCfg struct { | |||
Host string `yaml:"host"` //ip及端口 | |||
Name string `yaml:"name"` //库名 | |||
User string `yaml:"user"` //用户 | |||
Psw string `yaml:"psw"` //密码 | |||
ShowLog bool `yaml:"show_log"` //是否显示SQL语句 | |||
MaxLifetime int `yaml:"max_lifetime"` | |||
MaxOpenConns int `yaml:"max_open_conns"` | |||
MaxIdleConns int `yaml:"max_idle_conns"` | |||
Path string `yaml:"path"` //日志文件存放路径 | |||
} |
@@ -0,0 +1,18 @@ | |||
package test | |||
import ( | |||
"code.fnuoos.com/go_rely_warehouse/test.git/src/implement" | |||
"fmt" | |||
"testing" | |||
) | |||
func TestImplementServer_GetHappyOrchardRewardExchangeRecords(t *testing.T) { | |||
Init() | |||
dao := implement.NewHappyOrchardRewardExchangeRecordsDao(Db) | |||
record, err := dao.GetHappyOrchardRewardExchangeRecords(1) | |||
if err != nil { | |||
fmt.Println("error:", err.Error()) | |||
return | |||
} | |||
fmt.Printf("%+v\n", record) | |||
} |
@@ -0,0 +1,388 @@ | |||
package zhios_order_relate_utils | |||
import ( | |||
"encoding/binary" | |||
"encoding/json" | |||
"fmt" | |||
"math" | |||
"reflect" | |||
"strconv" | |||
"strings" | |||
) | |||
func ToString(raw interface{}, e error) (res string) { | |||
if e != nil { | |||
return "" | |||
} | |||
return AnyToString(raw) | |||
} | |||
func ToInt64(raw interface{}, e error) int64 { | |||
if e != nil { | |||
return 0 | |||
} | |||
return AnyToInt64(raw) | |||
} | |||
func IsNil(i interface{}) bool { | |||
vi := reflect.ValueOf(i) | |||
if vi.Kind() == reflect.Ptr { | |||
return vi.IsNil() | |||
} | |||
return false | |||
} | |||
func AnyToBool(raw interface{}) bool { | |||
switch i := raw.(type) { | |||
case float32, float64, int, int64, uint, uint8, uint16, uint32, uint64, int8, int16, int32: | |||
return i != 0 | |||
case []byte: | |||
return i != nil | |||
case string: | |||
if i == "false" { | |||
return false | |||
} | |||
return i != "" | |||
case error: | |||
return false | |||
case nil: | |||
return true | |||
} | |||
val := fmt.Sprint(raw) | |||
val = strings.TrimLeft(val, "&") | |||
if strings.TrimLeft(val, "{}") == "" { | |||
return false | |||
} | |||
if strings.TrimLeft(val, "[]") == "" { | |||
return false | |||
} | |||
// ptr type | |||
b, err := json.Marshal(raw) | |||
if err != nil { | |||
return false | |||
} | |||
if strings.TrimLeft(string(b), "\"\"") == "" { | |||
return false | |||
} | |||
if strings.TrimLeft(string(b), "{}") == "" { | |||
return false | |||
} | |||
return true | |||
} | |||
func AnyToInt64(raw interface{}) int64 { | |||
switch i := raw.(type) { | |||
case string: | |||
res, _ := strconv.ParseInt(i, 10, 64) | |||
return res | |||
case []byte: | |||
return BytesToInt64(i) | |||
case int: | |||
return int64(i) | |||
case int64: | |||
return i | |||
case uint: | |||
return int64(i) | |||
case uint8: | |||
return int64(i) | |||
case uint16: | |||
return int64(i) | |||
case uint32: | |||
return int64(i) | |||
case uint64: | |||
return int64(i) | |||
case int8: | |||
return int64(i) | |||
case int16: | |||
return int64(i) | |||
case int32: | |||
return int64(i) | |||
case float32: | |||
return int64(i) | |||
case float64: | |||
return int64(i) | |||
case error: | |||
return 0 | |||
case bool: | |||
if i { | |||
return 1 | |||
} | |||
return 0 | |||
} | |||
return 0 | |||
} | |||
func AnyToString(raw interface{}) string { | |||
switch i := raw.(type) { | |||
case []byte: | |||
return string(i) | |||
case int: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int64: | |||
return strconv.FormatInt(i, 10) | |||
case float32: | |||
return Float64ToStr(float64(i)) | |||
case float64: | |||
return Float64ToStr(i) | |||
case uint: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint8: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint16: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint32: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint64: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int8: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int16: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int32: | |||
return strconv.FormatInt(int64(i), 10) | |||
case string: | |||
return i | |||
case error: | |||
return i.Error() | |||
case bool: | |||
return strconv.FormatBool(i) | |||
} | |||
return fmt.Sprintf("%#v", raw) | |||
} | |||
func AnyToFloat64(raw interface{}) float64 { | |||
switch i := raw.(type) { | |||
case []byte: | |||
f, _ := strconv.ParseFloat(string(i), 64) | |||
return f | |||
case int: | |||
return float64(i) | |||
case int64: | |||
return float64(i) | |||
case float32: | |||
return float64(i) | |||
case float64: | |||
return i | |||
case uint: | |||
return float64(i) | |||
case uint8: | |||
return float64(i) | |||
case uint16: | |||
return float64(i) | |||
case uint32: | |||
return float64(i) | |||
case uint64: | |||
return float64(i) | |||
case int8: | |||
return float64(i) | |||
case int16: | |||
return float64(i) | |||
case int32: | |||
return float64(i) | |||
case string: | |||
f, _ := strconv.ParseFloat(i, 64) | |||
return f | |||
case bool: | |||
if i { | |||
return 1 | |||
} | |||
} | |||
return 0 | |||
} | |||
func ToByte(raw interface{}, e error) []byte { | |||
if e != nil { | |||
return []byte{} | |||
} | |||
switch i := raw.(type) { | |||
case string: | |||
return []byte(i) | |||
case int: | |||
return Int64ToBytes(int64(i)) | |||
case int64: | |||
return Int64ToBytes(i) | |||
case float32: | |||
return Float32ToByte(i) | |||
case float64: | |||
return Float64ToByte(i) | |||
case uint: | |||
return Int64ToBytes(int64(i)) | |||
case uint8: | |||
return Int64ToBytes(int64(i)) | |||
case uint16: | |||
return Int64ToBytes(int64(i)) | |||
case uint32: | |||
return Int64ToBytes(int64(i)) | |||
case uint64: | |||
return Int64ToBytes(int64(i)) | |||
case int8: | |||
return Int64ToBytes(int64(i)) | |||
case int16: | |||
return Int64ToBytes(int64(i)) | |||
case int32: | |||
return Int64ToBytes(int64(i)) | |||
case []byte: | |||
return i | |||
case error: | |||
return []byte(i.Error()) | |||
case bool: | |||
if i { | |||
return []byte("true") | |||
} | |||
return []byte("false") | |||
} | |||
return []byte(fmt.Sprintf("%#v", raw)) | |||
} | |||
func Int64ToBytes(i int64) []byte { | |||
var buf = make([]byte, 8) | |||
binary.BigEndian.PutUint64(buf, uint64(i)) | |||
return buf | |||
} | |||
func BytesToInt64(buf []byte) int64 { | |||
return int64(binary.BigEndian.Uint64(buf)) | |||
} | |||
func StrToInt(s string) int { | |||
res, _ := strconv.Atoi(s) | |||
return res | |||
} | |||
func StrToInt64(s string) int64 { | |||
res, _ := strconv.ParseInt(s, 10, 64) | |||
return res | |||
} | |||
func Float32ToByte(float float32) []byte { | |||
bits := math.Float32bits(float) | |||
bytes := make([]byte, 4) | |||
binary.LittleEndian.PutUint32(bytes, bits) | |||
return bytes | |||
} | |||
func ByteToFloat32(bytes []byte) float32 { | |||
bits := binary.LittleEndian.Uint32(bytes) | |||
return math.Float32frombits(bits) | |||
} | |||
func Float64ToByte(float float64) []byte { | |||
bits := math.Float64bits(float) | |||
bytes := make([]byte, 8) | |||
binary.LittleEndian.PutUint64(bytes, bits) | |||
return bytes | |||
} | |||
func ByteToFloat64(bytes []byte) float64 { | |||
bits := binary.LittleEndian.Uint64(bytes) | |||
return math.Float64frombits(bits) | |||
} | |||
func Float64ToStr(f float64) string { | |||
return strconv.FormatFloat(f, 'f', 2, 64) | |||
} | |||
func Float64ToStrPrec1(f float64) string { | |||
return strconv.FormatFloat(f, 'f', 1, 64) | |||
} | |||
func Float64ToStrPrec4(f float64) string { | |||
return strconv.FormatFloat(f, 'f', 4, 64) | |||
} | |||
func Float64ToStrPrec10(f float64) string { | |||
return strconv.FormatFloat(f, 'f', 10, 64) | |||
} | |||
func Float64ToStrPrec8(f float64) string { | |||
return strconv.FormatFloat(f, 'f', 8, 64) | |||
} | |||
func Float64ToStrPrec6(f float64) string { | |||
return strconv.FormatFloat(f, 'f', 6, 64) | |||
} | |||
func Float64ToStrByPrec(f float64, prec int) string { | |||
return strconv.FormatFloat(f, 'f', prec, 64) | |||
} | |||
func Float32ToStr(f float32) string { | |||
return Float64ToStr(float64(f)) | |||
} | |||
func StrToFloat64(s string) float64 { | |||
res, err := strconv.ParseFloat(s, 64) | |||
if err != nil { | |||
return 0 | |||
} | |||
return res | |||
} | |||
func StrToFormat(s string, prec int) string { | |||
ex := strings.Split(s, ".") | |||
if len(ex) == 2 { | |||
if StrToFloat64(ex[1]) == 0 { //小数点后面为空就是不要小数点了 | |||
return ex[0] | |||
} | |||
//看取多少位 | |||
str := ex[1] | |||
str1 := str | |||
if prec < len(str) { | |||
str1 = str[0:prec] | |||
} else { | |||
for i := 0; i < prec-len(str); i++ { | |||
str1 += "0" | |||
} | |||
} | |||
if prec > 0 { | |||
return ex[0] + "." + str1 | |||
} else { | |||
return ex[0] | |||
} | |||
} | |||
return s | |||
} | |||
func StrToFloat32(s string) float32 { | |||
res, err := strconv.ParseFloat(s, 32) | |||
if err != nil { | |||
return 0 | |||
} | |||
return float32(res) | |||
} | |||
func StrToBool(s string) bool { | |||
b, _ := strconv.ParseBool(s) | |||
return b | |||
} | |||
func BoolToStr(b bool) string { | |||
if b { | |||
return "true" | |||
} | |||
return "false" | |||
} | |||
func FloatToInt64(f float64) int64 { | |||
return int64(f) | |||
} | |||
func IntToStr(i int) string { | |||
return strconv.Itoa(i) | |||
} | |||
func Int64ToStr(i int64) string { | |||
return strconv.FormatInt(i, 10) | |||
} | |||
func IntToFloat64(i int) float64 { | |||
s := strconv.Itoa(i) | |||
res, err := strconv.ParseFloat(s, 64) | |||
if err != nil { | |||
return 0 | |||
} | |||
return res | |||
} | |||
func Int64ToFloat64(i int64) float64 { | |||
s := strconv.FormatInt(i, 10) | |||
res, err := strconv.ParseFloat(s, 64) | |||
if err != nil { | |||
return 0 | |||
} | |||
return res | |||
} |
@@ -0,0 +1,209 @@ | |||
package zhios_order_relate_utils | |||
import ( | |||
"bytes" | |||
"crypto/tls" | |||
"fmt" | |||
"io" | |||
"io/ioutil" | |||
"net/http" | |||
"net/url" | |||
"sort" | |||
"strings" | |||
"time" | |||
) | |||
var CurlDebug bool | |||
func CurlGet(router string, header map[string]string) ([]byte, error) { | |||
return curl(http.MethodGet, router, nil, header) | |||
} | |||
func CurlGetJson(router string, body interface{}, header map[string]string) ([]byte, error) { | |||
return curl_new(http.MethodGet, router, body, header) | |||
} | |||
// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string | |||
func CurlPost(router string, body interface{}, header map[string]string) ([]byte, error) { | |||
return curl(http.MethodPost, router, body, header) | |||
} | |||
func CurlPut(router string, body interface{}, header map[string]string) ([]byte, error) { | |||
return curl(http.MethodPut, router, body, header) | |||
} | |||
// 只支持form 与json 提交, 请留意body的类型, 支持string, []byte, map[string]string | |||
func CurlPatch(router string, body interface{}, header map[string]string) ([]byte, error) { | |||
return curl(http.MethodPatch, router, body, header) | |||
} | |||
// CurlDelete is curl delete | |||
func CurlDelete(router string, body interface{}, header map[string]string) ([]byte, error) { | |||
return curl(http.MethodDelete, router, body, header) | |||
} | |||
func curl(method, router string, body interface{}, header map[string]string) ([]byte, error) { | |||
var reqBody io.Reader | |||
contentType := "application/json" | |||
switch v := body.(type) { | |||
case string: | |||
reqBody = strings.NewReader(v) | |||
case []byte: | |||
reqBody = bytes.NewReader(v) | |||
case map[string]string: | |||
val := url.Values{} | |||
for k, v := range v { | |||
val.Set(k, v) | |||
} | |||
reqBody = strings.NewReader(val.Encode()) | |||
contentType = "application/x-www-form-urlencoded" | |||
case map[string]interface{}: | |||
val := url.Values{} | |||
for k, v := range v { | |||
val.Set(k, v.(string)) | |||
} | |||
reqBody = strings.NewReader(val.Encode()) | |||
contentType = "application/x-www-form-urlencoded" | |||
} | |||
if header == nil { | |||
header = map[string]string{"Content-Type": contentType} | |||
} | |||
if _, ok := header["Content-Type"]; !ok { | |||
header["Content-Type"] = contentType | |||
} | |||
resp, er := CurlReq(method, router, reqBody, header) | |||
if er != nil { | |||
return nil, er | |||
} | |||
res, err := ioutil.ReadAll(resp.Body) | |||
if CurlDebug { | |||
blob := SerializeStr(body) | |||
if contentType != "application/json" { | |||
blob = HttpBuild(body) | |||
} | |||
fmt.Printf("\n\n=====================\n[url]: %s\n[time]: %s\n[method]: %s\n[content-type]: %v\n[req_header]: %s\n[req_body]: %#v\n[resp_err]: %v\n[resp_header]: %v\n[resp_body]: %v\n=====================\n\n", | |||
router, | |||
time.Now().Format("2006-01-02 15:04:05.000"), | |||
method, | |||
contentType, | |||
HttpBuildQuery(header), | |||
blob, | |||
err, | |||
SerializeStr(resp.Header), | |||
string(res), | |||
) | |||
} | |||
resp.Body.Close() | |||
return res, err | |||
} | |||
func curl_new(method, router string, body interface{}, header map[string]string) ([]byte, error) { | |||
var reqBody io.Reader | |||
contentType := "application/json" | |||
if header == nil { | |||
header = map[string]string{"Content-Type": contentType} | |||
} | |||
if _, ok := header["Content-Type"]; !ok { | |||
header["Content-Type"] = contentType | |||
} | |||
resp, er := CurlReq(method, router, reqBody, header) | |||
if er != nil { | |||
return nil, er | |||
} | |||
res, err := ioutil.ReadAll(resp.Body) | |||
if CurlDebug { | |||
blob := SerializeStr(body) | |||
if contentType != "application/json" { | |||
blob = HttpBuild(body) | |||
} | |||
fmt.Printf("\n\n=====================\n[url]: %s\n[time]: %s\n[method]: %s\n[content-type]: %v\n[req_header]: %s\n[req_body]: %#v\n[resp_err]: %v\n[resp_header]: %v\n[resp_body]: %v\n=====================\n\n", | |||
router, | |||
time.Now().Format("2006-01-02 15:04:05.000"), | |||
method, | |||
contentType, | |||
HttpBuildQuery(header), | |||
blob, | |||
err, | |||
SerializeStr(resp.Header), | |||
string(res), | |||
) | |||
} | |||
resp.Body.Close() | |||
return res, err | |||
} | |||
func CurlReq(method, router string, reqBody io.Reader, header map[string]string) (*http.Response, error) { | |||
req, _ := http.NewRequest(method, router, reqBody) | |||
if header != nil { | |||
for k, v := range header { | |||
req.Header.Set(k, v) | |||
} | |||
} | |||
// 绕过github等可能因为特征码返回503问题 | |||
// https://www.imwzk.com/posts/2021-03-14-why-i-always-get-503-with-golang/ | |||
defaultCipherSuites := []uint16{0xc02f, 0xc030, 0xc02b, 0xc02c, 0xcca8, 0xcca9, 0xc013, 0xc009, | |||
0xc014, 0xc00a, 0x009c, 0x009d, 0x002f, 0x0035, 0xc012, 0x000a} | |||
client := &http.Client{ | |||
Transport: &http.Transport{ | |||
TLSClientConfig: &tls.Config{ | |||
InsecureSkipVerify: true, | |||
CipherSuites: append(defaultCipherSuites[8:], defaultCipherSuites[:8]...), | |||
}, | |||
}, | |||
// 获取301重定向 | |||
CheckRedirect: func(req *http.Request, via []*http.Request) error { | |||
return http.ErrUseLastResponse | |||
}, | |||
} | |||
return client.Do(req) | |||
} | |||
// 组建get请求参数,sortAsc true为小到大,false为大到小,nil不排序 a=123&b=321 | |||
func HttpBuildQuery(args map[string]string, sortAsc ...bool) string { | |||
str := "" | |||
if len(args) == 0 { | |||
return str | |||
} | |||
if len(sortAsc) > 0 { | |||
keys := make([]string, 0, len(args)) | |||
for k := range args { | |||
keys = append(keys, k) | |||
} | |||
if sortAsc[0] { | |||
sort.Strings(keys) | |||
} else { | |||
sort.Sort(sort.Reverse(sort.StringSlice(keys))) | |||
} | |||
for _, k := range keys { | |||
str += "&" + k + "=" + args[k] | |||
} | |||
} else { | |||
for k, v := range args { | |||
str += "&" + k + "=" + v | |||
} | |||
} | |||
return str[1:] | |||
} | |||
func HttpBuild(body interface{}, sortAsc ...bool) string { | |||
params := map[string]string{} | |||
if args, ok := body.(map[string]interface{}); ok { | |||
for k, v := range args { | |||
params[k] = AnyToString(v) | |||
} | |||
return HttpBuildQuery(params, sortAsc...) | |||
} | |||
if args, ok := body.(map[string]string); ok { | |||
for k, v := range args { | |||
params[k] = AnyToString(v) | |||
} | |||
return HttpBuildQuery(params, sortAsc...) | |||
} | |||
if args, ok := body.(map[string]int); ok { | |||
for k, v := range args { | |||
params[k] = AnyToString(v) | |||
} | |||
return HttpBuildQuery(params, sortAsc...) | |||
} | |||
return AnyToString(body) | |||
} |
@@ -0,0 +1,22 @@ | |||
package zhios_order_relate_utils | |||
import ( | |||
"os" | |||
"path" | |||
"strings" | |||
"time" | |||
) | |||
// 获取文件后缀 | |||
func FileExt(fname string) string { | |||
return strings.ToLower(strings.TrimLeft(path.Ext(fname), ".")) | |||
} | |||
func FilePutContents(fileName string, content string) { | |||
fd, _ := os.OpenFile("./tmp/"+fileName+".logs", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644) | |||
fd_time := time.Now().Format("2006-01-02 15:04:05") | |||
fd_content := strings.Join([]string{"[", fd_time, "] ", content, "\n"}, "") | |||
buf := []byte(fd_content) | |||
fd.Write(buf) | |||
fd.Close() | |||
} |
@@ -0,0 +1,59 @@ | |||
package zhios_order_relate_utils | |||
import ( | |||
"math" | |||
) | |||
func CouponFormat(data string) string { | |||
switch data { | |||
case "0.00", "0", "": | |||
return "" | |||
default: | |||
return Int64ToStr(FloatToInt64(StrToFloat64(data))) | |||
} | |||
} | |||
func CommissionFormat(data string) string { | |||
if data != "" && data != "0" { | |||
return data | |||
} | |||
return "" | |||
} | |||
func HideString(src string, hLen int) string { | |||
str := []rune(src) | |||
if hLen == 0 { | |||
hLen = 4 | |||
} | |||
hideStr := "" | |||
for i := 0; i < hLen; i++ { | |||
hideStr += "*" | |||
} | |||
hideLen := len(str) / 2 | |||
showLen := len(str) - hideLen | |||
if hideLen == 0 || showLen == 0 { | |||
return hideStr | |||
} | |||
subLen := showLen / 2 | |||
if subLen == 0 { | |||
return string(str[:showLen]) + hideStr | |||
} | |||
s := string(str[:subLen]) | |||
s += hideStr | |||
s += string(str[len(str)-subLen:]) | |||
return s | |||
} | |||
//SaleCountFormat is 格式化销量 | |||
func SaleCountFormat(s string) string { | |||
return s + "已售" | |||
} | |||
// 小数格式化 | |||
func FloatFormat(f float64, i int) float64 { | |||
if i > 14 { | |||
return f | |||
} | |||
p := math.Pow10(i) | |||
return float64(int64((f+0.000000000000009)*p)) / p | |||
} |
@@ -0,0 +1,245 @@ | |||
package zhios_order_relate_logx | |||
import ( | |||
"os" | |||
"strings" | |||
"time" | |||
"go.uber.org/zap" | |||
"go.uber.org/zap/zapcore" | |||
) | |||
type LogConfig struct { | |||
AppName string `yaml:"app_name" json:"app_name" toml:"app_name"` | |||
Level string `yaml:"level" json:"level" toml:"level"` | |||
StacktraceLevel string `yaml:"stacktrace_level" json:"stacktrace_level" toml:"stacktrace_level"` | |||
IsStdOut bool `yaml:"is_stdout" json:"is_stdout" toml:"is_stdout"` | |||
TimeFormat string `yaml:"time_format" json:"time_format" toml:"time_format"` // second, milli, nano, standard, iso, | |||
Encoding string `yaml:"encoding" json:"encoding" toml:"encoding"` // console, json | |||
Skip int `yaml:"skip" json:"skip" toml:"skip"` | |||
IsFileOut bool `yaml:"is_file_out" json:"is_file_out" toml:"is_file_out"` | |||
FileDir string `yaml:"file_dir" json:"file_dir" toml:"file_dir"` | |||
FileName string `yaml:"file_name" json:"file_name" toml:"file_name"` | |||
FileMaxSize int `yaml:"file_max_size" json:"file_max_size" toml:"file_max_size"` | |||
FileMaxAge int `yaml:"file_max_age" json:"file_max_age" toml:"file_max_age"` | |||
} | |||
var ( | |||
l *LogX = defaultLogger() | |||
conf *LogConfig | |||
) | |||
// default logger setting | |||
func defaultLogger() *LogX { | |||
conf = &LogConfig{ | |||
Level: "debug", | |||
StacktraceLevel: "error", | |||
IsStdOut: true, | |||
TimeFormat: "standard", | |||
Encoding: "console", | |||
Skip: 2, | |||
} | |||
writers := []zapcore.WriteSyncer{os.Stdout} | |||
lg, lv := newZapLogger(setLogLevel(conf.Level), setLogLevel(conf.StacktraceLevel), conf.Encoding, conf.TimeFormat, conf.Skip, zapcore.NewMultiWriteSyncer(writers...)) | |||
zap.RedirectStdLog(lg) | |||
return &LogX{logger: lg, atomLevel: lv} | |||
} | |||
// initial standard log, if you don't init, it will use default logger setting | |||
func InitDefaultLogger(cfg *LogConfig) { | |||
var writers []zapcore.WriteSyncer | |||
if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { | |||
writers = append(writers, os.Stdout) | |||
} | |||
if cfg.IsFileOut { | |||
writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) | |||
} | |||
lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) | |||
zap.RedirectStdLog(lg) | |||
if cfg.AppName != "" { | |||
lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 | |||
} | |||
l = &LogX{logger: lg, atomLevel: lv} | |||
} | |||
// create a new logger | |||
func NewLogger(cfg *LogConfig) *LogX { | |||
var writers []zapcore.WriteSyncer | |||
if cfg.IsStdOut || (!cfg.IsStdOut && !cfg.IsFileOut) { | |||
writers = append(writers, os.Stdout) | |||
} | |||
if cfg.IsFileOut { | |||
writers = append(writers, NewRollingFile(cfg.FileDir, cfg.FileName, cfg.FileMaxSize, cfg.FileMaxAge)) | |||
} | |||
lg, lv := newZapLogger(setLogLevel(cfg.Level), setLogLevel(cfg.StacktraceLevel), cfg.Encoding, cfg.TimeFormat, cfg.Skip, zapcore.NewMultiWriteSyncer(writers...)) | |||
zap.RedirectStdLog(lg) | |||
if cfg.AppName != "" { | |||
lg = lg.With(zap.String("app", cfg.AppName)) // 加上应用名称 | |||
} | |||
return &LogX{logger: lg, atomLevel: lv} | |||
} | |||
// create a new zaplog logger | |||
func newZapLogger(level, stacktrace zapcore.Level, encoding, timeType string, skip int, output zapcore.WriteSyncer) (*zap.Logger, *zap.AtomicLevel) { | |||
encCfg := zapcore.EncoderConfig{ | |||
TimeKey: "T", | |||
LevelKey: "L", | |||
NameKey: "N", | |||
CallerKey: "C", | |||
MessageKey: "M", | |||
StacktraceKey: "S", | |||
LineEnding: zapcore.DefaultLineEnding, | |||
EncodeCaller: zapcore.ShortCallerEncoder, | |||
EncodeDuration: zapcore.NanosDurationEncoder, | |||
EncodeLevel: zapcore.LowercaseLevelEncoder, | |||
} | |||
setTimeFormat(timeType, &encCfg) // set time type | |||
atmLvl := zap.NewAtomicLevel() // set level | |||
atmLvl.SetLevel(level) | |||
encoder := zapcore.NewJSONEncoder(encCfg) // 确定encoder格式 | |||
if encoding == "console" { | |||
encoder = zapcore.NewConsoleEncoder(encCfg) | |||
} | |||
return zap.New(zapcore.NewCore(encoder, output, atmLvl), zap.AddCaller(), zap.AddStacktrace(stacktrace), zap.AddCallerSkip(skip)), &atmLvl | |||
} | |||
// set log level | |||
func setLogLevel(lvl string) zapcore.Level { | |||
switch strings.ToLower(lvl) { | |||
case "panic": | |||
return zapcore.PanicLevel | |||
case "fatal": | |||
return zapcore.FatalLevel | |||
case "error": | |||
return zapcore.ErrorLevel | |||
case "warn", "warning": | |||
return zapcore.WarnLevel | |||
case "info": | |||
return zapcore.InfoLevel | |||
default: | |||
return zapcore.DebugLevel | |||
} | |||
} | |||
// set time format | |||
func setTimeFormat(timeType string, z *zapcore.EncoderConfig) { | |||
switch strings.ToLower(timeType) { | |||
case "iso": // iso8601 standard | |||
z.EncodeTime = zapcore.ISO8601TimeEncoder | |||
case "sec": // only for unix second, without millisecond | |||
z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { | |||
enc.AppendInt64(t.Unix()) | |||
} | |||
case "second": // unix second, with millisecond | |||
z.EncodeTime = zapcore.EpochTimeEncoder | |||
case "milli", "millisecond": // millisecond | |||
z.EncodeTime = zapcore.EpochMillisTimeEncoder | |||
case "nano", "nanosecond": // nanosecond | |||
z.EncodeTime = zapcore.EpochNanosTimeEncoder | |||
default: // standard format | |||
z.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) { | |||
enc.AppendString(t.Format("2006-01-02 15:04:05.000")) | |||
} | |||
} | |||
} | |||
func GetLevel() string { | |||
switch l.atomLevel.Level() { | |||
case zapcore.PanicLevel: | |||
return "panic" | |||
case zapcore.FatalLevel: | |||
return "fatal" | |||
case zapcore.ErrorLevel: | |||
return "error" | |||
case zapcore.WarnLevel: | |||
return "warn" | |||
case zapcore.InfoLevel: | |||
return "info" | |||
default: | |||
return "debug" | |||
} | |||
} | |||
func SetLevel(lvl string) { | |||
l.atomLevel.SetLevel(setLogLevel(lvl)) | |||
} | |||
// temporary add call skip | |||
func AddCallerSkip(skip int) *LogX { | |||
l.logger.WithOptions(zap.AddCallerSkip(skip)) | |||
return l | |||
} | |||
// permanent add call skip | |||
func AddDepth(skip int) *LogX { | |||
l.logger = l.logger.WithOptions(zap.AddCallerSkip(skip)) | |||
return l | |||
} | |||
// permanent add options | |||
func AddOptions(opts ...zap.Option) *LogX { | |||
l.logger = l.logger.WithOptions(opts...) | |||
return l | |||
} | |||
func AddField(k string, v interface{}) { | |||
l.logger.With(zap.Any(k, v)) | |||
} | |||
func AddFields(fields map[string]interface{}) *LogX { | |||
for k, v := range fields { | |||
l.logger.With(zap.Any(k, v)) | |||
} | |||
return l | |||
} | |||
// Normal log | |||
func Debug(e interface{}, args ...interface{}) error { | |||
return l.Debug(e, args...) | |||
} | |||
func Info(e interface{}, args ...interface{}) error { | |||
return l.Info(e, args...) | |||
} | |||
func Warn(e interface{}, args ...interface{}) error { | |||
return l.Warn(e, args...) | |||
} | |||
func Error(e interface{}, args ...interface{}) error { | |||
return l.Error(e, args...) | |||
} | |||
func Panic(e interface{}, args ...interface{}) error { | |||
return l.Panic(e, args...) | |||
} | |||
func Fatal(e interface{}, args ...interface{}) error { | |||
return l.Fatal(e, args...) | |||
} | |||
// Format logs | |||
func Debugf(format string, args ...interface{}) error { | |||
return l.Debugf(format, args...) | |||
} | |||
func Infof(format string, args ...interface{}) error { | |||
return l.Infof(format, args...) | |||
} | |||
func Warnf(format string, args ...interface{}) error { | |||
return l.Warnf(format, args...) | |||
} | |||
func Errorf(format string, args ...interface{}) error { | |||
return l.Errorf(format, args...) | |||
} | |||
func Panicf(format string, args ...interface{}) error { | |||
return l.Panicf(format, args...) | |||
} | |||
func Fatalf(format string, args ...interface{}) error { | |||
return l.Fatalf(format, args...) | |||
} | |||
func formatFieldMap(m FieldMap) []Field { | |||
var res []Field | |||
for k, v := range m { | |||
res = append(res, zap.Any(k, v)) | |||
} | |||
return res | |||
} |
@@ -0,0 +1,105 @@ | |||
package zhios_order_relate_logx | |||
import ( | |||
"bytes" | |||
"io" | |||
"os" | |||
"path/filepath" | |||
"time" | |||
"gopkg.in/natefinch/lumberjack.v2" | |||
) | |||
// output interface | |||
type WriteSyncer interface { | |||
io.Writer | |||
Sync() error | |||
} | |||
// split writer | |||
func NewRollingFile(dir, filename string, maxSize, MaxAge int) WriteSyncer { | |||
s, err := os.Stat(dir) | |||
if err != nil || !s.IsDir() { | |||
os.RemoveAll(dir) | |||
if err := os.MkdirAll(dir, 0766); err != nil { | |||
panic(err) | |||
} | |||
} | |||
return newLumberjackWriteSyncer(&lumberjack.Logger{ | |||
Filename: filepath.Join(dir, filename), | |||
MaxSize: maxSize, // megabytes, MB | |||
MaxAge: MaxAge, // days | |||
LocalTime: true, | |||
Compress: false, | |||
}) | |||
} | |||
type lumberjackWriteSyncer struct { | |||
*lumberjack.Logger | |||
buf *bytes.Buffer | |||
logChan chan []byte | |||
closeChan chan interface{} | |||
maxSize int | |||
} | |||
func newLumberjackWriteSyncer(l *lumberjack.Logger) *lumberjackWriteSyncer { | |||
ws := &lumberjackWriteSyncer{ | |||
Logger: l, | |||
buf: bytes.NewBuffer([]byte{}), | |||
logChan: make(chan []byte, 5000), | |||
closeChan: make(chan interface{}), | |||
maxSize: 1024, | |||
} | |||
go ws.run() | |||
return ws | |||
} | |||
func (l *lumberjackWriteSyncer) run() { | |||
ticker := time.NewTicker(1 * time.Second) | |||
for { | |||
select { | |||
case <-ticker.C: | |||
if l.buf.Len() > 0 { | |||
l.sync() | |||
} | |||
case bs := <-l.logChan: | |||
_, err := l.buf.Write(bs) | |||
if err != nil { | |||
continue | |||
} | |||
if l.buf.Len() > l.maxSize { | |||
l.sync() | |||
} | |||
case <-l.closeChan: | |||
l.sync() | |||
return | |||
} | |||
} | |||
} | |||
func (l *lumberjackWriteSyncer) Stop() { | |||
close(l.closeChan) | |||
} | |||
func (l *lumberjackWriteSyncer) Write(bs []byte) (int, error) { | |||
b := make([]byte, len(bs)) | |||
for i, c := range bs { | |||
b[i] = c | |||
} | |||
l.logChan <- b | |||
return 0, nil | |||
} | |||
func (l *lumberjackWriteSyncer) Sync() error { | |||
return nil | |||
} | |||
func (l *lumberjackWriteSyncer) sync() error { | |||
defer l.buf.Reset() | |||
_, err := l.Logger.Write(l.buf.Bytes()) | |||
if err != nil { | |||
return err | |||
} | |||
return nil | |||
} |
@@ -0,0 +1,192 @@ | |||
package zhios_order_relate_logx | |||
import ( | |||
"errors" | |||
"fmt" | |||
"strconv" | |||
"go.uber.org/zap" | |||
) | |||
type LogX struct { | |||
logger *zap.Logger | |||
atomLevel *zap.AtomicLevel | |||
} | |||
type Field = zap.Field | |||
type FieldMap map[string]interface{} | |||
// 判断其他类型--start | |||
func getFields(msg string, format bool, args ...interface{}) (string, []Field) { | |||
var str []interface{} | |||
var fields []zap.Field | |||
if len(args) > 0 { | |||
for _, v := range args { | |||
if f, ok := v.(Field); ok { | |||
fields = append(fields, f) | |||
} else if f, ok := v.(FieldMap); ok { | |||
fields = append(fields, formatFieldMap(f)...) | |||
} else { | |||
str = append(str, AnyToString(v)) | |||
} | |||
} | |||
if format { | |||
return fmt.Sprintf(msg, str...), fields | |||
} | |||
str = append([]interface{}{msg}, str...) | |||
return fmt.Sprintln(str...), fields | |||
} | |||
return msg, []Field{} | |||
} | |||
func (l *LogX) Debug(s interface{}, args ...interface{}) error { | |||
es, e := checkErr(s) | |||
if es != "" { | |||
msg, field := getFields(es, false, args...) | |||
l.logger.Debug(msg, field...) | |||
} | |||
return e | |||
} | |||
func (l *LogX) Info(s interface{}, args ...interface{}) error { | |||
es, e := checkErr(s) | |||
if es != "" { | |||
msg, field := getFields(es, false, args...) | |||
l.logger.Info(msg, field...) | |||
} | |||
return e | |||
} | |||
func (l *LogX) Warn(s interface{}, args ...interface{}) error { | |||
es, e := checkErr(s) | |||
if es != "" { | |||
msg, field := getFields(es, false, args...) | |||
l.logger.Warn(msg, field...) | |||
} | |||
return e | |||
} | |||
func (l *LogX) Error(s interface{}, args ...interface{}) error { | |||
es, e := checkErr(s) | |||
if es != "" { | |||
msg, field := getFields(es, false, args...) | |||
l.logger.Error(msg, field...) | |||
} | |||
return e | |||
} | |||
func (l *LogX) DPanic(s interface{}, args ...interface{}) error { | |||
es, e := checkErr(s) | |||
if es != "" { | |||
msg, field := getFields(es, false, args...) | |||
l.logger.DPanic(msg, field...) | |||
} | |||
return e | |||
} | |||
func (l *LogX) Panic(s interface{}, args ...interface{}) error { | |||
es, e := checkErr(s) | |||
if es != "" { | |||
msg, field := getFields(es, false, args...) | |||
l.logger.Panic(msg, field...) | |||
} | |||
return e | |||
} | |||
func (l *LogX) Fatal(s interface{}, args ...interface{}) error { | |||
es, e := checkErr(s) | |||
if es != "" { | |||
msg, field := getFields(es, false, args...) | |||
l.logger.Fatal(msg, field...) | |||
} | |||
return e | |||
} | |||
func checkErr(s interface{}) (string, error) { | |||
switch e := s.(type) { | |||
case error: | |||
return e.Error(), e | |||
case string: | |||
return e, errors.New(e) | |||
case []byte: | |||
return string(e), nil | |||
default: | |||
return "", nil | |||
} | |||
} | |||
func (l *LogX) LogError(err error) error { | |||
return l.Error(err.Error()) | |||
} | |||
func (l *LogX) Debugf(msg string, args ...interface{}) error { | |||
s, f := getFields(msg, true, args...) | |||
l.logger.Debug(s, f...) | |||
return errors.New(s) | |||
} | |||
func (l *LogX) Infof(msg string, args ...interface{}) error { | |||
s, f := getFields(msg, true, args...) | |||
l.logger.Info(s, f...) | |||
return errors.New(s) | |||
} | |||
func (l *LogX) Warnf(msg string, args ...interface{}) error { | |||
s, f := getFields(msg, true, args...) | |||
l.logger.Warn(s, f...) | |||
return errors.New(s) | |||
} | |||
func (l *LogX) Errorf(msg string, args ...interface{}) error { | |||
s, f := getFields(msg, true, args...) | |||
l.logger.Error(s, f...) | |||
return errors.New(s) | |||
} | |||
func (l *LogX) DPanicf(msg string, args ...interface{}) error { | |||
s, f := getFields(msg, true, args...) | |||
l.logger.DPanic(s, f...) | |||
return errors.New(s) | |||
} | |||
func (l *LogX) Panicf(msg string, args ...interface{}) error { | |||
s, f := getFields(msg, true, args...) | |||
l.logger.Panic(s, f...) | |||
return errors.New(s) | |||
} | |||
func (l *LogX) Fatalf(msg string, args ...interface{}) error { | |||
s, f := getFields(msg, true, args...) | |||
l.logger.Fatal(s, f...) | |||
return errors.New(s) | |||
} | |||
func AnyToString(raw interface{}) string { | |||
switch i := raw.(type) { | |||
case []byte: | |||
return string(i) | |||
case int: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int64: | |||
return strconv.FormatInt(i, 10) | |||
case float32: | |||
return strconv.FormatFloat(float64(i), 'f', 2, 64) | |||
case float64: | |||
return strconv.FormatFloat(i, 'f', 2, 64) | |||
case uint: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint8: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint16: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint32: | |||
return strconv.FormatInt(int64(i), 10) | |||
case uint64: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int8: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int16: | |||
return strconv.FormatInt(int64(i), 10) | |||
case int32: | |||
return strconv.FormatInt(int64(i), 10) | |||
case string: | |||
return i | |||
case error: | |||
return i.Error() | |||
} | |||
return fmt.Sprintf("%#v", raw) | |||
} |
@@ -0,0 +1,23 @@ | |||
package zhios_order_relate_utils | |||
import ( | |||
"encoding/json" | |||
) | |||
func Serialize(data interface{}) []byte { | |||
res, err := json.Marshal(data) | |||
if err != nil { | |||
return []byte{} | |||
} | |||
return res | |||
} | |||
func Unserialize(b []byte, dst interface{}) { | |||
if err := json.Unmarshal(b, dst); err != nil { | |||
dst = nil | |||
} | |||
} | |||
func SerializeStr(data interface{}, arg ...interface{}) string { | |||
return string(Serialize(data)) | |||
} |
@@ -0,0 +1,203 @@ | |||
package zhios_order_relate_utils | |||
import ( | |||
"fmt" | |||
"github.com/syyongx/php2go" | |||
"math/rand" | |||
"reflect" | |||
"sort" | |||
"strings" | |||
"time" | |||
) | |||
func Implode(glue string, args ...interface{}) string { | |||
data := make([]string, len(args)) | |||
for i, s := range args { | |||
data[i] = fmt.Sprint(s) | |||
} | |||
return strings.Join(data, glue) | |||
} | |||
//字符串是否在数组里 | |||
func InArr(target string, str_array []string) bool { | |||
for _, element := range str_array { | |||
if target == element { | |||
return true | |||
} | |||
} | |||
return false | |||
} | |||
func InArrToInt(target int, str_array []int) bool { | |||
for _, element := range str_array { | |||
if target == element { | |||
return true | |||
} | |||
} | |||
return false | |||
} | |||
//把数组的值放到key里 | |||
func ArrayColumn(array interface{}, key string) (result map[string]interface{}, err error) { | |||
result = make(map[string]interface{}) | |||
t := reflect.TypeOf(array) | |||
v := reflect.ValueOf(array) | |||
if t.Kind() != reflect.Slice { | |||
return nil, nil | |||
} | |||
if v.Len() == 0 { | |||
return nil, nil | |||
} | |||
for i := 0; i < v.Len(); i++ { | |||
indexv := v.Index(i) | |||
if indexv.Type().Kind() != reflect.Struct { | |||
return nil, nil | |||
} | |||
mapKeyInterface := indexv.FieldByName(key) | |||
if mapKeyInterface.Kind() == reflect.Invalid { | |||
return nil, nil | |||
} | |||
mapKeyString, err := InterfaceToString(mapKeyInterface.Interface()) | |||
if err != nil { | |||
return nil, err | |||
} | |||
result[mapKeyString] = indexv.Interface() | |||
} | |||
return result, err | |||
} | |||
//转string | |||
func InterfaceToString(v interface{}) (result string, err error) { | |||
switch reflect.TypeOf(v).Kind() { | |||
case reflect.Int64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32: | |||
result = fmt.Sprintf("%v", v) | |||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: | |||
result = fmt.Sprintf("%v", v) | |||
case reflect.String: | |||
result = v.(string) | |||
default: | |||
err = nil | |||
} | |||
return result, err | |||
} | |||
func HideTrueName(name string) string { | |||
res := "**" | |||
if name != "" { | |||
runs := []rune(name) | |||
leng := len(runs) | |||
if leng <= 3 { | |||
res = string(runs[0:1]) + res | |||
} else if leng < 5 { | |||
res = string(runs[0:2]) + res | |||
} else if leng < 10 { | |||
res = string(runs[0:2]) + "***" + string(runs[leng-2:leng]) | |||
} else if leng < 16 { | |||
res = string(runs[0:3]) + "****" + string(runs[leng-3:leng]) | |||
} else { | |||
res = string(runs[0:4]) + "*****" + string(runs[leng-4:leng]) | |||
} | |||
} | |||
return res | |||
} | |||
func GetQueryParam(uri string) map[string]string { | |||
//根据问号分割路由还是query参数 | |||
uriList := strings.Split(uri, "?") | |||
var query = make(map[string]string, 0) | |||
//有参数才处理 | |||
if len(uriList) == 2 { | |||
//分割query参数 | |||
var queryList = strings.Split(uriList[1], "&") | |||
if len(queryList) > 0 { | |||
//key value 分别赋值 | |||
for _, v := range queryList { | |||
var valueList = strings.Split(v, "=") | |||
if len(valueList) == 2 { | |||
value, _ := php2go.URLDecode(valueList[1]) | |||
if value == "" { | |||
value = valueList[1] | |||
} | |||
query[valueList[0]] = value | |||
} | |||
} | |||
} | |||
} | |||
return query | |||
} | |||
//JoinStringsInASCII 按照规则,参数名ASCII码从小到大排序后拼接 | |||
//data 待拼接的数据 | |||
//sep 连接符 | |||
//onlyValues 是否只包含参数值,true则不包含参数名,否则参数名和参数值均有 | |||
//includeEmpty 是否包含空值,true则包含空值,否则不包含,注意此参数不影响参数名的存在 | |||
//exceptKeys 被排除的参数名,不参与排序及拼接 | |||
func JoinStringsInASCII(data map[string]string, sep string, onlyValues, includeEmpty bool, exceptKeys ...string) string { | |||
var list []string | |||
var keyList []string | |||
m := make(map[string]int) | |||
if len(exceptKeys) > 0 { | |||
for _, except := range exceptKeys { | |||
m[except] = 1 | |||
} | |||
} | |||
for k := range data { | |||
if _, ok := m[k]; ok { | |||
continue | |||
} | |||
value := data[k] | |||
if !includeEmpty && value == "" { | |||
continue | |||
} | |||
if onlyValues { | |||
keyList = append(keyList, k) | |||
} else { | |||
list = append(list, fmt.Sprintf("%s=%s", k, value)) | |||
} | |||
} | |||
if onlyValues { | |||
sort.Strings(keyList) | |||
for _, v := range keyList { | |||
list = append(list, AnyToString(data[v])) | |||
} | |||
} else { | |||
sort.Strings(list) | |||
} | |||
return strings.Join(list, sep) | |||
} | |||
//x的y次方 | |||
func RandPow(l int) string { | |||
var i = "1" | |||
for j := 0; j < l; j++ { | |||
i += "0" | |||
} | |||
k := StrToInt64(i) | |||
n := rand.New(rand.NewSource(time.Now().UnixNano())).Int63n(k) | |||
ls := "%0" + IntToStr(l) + "v" | |||
str := fmt.Sprintf(ls, n) | |||
//min := int(math.Pow10(l - 1)) | |||
//max := int(math.Pow10(l) - 1) | |||
return str | |||
} | |||
//根据显示长度截取字符串 | |||
func ShowSubstr(s string, l int) string { | |||
if len(s) <= l { | |||
return s | |||
} | |||
ss, sl, rl, rs := "", 0, 0, []rune(s) | |||
for _, r := range rs { | |||
rint := int(r) | |||
if rint < 128 { | |||
rl = 1 | |||
} else { | |||
rl = 2 | |||
} | |||
if sl+rl > l { | |||
break | |||
} | |||
sl += rl | |||
ss += string(r) | |||
} | |||
return ss | |||
} |
@@ -0,0 +1,29 @@ | |||
package zhios_order_relate_utils | |||
import "time" | |||
func Time2String(date time.Time, format string) string { | |||
if format == "" { | |||
format = "2006-01-02 15:04:05" | |||
} | |||
timeS := date.Format(format) | |||
if timeS == "0001-01-01 00:00:00" { | |||
return "" | |||
} | |||
return timeS | |||
} | |||
func String2Time(timeStr string) time.Time { | |||
toTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local) | |||
if err != nil { | |||
return time.Now() | |||
} | |||
return toTime | |||
} | |||
//GetDiffDays 获取两个时间相差的天数,0表同一天,正数表t1>t2,负数表t1<t2 | |||
func GetDiffDays(t1, t2 time.Time) int { | |||
t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local) | |||
t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local) | |||
return int(t1.Sub(t2).Hours() / 24) | |||
} |