goutils

package
v1.2.167 Latest Latest
Warning

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

Go to latest
Published: Dec 14, 2024 License: Apache-2.0 Imports: 48 Imported by: 0

README

常用工具包

加密相关
  • 生成 AES 密钥
  • 生成 AES 密钥和 IV
  • 计算文件md5(支持超大文件)
  • 计算MD5大写、计算Md5小写
  • SHA1、SHA256、HMacMd5、HMacSha1、SHAWithRSA
  • Base64Encode、Base64Decode
  • SHAWithRSA
email
  • HideEmail
  • IsEmail
大数据计算
  • bigint 计算
Goroutine
  • NewErrorGroup(context.TODO(), maxWorkers) 并发可取消的协程组
  • AsyncFunc
  • AsyncFuncPanic
  • AsyncFuncGroup
  • AsyncFuncGroupPanic
  • MeasureExecutionTime
  • IsContextDone
Utils
  • func CheckSign(secret string, linkSignTimeout int64, ts int64, sign string) bool // 常用签名验证, sign md5 小写
  • func CheckSignSha1(secret, nonce string, linkSignTimeout int64, ts int64, sign string) bool {
  • func IsInArray[T any](arr []T, target T) bool // 元素都转换成字符串比较
  • func IsInArrayX[T any](arr []T, exists func(target T) bool) bool
  • func IsInArrayXX[T any](arr []*T, exists func(target *T) bool) bool
  • func IfNot[T any](isTrue bool, a, b T) T // 通用三目运算
  • func IfString(isTrue bool, a, b string) string
  • func IfInt(isTrue bool, a, b int) int
  • func IfFloat32(isTrue bool, a, b float32) float32
  • func IfFloat64(isTrue bool, a, b float64) float64
  • func ReverseArray(arr []*interface{})
  • func PadStart(str, pad string, length int) string
  • func MinInt64(a, b int64) int64
  • func MinInt(a, b int) int
  • func MaxInt64(a, b int64) int64
  • func MaxInt(a, b int) int
  • func GenValidateCode(width int) string {//随机数
  • func SplitStringArray(arr []string, size int) (list [][]string)
  • func SplitIntArray(arr []int, size int) (list [][]int)
  • func SplitInt64Array(arr []int64, size int) (list [][]int64)
  • func SplitArray(arr []interface{}, size int) (list [][]interface{})
  • func GetFieldValue(config interface{}, fieldName string) (interface{}, error) {// 通过反射获取结构体字段的值
  • func CopyProperties[T any](target interface{}) // 复制对象
  • func GetRuntimeStack() string // 获取运行堆栈
  • func GenericSort // 通用排序
  • func InsertionSort // 通用插入排序
  • func FillMissingNumbers 填充缺失数字
  • func ConvertAmPmHourTo24HourFormat Am Pm 时间转换比
password
  • func BcryptHash(password string) string // BcryptHash 使用 bcrypt 对密码进行加密
  • func BcryptCheck(password, hash string) bool // BcryptCheck 对比明文密码和数据库的哈希值
  • func ValidPassword(str string) (msg string, matched bool) { //至少一位数字、大小字母,且长度6-20位
  • func ValidPasswordV2(str string) (msg string, matched bool) { //至少一位数字、大小字母和特殊字符,且长度6-20位
time 时间
  • time.go
  • timex.go
xml
  • xml.go

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	TimeLayout string = "2006-01-02 15:04:05"
	DateLayout        = "20060102"
	TimeFormat        = map[string]string{
		"Y-m-d H:i:s": "2006-01-02 15:04:05",
		"Y-m-d":       "2006-01-02",
		"Ymd":         "20060102",
		"H:i:s":       "15:04:05",
		"Y":           "2006",
		"m":           "01",
		"d":           "02",
	}
)

这个包即将废弃,改用 gotime 包

View Source
var (
	ErrInitialize = errors.New("not yet initialized")
)

Functions

func AESCBCDecrypt

func AESCBCDecrypt(cipherData, key, iv []byte) ([]byte, error)

func AESCBCEncrypt

func AESCBCEncrypt(rawData, key, iv []byte) ([]byte, error)

func AESECBDecrypt

func AESECBDecrypt(buf, key []byte) ([]byte, error)

func AESECBEncrypt

func AESECBEncrypt(data, key []byte) ([]byte, error)

func AddFloat64 added in v1.1.2

func AddFloat64(a float64, b float64) float64

func AfterPage added in v1.2.101

func AfterPage(page int64, pageCount int64) int64

下一页

func AsyncFunc

func AsyncFunc(fn func())

异步执行(安全)

func AsyncFuncGroup

func AsyncFuncGroup(fns ...func())

异步并发执行(安全), 建议使用NewErrorGroup 替代

func AsyncFuncGroupPanic added in v1.1.7

func AsyncFuncGroupPanic(errFn func(err any), fns ...func())

异步并发执行(安全)errFn = nil 时自动Recovery 不会Panic

建议使用NewErrorGroup 替代

func AsyncFuncPanic added in v1.1.7

func AsyncFuncPanic(fn func(), errFn func(err any))

异步执行(安全)errFn = nil 时自动Recovery 不会Panic

func Base59Decoding

func Base59Decoding(strByte []byte, key ...string) []byte

func Base59Encoding

func Base59Encoding(strByte []byte, key ...string) string

如果遇到特殊字符,需要用 url.PathEscape(str) 解决

func Base64Decode

func Base64Decode(str string) []byte

func Base64Encode

func Base64Encode(buf []byte) string

func BcryptCheck added in v1.2.64

func BcryptCheck(password, hash string) bool

BcryptCheck 对比明文密码和数据库的哈希值

func BcryptHash added in v1.2.64

func BcryptHash(password string) string

BcryptHash 使用 bcrypt 对密码进行加密

func BeforePage added in v1.2.101

func BeforePage(page int64) int64

func BeijingTimeLocation added in v1.2.129

func BeijingTimeLocation() *time.Location

func BigIntAdd

func BigIntAdd(num1 string, num2 string) string

func BigIntCmp

func BigIntCmp(num1 string, num2 string) int

比大小,大于返回1,等于返回0,小于返回-1

func BigIntDiv

func BigIntDiv(num1 string, num2 string) string

func BigIntMod

func BigIntMod(num1 string, num2 string) string

取模

func BigIntMul

func BigIntMul(num1 string, num2 string) string

func BigIntReduce

func BigIntReduce(num1 string, num2 string) string

func CalculateFileMD5 added in v1.2.34

func CalculateFileMD5(filePath string) (string, error)

计算文件md5(支持超大文件)

func Camel2Case

func Camel2Case(str string) string

驼峰转下划线

func CaptchaAudioGet added in v1.2.27

func CaptchaAudioGet(audioStr string) map[string]string

func CaptchaChineseGet added in v1.2.27

func CaptchaChineseGet(width, height int, source string) map[string]string

func CaptchaGet

func CaptchaGet(width, height int) map[string]string

获取图片验证码-数字

func CaptchaMathGet added in v1.2.27

func CaptchaMathGet(width, height int) map[string]string

func CaptchaStringGet added in v1.2.27

func CaptchaStringGet(width, height int) map[string]string

func CaptchaVerify

func CaptchaVerify(id, code string) bool

验证图片验证码

func Case2Camel

func Case2Camel(str string) string

下划线转驼峰

func CheckSign added in v1.2.17

func CheckSign(secret string, linkSignTimeout int64, ts int64, sign string) bool

常用签名验证, sign md5 小写

func Code2Id

func Code2Id(code string) (int64, error)

func ConvertAmPmHourTo24HourFormat added in v1.2.127

func ConvertAmPmHourTo24HourFormat(timeStr string, layout24Hour string) (string, error)

convertTo24HourFormat 将时间字符串转换为 0-23 小时制 timeStr: 时间字符串,例如 "3:04 PM" 3:04 PM-->15:04 ,必须是这两个格式之一

func ConvertToGMTTime added in v1.2.136

func ConvertToGMTTime(gmtTime string) (time.Time, error)

格式为: 2021-08-06T07:00:00+0000 To time.Time

func CopyProperties added in v1.2.88

func CopyProperties[T any](target interface{}) T

使用反射复制A结构到B结构,前提是两个结构体字段数量和类型完全相同 如:使用反射将 VO 转换为 DTO 反射(reflect)虽爽,但很贵,性能会有损失

func CurrentHourStartAndEnd added in v1.0.14

func CurrentHourStartAndEnd() (int, int64, int64)

func Date2Ts

func Date2Ts(date string) int64

func Date2TsLocal added in v1.2.93

func Date2TsLocal(date string, location *time.Location) int64

func DateTime

func DateTime(format string) string

当前时区相关日期函数

func DateTime2Ts

func DateTime2Ts(dateTime string) int64

func DateTime2TsLocal added in v1.2.93

func DateTime2TsLocal(dateTime string, location *time.Location) int64

func DateTime2TsLocalFormat added in v1.2.93

func DateTime2TsLocalFormat(dateTime string, location *time.Location, format string) int64

func DateTimeLocal added in v1.2.93

func DateTimeLocal(format string, timeOffsetSec int) string

当前时间通用 格式用法

func DatesForRangeTs added in v1.2.154

func DatesForRangeTs(startTimestamp int64, endTimestamp int64, format string) []string

func DivFloat64 added in v1.1.2

func DivFloat64(a float64, b float64) float64

func FillMissingNumbers added in v1.2.98

func FillMissingNumbers(nums []int64, max int64) []int64

把缺失的数字填充到数组中

func GBK2UTF8

func GBK2UTF8(s string) string

func GBKToUTF8 added in v1.2.167

func GBKToUTF8(text string) (string, error)

GBK 转 UTF8

func GenId

func GenId() int64

func GenIdInit

func GenIdInit(adapter iGenId)

func GenIdStr

func GenIdStr() string

func GenValidateCode added in v1.0.14

func GenValidateCode(width int) string

func GenerateAESKey added in v1.2.52

func GenerateAESKey() (string, error)

生成 AES 密钥

func GenerateAESKeyAndIV added in v1.2.52

func GenerateAESKeyAndIV() (string, string, error)

生成 AES 密钥和 IV

func GenericSort added in v1.2.96

func GenericSort[T any](arr []T, less func(T, T) bool)

定义一个泛型排序函数

func GetChinaTomorrowAMSeconds added in v1.0.14

func GetChinaTomorrowAMSeconds(isBeijing bool) int64

func GetDateInterval added in v1.0.14

func GetDateInterval(t1, t2 time.Time) int

func GetFieldValue added in v1.2.25

func GetFieldValue(config interface{}, fieldName string) (interface{}, error)

通过反射获取结构体字段的值

func GetLocalTomorrowAMSeconds added in v1.0.14

func GetLocalTomorrowAMSeconds() int64

func GetNowDateForLocation added in v1.0.14

func GetNowDateForLocation(isBeijing bool) string

func GetPageCount added in v1.2.100

func GetPageCount(total int64, pageSize int64) (totalPages int64)

func GetRuntimeStack added in v1.2.89

func GetRuntimeStack() string

func GetTimeNow added in v1.0.14

func GetTimeNow() time.Time

GetTimeNow 获取当前时间GetTimeNow(),用于测试时的时间修改

func GetTodayZero added in v1.0.14

func GetTodayZero() time.Time

func GetZero added in v1.0.14

func GetZero(targetTime time.Time) time.Time

func HMacMd5

func HMacMd5(buf, key []byte) string

func HMacSha1

func HMacSha1(buf, key []byte) string

func HMacSha256

func HMacSha256(buf, key []byte) string

func HideEmail added in v1.0.14

func HideEmail(email string) string

func Id2Code

func Id2Code(id int64) string

func IfFloat32 added in v1.0.14

func IfFloat32(isTrue bool, a, b float32) float32

func IfFloat64 added in v1.0.14

func IfFloat64(isTrue bool, a, b float64) float64

func IfInt added in v1.0.14

func IfInt(isTrue bool, a, b int) int

func IfNot added in v1.1.3

func IfNot[T any](isTrue bool, a, b T) T

通用三目运算

func IfString added in v1.0.14

func IfString(isTrue bool, a, b string) string

func InitCaptcha added in v1.2.27

func InitCaptcha(captcha *gocaptcha.GoCaptcha)

func InsertionSort added in v1.2.96

func InsertionSort[T any](arr []T, less func(T, T) bool)

插入排序函数,使用泛型指定元素类型

func IsContextDone added in v1.2.46

func IsContextDone(ctx context.Context) bool

func IsEmail added in v1.0.17

func IsEmail(email string) bool

func IsEqualArray added in v1.2.166

func IsEqualArray[T comparable](arr1 []T, arr2 []T) bool

两个数组是否相等,判断长度一样的两个数组 元素是否完全相同,顺序可以不同

func IsInArray added in v1.1.12

func IsInArray[T comparable](arr []T, target T) bool

元素都转换成字符串比较

func IsInArrayX added in v1.2.125

func IsInArrayX[T any](arr []T, exists func(target T) bool) bool

条件满足任意元素 exists func(target T) bool 返回true时返回true

适合判断数组中存储复杂对象,判断条件定义情况

用以下代替

slices.ContainsFunc(arr, func(t T) bool {

})

func IsInArrayXX added in v1.2.125

func IsInArrayXX[T any](arr []*T, exists func(target *T) bool) bool

条件满足任意元素 exists func(target *T) bool 返回true时返回true

适合判断数组中存储复杂对象,判断条件定义情况,数组元素是指针类型时用

用以下代替

slices.ContainsFunc(arr, func(t T) bool {

})

func IsInt added in v1.2.138

func IsInt(str string) bool

func IsNumeric added in v1.2.138

func IsNumeric(str string) bool

是不是数字

func IsSameDay added in v1.0.14

func IsSameDay(t1, t2 time.Time) bool

func IsValidDate added in v1.2.139

func IsValidDate(str string) bool

func IsValidDateTime added in v1.2.138

func IsValidDateTime(str string) bool

判断是不是 2024-11-22 4 格式的时间串

func LastHourStartAndEnd added in v1.0.14

func LastHourStartAndEnd(isBeijing bool) (int, int64, int64)

LastHourStartAndEnd 上一个小时的开始和结束时间戳

func MD5

func MD5(buf []byte) string

MD5 大写

func MaxInt added in v1.0.14

func MaxInt(a, b int) int

func MaxInt64 added in v1.0.14

func MaxInt64(a, b int64) int64

func Md5 added in v1.2.17

func Md5(buf []byte) string

Md5小写

func MeasureExecutionTime added in v1.2.34

func MeasureExecutionTime(fn func()) time.Duration

返回函数执行时间

func MinInt added in v1.0.14

func MinInt(a, b int) int

func MinInt64 added in v1.0.14

func MinInt64(a, b int64) int64

func MulFloat64 added in v1.1.2

func MulFloat64(a float64, b float64) float64

func NewIdCode

func NewIdCode(key string) *idCode

func NextDate

func NextDate(d int) string

func NextDateLocal added in v1.2.93

func NextDateLocal(d int, timeOffsetSec int) string

NextDate

func NonceStr

func NonceStr() string

func NonceStr8

func NonceStr8() string

func Now

func Now() string

func NowLocal added in v1.2.93

func NowLocal(timeOffsetSec int) string

NowDateTime

func PadStart added in v1.0.14

func PadStart(str, pad string, length int) string

func ParseTime added in v1.0.14

func ParseTime(timeStr string) (datetime time.Time)

ParseTime 解析时间,"2021-03-17 00:00:00"

func ParseTimeString added in v1.0.14

func ParseTimeString(timeStr string) (datetime time.Time)

func PinYin

func PinYin(origin string) (string, error)

func Recovery

func Recovery(errFn func(err any))

捕获panic

func ReverseArray added in v1.0.14

func ReverseArray(arr []*interface{})

func SHA1

func SHA1(buf []byte) string

小写

func SHA256

func SHA256(buf, key []byte) string

func SHAWithRSA

func SHAWithRSA(key, data []byte) (string, error)

func SessionId

func SessionId() string

func SinceDays added in v1.0.14

func SinceDays(dateString string) (int64, error)

SinceDays 获取过去的天数,dateString格式20060102

func Split

func Split(s string, rs ...rune) []string

多字符切割,默认支持逗号,分号,\n

func SplitArray

func SplitArray(arr []interface{}, size int) (list [][]interface{})

func SplitInt64Array

func SplitInt64Array(arr []int64, size int) (list [][]int64)

func SplitIntArray

func SplitIntArray(arr []int, size int) (list [][]int)

func SplitStringArray

func SplitStringArray(arr []string, size int) (list [][]string)

func SubFloat64 added in v1.1.2

func SubFloat64(a float64, b float64) float64

func Sum added in v1.2.160

func Sum(list []int) int

func TimeRangeDates added in v1.0.14

func TimeRangeDates(startDate string, endDate string) []string

func TimeRangeDay added in v1.0.14

func TimeRangeDay(stTime int64, endTIme int64) int

返回相差天数

func ToDate added in v1.0.14

func ToDate(ts int64, isBeijing bool) string

func ToDateTime added in v1.0.14

func ToDateTime(ts int64, isBeijing bool) string

func Today

func Today() string

func TodayLocal added in v1.2.93

func TodayLocal(timeOffsetSec int) string

NowDate

func Ts2Date

func Ts2Date(ts int64) string

func Ts2DateLocal added in v1.2.92

func Ts2DateLocal(ts int64, timeOffsetSec int) string

本地化日期 给定时间戳(以秒为单位)

func Ts2DateTime

func Ts2DateTime(ts int64) string

func Ts2DateTimeLocal added in v1.2.92

func Ts2DateTimeLocal(ts int64, timeOffsetSec int) string

本地化日期时间 给定时间戳(以秒为单位)

func Ts2DateTimeLocalFormat added in v1.2.93

func Ts2DateTimeLocalFormat(ts int64, timeOffsetSec int, format string) string

将时间对象转换为特定时区的时间

func Ts2Time added in v1.2.115

func Ts2Time(t int64) time.Time

func UTF82GBK

func UTF82GBK(s string) string

func UTF8ToGBK added in v1.2.167

func UTF8ToGBK(text string) (string, error)

如果只需要转换单个字符串为 GBK

func UUID added in v1.2.143

func UUID() string

func UrlDecode added in v1.2.108

func UrlDecode(str string) string

func UrlEncode added in v1.2.108

func UrlEncode(str string) string

func ValidPassword

func ValidPassword(str string) (msg string, matched bool)

func ValidPasswordV2

func ValidPasswordV2(str string) (msg string, matched bool)

Types

type Byte

type Byte []byte

func (Byte) Params

func (b Byte) Params() (p Params, err error)

type ErrorGroup added in v1.2.90

type ErrorGroup struct {
	// contains filtered or unexported fields
}

func NewErrorGroup added in v1.2.90

func NewErrorGroup(context context.Context, maxWorkers int) ErrorGroup

当并发执行过程中有错误时,会自动取消其他所有任务,通过CancelContext 取消来实现 (最大并发数为 maxWorkers,超过阻塞等待 )

func (*ErrorGroup) IsContextDone added in v1.2.90

func (e *ErrorGroup) IsContextDone() bool

func (*ErrorGroup) Submit added in v1.2.90

func (e *ErrorGroup) Submit(fn ...func() error)

func (*ErrorGroup) TryGo added in v1.2.91

func (e *ErrorGroup) TryGo(fn func() error) bool

func (*ErrorGroup) Wait added in v1.2.90

func (e *ErrorGroup) Wait() error

type M added in v1.2.144

type M map[string]interface{}

func (M) Json added in v1.2.144

func (m M) Json() []byte

func (M) Params added in v1.2.144

func (m M) Params() Params

func (M) String added in v1.2.144

func (m M) String() string

type Mode

type Mode int
const (
	WithoutTone        Mode = iota + 1 // 默认模式,例如:guo
	Tone                               // 带声调的拼音 例如:guó
	InitialsInCapitals                 // 首字母大写不带声调,例如:Guo
)

type Params

type Params struct {
	// contains filtered or unexported fields
}

func Json2Params added in v1.2.158

func Json2Params(b []byte) (p Params, err error)

func NewParams

func NewParams() Params

func (Params) Array

func (p Params) Array() (ps []Params)

func (Params) ArrayData

func (p Params) ArrayData() []interface{}

func (Params) Bool

func (p Params) Bool() bool

func (Params) Data

func (p Params) Data() interface{}

func (Params) Float32

func (p Params) Float32() float32

func (Params) Float64

func (p Params) Float64() float64

func (Params) Get

func (p Params) Get(key string) Params

func (Params) Int

func (p Params) Int() int

func (Params) Int32

func (p Params) Int32() int32

func (Params) Int64

func (p Params) Int64() int64

func (Params) JSON

func (p Params) JSON() []byte

func (Params) Map

func (p Params) Map() (rst map[string]Params)

func (Params) MapData

func (p Params) MapData() map[string]interface{}

func (Params) Set

func (p Params) Set(key string, val interface{}) Params

func (Params) String

func (p Params) String() string

type SafeSlice added in v1.2.5

type SafeSlice[T comparable] struct {
	// contains filtered or unexported fields
}

读写锁 + 顺序获取(循环)

如: s := []string{"s1", "s2", "s3"}, 无论并发怎么读取,顺序为:s1,s2,s3,s1,s2,s3,s1,s2,s...

func NewSafeSlice added in v1.2.5

func NewSafeSlice[T comparable]() *SafeSlice[T]

func (*SafeSlice[T]) Get added in v1.2.5

func (m *SafeSlice[T]) Get() T

func (*SafeSlice[T]) Set added in v1.2.5

func (m *SafeSlice[T]) Set(str T)

func (*SafeSlice[T]) Sets added in v1.2.5

func (m *SafeSlice[T]) Sets(data []T)

type SnowFlakeId

type SnowFlakeId struct {
	DataCenterId int // 机房或者数据中心ID 0 - 31
	WorkerId     int // 机器或者容器ID 0 - 31
	// contains filtered or unexported fields
}

Snowflake,雪花算法是由Twitter开源的分布式ID生成算法,以划分命名空间的方式将 64-bit位分割成多个部分, 每个部分代表不同的含义。这种就是将64位划分为不同的段,每段代表不同的涵义,基本就是时间戳、机器ID和序列数。 为什么如此重要?因为它提供了一种ID生成及生成的思路,当然这种方案就是需要考虑时钟回拨的问题以及做一些 buffer的缓冲设计提高性能。 雪花算法

func (*SnowFlakeId) GenId

func (sf *SnowFlakeId) GenId() int64

type StringMap

type StringMap map[string]string

func (StringMap) MarshalXML

func (m StringMap) MarshalXML(e *xml.Encoder, start xml.StartElement) error

func (*StringMap) UnmarshalXML

func (m *StringMap) UnmarshalXML(d *xml.Decoder, _ xml.StartElement) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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