Categorygithub.com/caoshuyu/kit
module
1.0.8
Repository: https://github.com/caoshuyu/kit.git
Documentation: pkg.go.dev

# README

Kit 工具包

gls

记录用户sessionId, actionId, spanID值,用于存储调用

filetools

文件操作相关方法

函数入参数返回值方法说明
CheckFileExistfilename stringbool检测文件是否存在
MakeDirdirPath stringerror递归创建文件夹
ReadFilefilename stringstring读取文件
ReadFileBytefilename string[]byte读取byte文件
WriteFilefilename string, value stringerror写文件(追加)
WriteFileCoverfilename string, value stringerror写文件(覆盖)
WriteFileBytefilename string, value []byteerror写文件,字符类型

dlog

  • 设置日志信息
	dlog.SetLog(dlog.SetLogConf{
		LogType: dlog.LOG_TYPE_LOCAL,
		LogPath: "/Users/caoshuyu/WorkSpace/GoWork/Csy/src/logs",
		Prefix:  "id_generator",
	})
参数说明可选值默认值
LogType日志存储类型LOG_TYPE_LOCAL 本地文件存储,LOG_TYPE_NET 网络存储(暂不支持)LOG_TYPE_LOCAL
LogPath日志存储位置实际存储位置/data/logs
Prefix项目名称--
  • 调用日志存储
日志级别调用方法
DEBUGdlog.DEBUG("funcName", "GetIdUseSnowflake", "info", info)
INFOdlog.INFO("funcName", "GetIdUseSnowflake", "info", info)
WARNdlog.WARN("funcName", "GetIdUseSnowflake", "warn", warn)
ERRORdlog.ERROR("funcName", "GetIdUseSnowflake", "error", err)

uuid

函数入参数返回值方法说明
NewV1-UUID基于当前时间戳和MAC地址
NewV2domain byteUUID返回基于POSIX UID/GID的DCE安全UUID
NewV3ns UUID, name stringUUID基于命名空间UUID和名称的MD5哈希
NewV4-UUID随机生成的UUID
NewV5ns UUID, name string基于命名空间UUID和名称的SHA-1散列

inttools

函数入参数返回值方法说明
Int64ArrToStringdata []int64, split stringstring数字数组转字符串;input [3306,4450,3,12],-;out 3306-4450-3-12
StringToInt64Arrdata string, split string[]int64字符串分割为数字数组;input 3306-4450-3-12,-;out [3306,4450,3,12]
GetPageNumpage int64, pageContext int64newPage int64, newPageContext int64, startLine int64通过页码和每页数量计算起始行数
Intersectarr1 []int64, arr2 []int64[]int64Intersect 取两个数组交集

stringtools

函数入参数返回值方法说明
InitialUpdateStrstringstring首字母大写,有_的去掉后第一个字母大写
InitialLowStrstringstring首字母小写,有_的去掉后第一个字母大写
UpperToUnderlineToUpperstringstring变成大写字母,用_分割
UpperToUnderlinestringstring变成小写字母,用_分割
MakeRoundaboutintstring制作问号
Md5stringstringMD5加密
Time33stringint64Time33加密算法
IsNumstringbool判断字符串是不是数字
RemoveSliceRepeatStr[]string,[]string[]string去除数组中重复的字符串

timetools

函数入参数返回值方法说明
GetConstellationmonth int64, day int64int64查询星座,具体返回值星座见文件内
GetNowDateTime-time.Time获取当前时间
GetBeforeTimebeforeSecond inttime.Time获取当前时间之前时间
GetNextTimenextSecond inttime.Time获取当前时间之后时间
TimeStamplayout string, value stringtime.Time, error时间类型转时间
GetDayStarttime.Timetime.Time获取零晨时间
GetDayEndtime.Timetime.Time获取一天最后一刻时间
SecondToDateTimeint64time.Time时间戳转时间
TimeFormatt time.Time, layout stringstring格式化时间
参数类型可选值说明
layoutstringRFC3339/TT/TTDAY/NOSPLITT时间格式
valuestring-时间值

调用方法示例

	var (
		t  time.Time
		tn int64
		ts string
	)

	//获取当前时间
	t = timetools.GetNowDateTime()
	fmt.Println("获取当前时间:", t)
	//获取当前时间戳
	tn = timetools.GetNowDateTime().Unix()
	fmt.Println("获取当前时间戳:", tn)
	//获取一小时前时间
	t = timetools.GetBeforeTime(timetools.ONE_HOURS_SECOND)
	fmt.Println("获取一小时前时间:", t)
	//获取一小时后时间
	t = timetools.GetNextTime(timetools.ONE_HOURS_SECOND)
	fmt.Println("获取一小时后时间:", t)
	//获取今天日期 2006-01-02
	ts = timetools.TimeFormat(timetools.TTDAY, timetools.GetNowDateTime())
	fmt.Println("获取今天日期 2006-01-02:", ts)
	//获取今天日期 20060102
	ts = timetools.TimeFormat(timetools.NOSPLITTDAY, timetools.GetNowDateTime())
	fmt.Println("获取今天日期 20060102:", ts)
	//2006-01-02T15:04:05Z07:00 转 时间
	t, err := timetools.TimeStamp(timetools.RFC3339, "2006-01-02T15:04:05Z07:00")
	if nil != err {
		fmt.Println(err)
		return
	}
	fmt.Println("2006-01-02T15:04:05Z07:00 转 时间:", t)

	//2006-01-02T15:04:05Z07:00 转 时间戳
	tn, err = timetools.TimeStampUnix(timetools.RFC3339, "2006-01-02T15:04:05Z07:00")
	if nil != err {
		fmt.Println(err)
		return
	}
	fmt.Println("2006-01-02T15:04:05Z07:00 转 时间戳:", tn)
	//2006-01-02 15:04:05 转 时间戳
	tn, err = timetools.TimeStampUnix(timetools.TT, "2006-01-02 15:04:05")
	if nil != err {
		fmt.Println(err)
		return
	}
	fmt.Println("2006-01-02 15:04:05 转 时间戳:", tn)

	//获取昨日零晨时间
	t = timetools.GetDayStart(timetools.GetBeforeTime(timetools.ONE_DAY_SECOND))
	fmt.Println("昨日零晨时间:", t)

	//获取昨日最后一刻时间
	t = timetools.GetDayEnd(timetools.GetBeforeTime(timetools.ONE_DAY_SECOND))
	fmt.Println("获取昨日最后一刻时间:", t)

	//时间戳转时间 1613802876
	t = timetools.SecondToDateTime(1613802876)
	fmt.Println("时间戳转时间 1613802876:", t)

	//格式化时间
	ts = timetools.TimeFormat(timetools.TT, timetools.GetNowDateTime())
	fmt.Println("格式化时间:", ts)

	_, _, _ = t, tn, ts

etcdclient

初始化客户端

	//添加一个节点
	//etcdclient.AddEndpoint("127.0.0.1:2379")
	//设置多个节点,默认值为"127.0.0.1:2379"
	etcdclient.SetEndpoints([]string{
		"127.0.0.1:2379",
	})
	//设置超时时间,秒 ,默认值为5
	etcdclient.SetTimeOutSecond(5)
	//设置etcd用户名,没有可忽略
	etcdclient.SetUsername("root")
	//设置etcd密码,没有可忽略
	etcdclient.SetPassword("root")
	//初始化客户端
	etcdclient.InitClient()

使用客户端

    //使用客户端读取数据
	etcdclient.GetValue("key")

	//使用客户端监听数据
	listeningChan := make(chan []byte, 100)
	etcdclient.WatchValue("key", listeningChan)
	select {
	case val := <-listeningChan:
		fmt.Println(val)
	}

exceltools

函数入参数返回值方法说明
SaveExcelfilename string, data []*Sheeterror存储excel
GetExcelfilename stringdata []*Sheet, err error读取excel
GetXlsfilename string, charset stringdata []*Sheet, err error读取xls

httptools

函数入参数返回值方法说明
HTTPRequest*ExternalHttpRequest*ExternalHttpResponse,error发起http请求
  • ExternalHttpRequest
type ExternalHttpRequest struct {
	Jar          *cookiejar.Jar
	Method       string
	Header       map[string]string
	TimeOut      int
	Domain       string
	Uri          string
	Body         string
	ReqUriParams string
}
+ Jar 需要多次请求使用同一个cookie的情况下使用
  • ExternalHttpResponse
type ExternalHttpResponse struct {
	StatusCode int
	Header     map[string][]string
	Body       []byte
	UseTime    int64
}
  • 使用方法
	jar, _ := cookiejar.New(nil)
	header := make(map[string]string)
	request := &httptools.ExternalHttpRequest{
		Jar:          jar,
		Method:       http.MethodPost,            //请求类型
		Header:       header,                     //请求头
		TimeOut:      6,                          //超时时间
		Domain:       "http://127.0.0.1:3000",    //请求domain
		Uri:          "/test",                    //请求uri
		Body:         "{\"body_info\":\"json\"}", //请求体
		ReqUriParams: "a=b",                      //用于在url上添加信息,http://127.0.0.1:3000/test?a=b
	}
	response, err := httptools.HTTPRequest(request)
	if nil != err {
		fmt.Println(err)
	}

redistools

函数入参数返回值方法说明
ConnRedis*RedisClienterror链接Redis
Lock*RedisClientok bool, err error加锁,outTime 加锁时长(秒),ok 成功为 true
UnLock*RedisClient,key stringerror解锁
  • 使用
	rc := redistools.RedisClient{
		Conf: &redistools.RedisConf{
			Addr: "127.0.0.1:6379",
		},
	}
	err := rc.ConnRedis()
	if nil != err {
		panic(err)
	}

    var ctx = context.Background()

	rc.Client.SetNX(ctx,"key", "value", time.Second*time.Duration(30))

	//add sync lock
	rc.Lock(ctx,"LOCK_KEY",30)
	//del sync lock
	rc.UnLock(ctx,"LOCK_KEY")

mysqltools

函数入参数返回值方法说明
Connect*MysqlClienterror链接mysql服务
CheckMonitor*MysqlClienterror检测链接有效性
  • 单数据库使用
	//get one db conf
	dbJson := "{\"db_dsn\":\"root:root@tcp(127.0.0.1:3306)/api_platform?clientFoundRows=false&parseTime=true&loc=Asia%2FShanghai&timeout=5s&collation=utf8mb4_bin&interpolateParams=true\",\"max_open\":100,\"max_idle\":100,\"db_name\":\"api_platform\"}"
	mysqlDbConf := mysqltools.MySqlConf{}
	err := json.Unmarshal([]byte(dbJson), &mysqlDbConf)
	if nil != err {
		panic(err)
	}

	var MasterDb *sql.DB

	//connect db
	mysqlClient := mysqltools.MysqlClient{
		Conf: &mysqlDbConf,
	}
	err = mysqlClient.Connect()
	if nil != err {
		panic(err)
	}
	MasterDb = mysqlClient.Client
	//check db connect
	go func(mysqlClient mysqltools.MysqlClient) {
		//5 second check once
		time.Sleep(time.Second * time.Duration(5))
		err := mysqlClient.CheckMonitor()
		if nil != err {
			//Try to reconnect
			for i := 0; i <= 3; i++ {
				err := mysqlClient.Connect()
				if nil != err {
					time.Sleep(time.Second * time.Duration(i*3+1))
				} else {
					MasterDb = mysqlClient.Client
					break
				}
			}
			err := MasterDb.Ping()
			if nil != err {
				panic(err)
			}
		}
	}(mysqlClient)
  • 一主多从数据库使用
	//get more db conf
	dbJson := "{\"master\":{\"db_dsn\":\"root:root@tcp(127.0.0.1:3306)/api_platform?clientFoundRows=false&parseTime=true&loc=Asia%2FShanghai&timeout=5s&collation=utf8mb4_bin&interpolateParams=true\",\"max_open\":100,\"max_idle\":100,\"db_name\":\"api_platform\"},\"slave\":{\"db_dsn\":\"root:root@tcp(127.0.0.1:3306)/api_platform?clientFoundRows=false&parseTime=true&loc=Asia%2FShanghai&timeout=5s&collation=utf8mb4_bin&interpolateParams=true\",\"max_open\":100,\"max_idle\":100,\"db_name\":\"api_platform\"}}"
	type DbStruct struct {
		Master mysqltools.MySqlConf `json:"master"`
		Slave  mysqltools.MySqlConf `json:"slave"`
	}

	mysqlDbConf := DbStruct{}
	err := json.Unmarshal([]byte(dbJson), &mysqlDbConf)
	if nil != err {
		panic(err)
	}

	var MasterDb *sql.DB
	var SlaveDb *sql.DB

	//connect db
	var MasterDbClient = connectDb(mysqlDbConf.Master)
	var SlaveDbClient = connectDb(mysqlDbConf.Slave)

	MasterDb = MasterDbClient.Client
	SlaveDb = SlaveDbClient.Client

	//check db

func connectDb(mysqlDbConf mysqltools.MySqlConf) (mysqlClient *mysqltools.MysqlClient) {
	mysqlClient = &mysqltools.MysqlClient{
		Conf: &mysqlDbConf,
	}
	err := mysqlClient.Connect()
	if nil != err {
		panic(err)
	}
	return mysqlClient
}

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Package uuid provides implementation of Universally Unique Identifier (UUID).