toolbox

package module
v0.0.0-...-d3fa53b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2026 License: GPL-3.0 Imports: 32 Imported by: 4 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

golang toolbox

Some useful golang function module codes written by myself, I hope they are also useful to you.

useage: go get -u github.com/xyzj/toolbox

Documentation

Overview

Package toolbox : 收集,保存的一些常用方法

Index

Constants

View Source
const (
	// OSNAME from runtime
	OSNAME = runtime.GOOS
	// OSARCH from runtime
	OSARCH = runtime.GOARCH
	// DateTimeFormat yyyy-mm-dd hh:MM:ss
	DateTimeFormat = "2006-01-02 15:04:05"
	// DateOnlyFormat yyyy-mm-dd
	DateOnlyFormat = "2006-01-02"
	// TimeOnlyFormat hh:MM:ss
	TimeOnlyFormat = "15:04:05"
	// LongTimeFormat 含日期的日志内容时间戳格式 2006-01-02 15:04:05.000
	LongTimeFormat = "2006-01-02 15:04:05.000"
	// ShortTimeFormat 无日期的日志内容时间戳格式 15:04:05.000
	ShortTimeFormat = "15:04:05.000"
	// FileTimeFormat 日志文件命名格式 060102
	FileTimeFormat = "060102" // 日志文件命名格式
)

Variables

View Source
var (
	TimeUnitsZh = timeUnits{
		Day:               "天",
		Hour:              "小时",
		Minute:            "分钟",
		Second:            "秒",
		LessThanOneMinute: "不到1分钟",
	}
	TimeUnitsEn = timeUnits{
		Day:               " day",
		Hour:              " hour",
		Minute:            " minute",
		Second:            " second",
		LessThanOneMinute: "less than 1 minute",
	}
)
View Source
var (
	// DefaultLogDir 默认日志文件夹
	DefaultLogDir = filepath.Join(pathtool.GetExecDir(), "..", "log")
	// DefaultCacheDir 默认缓存文件夹
	DefaultCacheDir = filepath.Join(pathtool.GetExecDir(), "..", "cache")
	// DefaultConfDir 默认配置文件夹
	DefaultConfDir = filepath.Join(pathtool.GetExecDir(), "..", "conf")
)

Functions

func Base64Decode

func Base64Decode(data string) ([]byte, error)

Base64Decode decodes a base64 encoded string into a byte slice.

The function takes a single parameter: - data: A string representing the base64 encoded data.

The function returns two values: - []byte: A byte slice containing the decoded data. - error: An error if the decoding process fails. If the decoding is successful, the error will be nil.

func Base64Imgfile

func Base64Imgfile(b, f string) error

Base64Imgfile base64码保存为图片

func Base64URLDecode

func Base64URLDecode(data string) ([]byte, error)

Base64URLDecode url解码

func Bcd2Int8

func Bcd2Int8(v byte) byte

Bcd2Int8 bcd to int

func Bcd2STime

func Bcd2STime(b []byte) int32

Bcd2STime bcd转hh*60+mm

func BcdBytes2Float64

func BcdBytes2Float64(b []byte, decimal int, unsigned bool) float64

BcdBytes2Float64 bcd数组转浮点(小端序)

b:bcd数组
d:小数位数
Unsigned:无符号的

func BcdBytes2Float64BigOrder

func BcdBytes2Float64BigOrder(b []byte, decimal int, unsigned bool) float64

BcdBytes2Float64BigOrder bcd数组转浮点(大端序)

b:bcd数组
d:小数位数
Unsigned:无符号的

func BcdDT2Stamp

func BcdDT2Stamp(d []byte) int64

BcdDT2Stamp bcd时间戳转unix

func Byte2Bytes

func Byte2Bytes(v byte, reverse bool) []byte

Byte2Bytes int8 to bytes

func Byte2Int8

func Byte2Int8(b byte) int8

Byte2Int8 byte转有符号整型

func Byte2Int32s

func Byte2Int32s(v byte, reverse bool) []int32

Byte2Int32s int8 to int32 list

func Byte2SignedInt32 deprecated

func Byte2SignedInt32(b byte) int32

Byte2SignedInt32 byte转有符号整型

Deprecated: use Byte2Int8()

func Bytes deprecated

func Bytes(s string) []byte

Bytes use unsafe package conver string to []byte

Deprecated: use json.String

func Bytes2Float32

func Bytes2Float32(b []byte, bigOrder bool) float32

Bytes2Float32 字节数组转单精度浮点,bigOrder==true,高位在前

func Bytes2Float64

func Bytes2Float64(b []byte, bigOrder bool) float64

Bytes2Float64 字节数组转双精度浮点,bigOrder==true,高位在前

func Bytes2Int64

func Bytes2Int64(b []byte, bigorder bool) int64

Bytes2Int64 字节数组转换为int64

b-字节数组
bigorder-是否高位在前
false低位在前

func Bytes2String

func Bytes2String(data []byte, sep string) string

Bytes2String convert []byte to hex-string

 args:
	data: 输入字节切片
	sep: 用于分割字符串的分割字符
 return:
	字符串

func Bytes2Uint64

func Bytes2Uint64(b []byte, bigorder bool) uint64

Bytes2Uint64 字节数组转换为uint64

b-字节数组
bigorder-是否高位在前
false低位在前

func CalcCRC32

func CalcCRC32(b []byte, bigorder bool) []byte

CalcCRC32 计算crc32,返回[]byte

func CalcCRC32String

func CalcCRC32String(b []byte) string

CalcCRC32String 计算crc32,返回16进制字符串

func CalculateSecurityCode

func CalculateSecurityCode(t, salt string, offset int) []string

CalculateSecurityCode calculate security code

 args:
	t: calculate type "h"-按小时计算,当分钟数在偏移值范围内时,同时计算前后一小时的值,"m"-按分钟计算,同时计算前后偏移量范围内的值
	salt: 拼接用字符串
	offset: 偏移值,范围0~59
 return:
	32位小写md5码切片

func CheckCrc16VB

func CheckCrc16VB(d []byte) bool

CheckCrc16VB check crc16 data

func CheckCrc16VBBigOrder

func CheckCrc16VBBigOrder(d []byte) bool

CheckCrc16VBBigOrder check crc16 data,use big order

func CheckIP

func CheckIP(ip string) bool

CheckIP check if the ipstring is legal

 args:
	ip: ipstring something like 127.0.0.1:10001
 return:
	true/false

func CheckLrc

func CheckLrc(d []byte) bool

CheckLrc check lrc data

func CheckRCMru

func CheckRCMru(d []byte) bool

CheckRCMru 校验电表数据

func CheckSQLInject

func CheckSQLInject(s string) bool

CheckSQLInject 检查sql语句是否包含注入攻击

func CodeString

func CodeString(s string) string

CodeString 编码字符串

func CopyFile

func CopyFile(src, dst string) (int64, error)

CopyFile 复制文件

func CountCrc16VB

func CountCrc16VB(data *[]byte) []byte

CountCrc16VB count crc16 as vb6 do

func CountLrc

func CountLrc(data *[]byte) byte

CountLrc count lrc data

func CountRCMru

func CountRCMru(d []byte) byte

CountRCMru 计算电表校验码

func DFM2GPS

func DFM2GPS(du, fen int, miao float64) float64

DFM2GPS 度分秒转经纬度

func Days2String

func Days2String(days int) string

Days2String 将天数转换为年月日显示

func Days2StringCHS

func Days2StringCHS(days int) string

Days2StringCHS 将天数转换为年月日显示

func DecodeString

func DecodeString(s string) string

DecodeString 解码混淆字符串,兼容python算法

func DecodeStringOld

func DecodeStringOld(s string) string

DecodeStringOld 解码混淆字符串,兼容python算法

func DoRequestWithTimeout

func DoRequestWithTimeout(req *http.Request, timeo time.Duration) (int, []byte, map[string]string, error)

DoRequestWithTimeout 发起请求

func DoStreamRequest

func DoStreamRequest(req *http.Request, header func(map[string]string), recv func([]byte) error, opts ...httpclient.ReqOptions) error

func DumpReqBody

func DumpReqBody(req *http.Request) ([]byte, error)

func EncodeUTF16BE

func EncodeUTF16BE(s string) []byte

EncodeUTF16BE 将字符串编码成utf16be的格式,用于cdma短信发送

func EraseSyncMap

func EraseSyncMap(m *sync.Map)

EraseSyncMap 清空sync.map

func Float32ToByte

func Float32ToByte(float float32) []byte

Float32ToByte 32位浮点转bytes

func Float32ToByteBig

func Float32ToByteBig(float float32) []byte

Float32ToByte 32位浮点转bytes

func Float64ToByte

func Float64ToByte(float float64) []byte

Float64ToByte 64位浮点转bytes

func Float64ToByteBig

func Float64ToByteBig(float float64) []byte

Float64ToByte 64位浮点转bytes

func Float642BcdBytes

func Float642BcdBytes(v float64, f string) []byte

Float642BcdBytes 浮点转bcd字节数组(小端序)

v:十进制浮点数值
f:格式化的字符串,如"%07.03f","%03.0f"

func Float642BcdBytesBigOrder

func Float642BcdBytesBigOrder(v float64, f string) []byte

Float642BcdBytesBigOrder 浮点转bcd字节数组(大端序)

v:十进制浮点数值
f:格式化的字符串,如"%07.03f","%03.0f"

func FormatBytes

func FormatBytes(bytes int64) string

FormatBytes 将字节数转换为带单位的字符串表示形式

func FormatDuration

func FormatDuration(seconds int64, opts ...DurationOptions) string

FormatDuration 接受秒数和一个可选的 DurationOptions 结构体 将秒数转换为 xx天xx小时xx分钟xx秒 的可读格式。

func FormatFileSize

func FormatFileSize(byteSize uint64) (size string)

FormatFileSize 字节的单位转换

func FormatFloat64

func FormatFloat64(f float64, p int) float64

FormatFloat64 格式化浮点精度,f-浮点数,p-小数位数

func GPS2DFM

func GPS2DFM(l float64) (int, int, float64)

GPS2DFM 经纬度转度分秒

func GbkToUtf8

func GbkToUtf8(s []byte) ([]byte, error)

GbkToUtf8 gbk编码转utf8

func GetAddrFromString

func GetAddrFromString(straddr string) ([]int64, error)

GetAddrFromString get addr from config string

straddr: something like "1,2,3-6" return: []int64,something like []int64{1,2,3,4,5,6}

func GetFirstLocalIP

func GetFirstLocalIP(preferIPv6 bool) (string, error)

GetFirstLocalIP 返回首个匹配的本机地址,找不到时返回空字符串和错误。 优先 IPv4(preferIPv6=false),可通过 preferIPv6 改变优先级。

func GetLocalIPs

func GetLocalIPs(ipv6 bool) ([]string, error)

GetLocalIPs 返回本机所有网卡绑定的 IPv4 或 IPv6 地址(不包含回环或未启用接口)。 参数 ipv6 = true 则返回 IPv6 地址,否则返回 IPv4 地址。 会过滤:未启用接口、loopback、未指定地址(0.0.0.0 / ::)、链路本地地址(如 fe80::/10)。

func GetRandomString

func GetRandomString(l int64, letteronly ...bool) string

GetRandomString 生成随机字符串

func GetTCPPort

func GetTCPPort() (int, error)

GetTCPPort 获取随机可用端口

func GetUUID1

func GetUUID1() string

GetUUID1 returns a Version 1 UUID based on the current NodeID and clock sequence, and the current time. If the NodeID has not been set by SetNodeID or SetNodeInterface then it will be set automatically. If the NodeID cannot be set NewUUID returns nil. If clock sequence has not been set by SetClockSequence then it will be set automatically. If GetTime fails to return the current NewUUID returns nil and an error.

In most cases, New should be used.

func HTTPBasicAuth

func HTTPBasicAuth(namemap map[string]string, next http.HandlerFunc) http.HandlerFunc

func HexString2Bytes

func HexString2Bytes(s string, bigorder bool) []byte

HexString2Bytes 转换hexstring为字节数组

s-hexstring(11aabb)
bigorder-是否高位在前
false低位在前

func IP2Int64

func IP2Int64(ipnr string) int64

IP2Int64 change ip string data to int64 format

func IP2Uint

func IP2Uint(ipnr string) uint

IP2Uint change ip string data to int64 format

func IPInt642Bytes

func IPInt642Bytes(ipnr int64) []byte

IPInt642Bytes change ip int64 data to string format

func IPInt642String

func IPInt642String(ipnr int64) string

IPInt642String change ip int64 data to string format

func IPUint2Bytes

func IPUint2Bytes(ipnr int64) []byte

IPUint2Bytes change ip int64 data to string format

func IPUint2String

func IPUint2String(ipnr uint) string

IPUint2String change ip int64 data to string format

func IPv6ToInt32Segments

func IPv6ToInt32Segments(s string) ([]byte, error)

IPv6ToInt32Segments 将 IPv6 地址字符串转换为 16 字节的表示形式。 每个 16 位段使用低字节在前(little-endian per segment)。 支持缩写 ::、带方括号的形式 [::1] 以及带 zone 的形式 fe80::1%eth0。 返回长度为 16 的 byte 数组,解析失败返回错误。

func Imgfile2Base64

func Imgfile2Base64(s string) (string, error)

Imgfile2Base64 图片转base64

func Int32SegmentsToIPv6

func Int32SegmentsToIPv6(b []byte) (string, error)

Int32SegmentsToIPv6 将 16 字节(每段 2 字节,低字节在前,little-endian per segment)的数据 还原为标准的 IPv6 字符串表示(如 "2001:db8::1")。 输入长度必须为 16,否则返回错误。

func Int82Bcd

func Int82Bcd(v byte) byte

Int82Bcd int to bcd

func Int82Byte

func Int82Byte(i int8) byte

Int82Byte 有符号整型转byte

func Int642Bytes

func Int642Bytes(i int64, bigOrder bool) []byte

Int642Bytes 无符号长整形转换字节数组(8位),bigOrder==true,高位在前

func IsValidIP

func IsValidIP(ipStr string) (string, bool)

func JSON2PB

func JSON2PB(js string, pb interface{}) error

JSON2PB json字符串转pb2格式

func LastSlice

func LastSlice(s, sep string) string

LastSlice 返回切片的最后一个元素

func LeftPadZeros

func LeftPadZeros(s string, totalLen int) string

func PB2Json

func PB2Json(pb interface{}) []byte

PB2Json pb2格式转换为json []byte格式

func PB2String

func PB2String(pb interface{}) string

PB2String pb2格式转换为json 字符串格式

func ParseNumberRange

func ParseNumberRange(input string) ([]int64, error)

ParseNumberRange 解析逗号分隔的数字字符串,支持范围表示法(如"2-8") 输入示例: "1,3,5-9,12" 输出: [1,3,5,6,7,8,9,12]

func RealIP

func RealIP(v6first bool) string

RealIP 返回本机的v4或v6ip

func RemoveUnvisiable

func RemoveUnvisiable(s string) string

func ReverseString

func ReverseString(s string) string

ReverseString ReverseString

func SMSUnicode

func SMSUnicode(s string) []string

SMSUnicode 编码短信

func STime2Bcd

func STime2Bcd(t int32) []byte

STime2Bcd hh*60+mm转BCD

func Seconds2String

func Seconds2String(sec int64) string

Seconds2String 秒数转换成天,小时,分钟

func Seconds2StringCHS

func Seconds2StringCHS(sec int64) string

Seconds2StringCHS 秒数转换成天,小时,分钟

func SignedBytes2Int64

func SignedBytes2Int64(b []byte) int64

SignedBytes2Int64 有符号字节数组转int64,低前

func SignedInt322Byte deprecated

func SignedInt322Byte(i int32) byte

SignedInt322Byte 有符号整形转byte

Deprecated: use Int82Byte()

func SlicesDifference

func SlicesDifference(slice1, slice2 []string) []string

SlicesDifference 求差集 slice1-并集

func SlicesIntersect

func SlicesIntersect(slice1, slice2 []string) []string

SlicesIntersect 求交集

func SlicesUnion

func SlicesUnion(slice1, slice2 []string) []string

SlicesUnion 求并集

func SplitDateTime

func SplitDateTime(sdt int64) (y, m, d, h, mm, s, wd byte)

SplitDateTime SplitDateTime

func SplitStringWithLen

func SplitStringWithLen(s string, l int) []string

SplitStringWithLen 按制定长度分割字符串

s-原始字符串
l-切割长度

func Stamp2BcdDT

func Stamp2BcdDT(dt int64) []byte

Stamp2BcdDT unix时间戳转bcd,6字节,第一字节为秒

func Stamp2Time

func Stamp2Time(t int64, fmt ...string) string

Stamp2Time convert stamp to datetime string

func String deprecated

func String(b []byte) string

String use unsafe package conver []byte to string

Deprecated: use json.String

func String2Byte

func String2Byte(s string, t int) byte

String2Byte convert string 2 one byte

 args:
	s: 输入字符串
	t: 返回数值进制
 Return:
	byte

func String2Bytes

func String2Bytes(data string, sep string) []byte

String2Bytes convert hex-string to []byte

 args:
	data: 输入字符串
	sep: 用于分割字符串的分割字符
 return:
	字节切片

func String2Float32

func String2Float32(s string) float32

String2Float32 convert string 2 float64

func String2Float64

func String2Float64(s string) float64

String2Float64 convert string 2 float64

func String2Int

func String2Int(s string, t int) int

String2Int convert string 2 int

 args:
	s: 输入字符串
	t: 返回数值进制
 Return:
	int

func String2Int8

func String2Int8(s string, t int) byte

String2Int8 convert string 2 int8

 args:
	s: 输入字符串
	t: 返回数值进制
 Return:
	int8

func String2Int32

func String2Int32(s string, t int) int32

String2Int32 convert string 2 int32

 args:
	s: 输入字符串
	t: 返回数值进制
 Return:
	int32

func String2Int64

func String2Int64(s string, t int) int64

String2Int64 convert string 2 int64

 args:
	s: 输入字符串
	t: 返回数值进制
 Return:
	int64

func String2UInt64

func String2UInt64(s string, t int) uint64

String2UInt64 convert string 2 uint64

 args:
	s: 输入字符串
	t: 返回数值进制
 Return:
	uint64

func String2Unicode

func String2Unicode(s string) string

String2Unicode 字符串转4位unicode编码

func StringSlice2Int8

func StringSlice2Int8(bs []string) byte

StringSlice2Int8 convert string Slice 2 int8

func StringToFixedRightPad

func StringToFixedRightPad(s string, n int) []byte

StringToFixedRightPad 截断或右侧填充 0x00 到指定字节长度 n

func SwapCase

func SwapCase(s string) string

SwapCase swap char case

func SwitchStamp

func SwitchStamp(t int64) int64

SwitchStamp switch stamp format between unix and c#

func Time2Stamp

func Time2Stamp(s string) int64

Time2Stamp convert datetime string to stamp

func Time2StampNB

func Time2StampNB(s string) int64

Time2StampNB 电信NB平台数据时间戳转为本地unix时间戳

func Time2Stampf

func Time2Stampf(s, fmt string, tz float32) int64

Time2Stampf 可根据制定的时间格式和时区转换为当前时区的Unix时间戳

	s:时间字符串
 fmt:时间格式
 year:2006,month:01,day:02
 hour:15,minute:04,second:05
 tz:0~12,超范围时使用本地时区

func TrimString

func TrimString(s string) string

TrimString 去除字符串末尾的空格,\r\n

func Uint642Bytes

func Uint642Bytes(i uint64, bigOrder bool) []byte

Uint642Bytes 长整形转换字节数组(8位),bigOrder==true,高位在前

func UnZIPFile

func UnZIPFile(archive, target string) error

UnZIPFile 解压缩文件

func Utf8ToGbk

func Utf8ToGbk(s []byte) ([]byte, error)

Utf8ToGbk utf8编码转gbk

func ValidateIPPort

func ValidateIPPort(s string) (*net.TCPAddr, bool)

ValidateIPPort 验证输入的 "ip:port" 字符串(支持 IPv4 和 IPv6)。 返回解析出的 ip(不含方括号与 zone)和端口号;解析失败返回 error。 支持格式示例:

1.2.3.4:80
[2001:db8::1]:443
2001:db8::1:443   // 尝试通过最后一个冒号分割 host/port(推荐使用带方括号的 IPv6)

注:IPv6 带 zone 的情况会在验证时去掉 zone(例如 fe80::1%eth0 -> fe80::1)。

func WriteVersionInfo

func WriteVersionInfo(p, v, gv, bd, pl, a string)

WriteVersionInfo write version info to .ver file

 args:
	p: program name
	v: program version
	gv: golang version
	bd: build datetime
	pl: platform info
	a: auth name

func ZIPFile

func ZIPFile(d, s string, delold bool) error

ZIPFile 压缩文件

func ZIPFiles

func ZIPFiles(dstName string, srcFiles []string, newDir string) error

ZIPFiles 压缩多个文件

Types

type DurationOptions

type DurationOptions func(opt *durationOption)

func WithEnglishUnit

func WithEnglishUnit(t bool) DurationOptions

func WithShowSeconds

func WithShowSeconds(t bool) DurationOptions

type FlexibleInt64

type FlexibleInt64 int64

1. 定义一个兼容类型

func (*FlexibleInt64) Int64

func (f *FlexibleInt64) Int64() int64

func (*FlexibleInt64) String

func (f *FlexibleInt64) String() string

String 方便打印

func (*FlexibleInt64) UnmarshalJSON

func (f *FlexibleInt64) UnmarshalJSON(data []byte) error

2. 实现 UnmarshalJSON 接口

type StringSliceSort

type StringSliceSort struct {
	OneDimensional []string
	TwoDimensional [][]string
	Idx            int
	Order          string
}

StringSliceSort 字符串数组排序

func (*StringSliceSort) Len

func (arr *StringSliceSort) Len() int

func (*StringSliceSort) Less

func (arr *StringSliceSort) Less(i, j int) bool

func (*StringSliceSort) Swap

func (arr *StringSliceSort) Swap(i, j int)

type Time

type Time int64

A Time represents a time as the number of 100's of nanoseconds since 15 Oct 1582.

Directories

Path Synopsis
Package cache : 数据缓存模块,可定时清理过期数据
Package cache : 数据缓存模块,可定时清理过期数据
Package config 类ini的配置文件库,支持注释信息
Package config 类ini的配置文件库,支持注释信息
Package coord 坐标相关功能模块
Package coord 坐标相关功能模块
Package cron scheduled jobs
Package cron scheduled jobs
Package crypto 加密解密
Package crypto 加密解密
cmd command
Package db : 数据库模块,封装了常用方法,可缓存数据,可依据配置自动创建myisam引擎的子表,支持mysql和sqlserver
Package db : 数据库模块,封装了常用方法,可缓存数据,可依据配置自动创建myisam引擎的子表,支持mysql和sqlserver
Package email : email emtp发送模块
Package email : email emtp发送模块
Package excel excel功能模块
Package excel excel功能模块
Package games : 搜罗的一些网页小游戏
Package games : 搜罗的一些网页小游戏
Package ginmiddleware 基于gin的web框架封装
Package ginmiddleware 基于gin的web框架封装
Package loopfunc : 用于控制需要持续运行的循环方法,当方法漰溃时会自动重启
Package loopfunc : 用于控制需要持续运行的循环方法,当方法漰溃时会自动重启
Package mapfx 线程安全的字典模块
Package mapfx 线程安全的字典模块
Package mq mqtt 和 rmq 相关功能模块
Package mq mqtt 和 rmq 相关功能模块
Package pathtool some path-related methods
Package pathtool some path-related methods
Package proc watch process status
Package proc watch process status
test command
Package queue safety queue
Package queue safety queue
Package sunriset 日出日落功能模块
Package sunriset 日出日落功能模块
Package tcpfactory 高可用性的tcp服务
Package tcpfactory 高可用性的tcp服务

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL