utils

package
v1.19.47 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2024 License: MIT Imports: 55 Imported by: 11

README

Go-Utils Go语言常用公共函数收集

安装

go get -u github.com/maczh/utils

包含工具包

  • 3DES加解密
  • AES加解密
  • DES加解密
  • BASE64编码解码
  • RSA加密解密签名验签
  • MD5摘要算法
  • SHA摘要算法
  • JSON序列化与反序列化
  • 文件与目录操作
  • 常用字符串验证:手机号、email、昵称、用户名、中文名等
  • 条件判断函数
  • 文件下载工具
  • emoji表情工具
  • Gin获取Post和Get全部参数 x-www-form-urlencoded
  • hashset
  • IP和端口工具
  • Map转换、排序、判断key是否存在
  • 随机字符串工具
  • uuid生成工具
  • SFTP上传下载工具
  • 数组切片工具
  • 字符串工具
  • 中文工具:判断是否中文、中文字数、中文取子串、GBK/UTF-8互转
  • 结构体与map互转工具
  • 运行外部程序工具
  • 时间格式转换
  • URL编码反编码
  • XML与map互转工具
  • zip压缩工具

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDataToLarge     = errors.New("message too long for RSA public key size")
	ErrDataLen         = errors.New("data length error")
	ErrDataBroken      = errors.New("data broken, first byte is not zero")
	ErrKeyPairDismatch = errors.New("data is not encrypted by the private key")
	ErrDecryption      = errors.New("decryption error")
	ErrPublicKey       = errors.New("get public key error")
	ErrPrivateKey      = errors.New("get private key error")
)
View Source
var LimitQueue = &LimitQueeMap{
	LimitQueue: make(map[string][]int64),
}
View Source
var RSA = &RSASecurity{}
View Source
var (
	UUIDSnippet = block1 + "-" + block2 + "-" + block3 + "-" + block4 + "-" + block5
)

regex for validating that the UUID matches RFC 4122. This package generates version 4 UUIDs but accepts any UUID version. http://www.ietf.org/rfc/rfc4122.txt

Functions

func AESBase64Decrypt

func AESBase64Decrypt(encrypt_data string, key string, iv []byte) (string, error)

func AESBase64Encrypt

func AESBase64Encrypt(origin_data string, key string, iv []byte) (base64_result string, err error)

func AESDecrypt

func AESDecrypt(data string, key string) string

func AESEncrypt

func AESEncrypt(data string, key string) string

func AddPortsToFirewall added in v1.19.42

func AddPortsToFirewall(ports []int)

func AddSpaceBetweenCharsAndNumbers

func AddSpaceBetweenCharsAndNumbers(src string) string

func AddString

func AddString(s ...string) string

AddString 拼接字符串

func AddStringBytes

func AddStringBytes(s ...string) []byte

AddStringBytes 拼接字符串, 返回 bytes from bytes.Join()

func AesDecrypt

func AesDecrypt(encrypted []byte, key []byte) ([]byte, error)

func AesDecryptEcb

func AesDecryptEcb(crypted, key string) (string, error)

func AesEncrypt

func AesEncrypt(origData []byte, key []byte) ([]byte, error)

func AesEncryptEcb

func AesEncryptEcb(src, key string) (string, error)

func AnyToMap added in v1.1.22

func AnyToMap(obj any) map[string]string

func AnyToString added in v1.19.42

func AnyToString(i any) (string, error)

func ArrayInt2Str

func ArrayInt2Str(data []int) []string

[]int => []string

func ArrayStr2Int

func ArrayStr2Int(data []string) []int

[]string => []int

func Base64Decode

func Base64Decode(str string) string

func Base64Encode

func Base64Encode(str string) string

func Basename

func Basename(file string) string

get filepath base name

func BytePos

func BytePos(s string, bt byte) int

BytePos alias of the strings.IndexByte

func CenterJustin

func CenterJustin(text string, size int) string

Center justifies the text in the center

func CheckSqlValidate

func CheckSqlValidate(content string) (bool, string)

CheckSqlValidate 检查是否含有可能产生注入的非法字符 返回值为true时表示含有非法字符,同时返回的字符串值为匹配到的非法字符

func ChineseLength

func ChineseLength(str string) int

func ClearUtf8BOM

func ClearUtf8BOM(bomStr string) string

func Clone

func Clone(src any, dst any)

func CmdExec

func CmdExec(name string, arg ...string) (string, error)

func CmdRunWithTimeout

func CmdRunWithTimeout(cmd *exec.Cmd, timeout time.Duration) (error, bool)

func CompactJSON

func CompactJSON(in string) string

CompactJSON compact json input with insignificant space characters elided

func Compress

func Compress(data []byte) ([]byte, error)

Compress returns compressed bytes

func ConvertDateFormat

func ConvertDateFormat(timeStr string, format string) string

func CopyStruct added in v1.19.17

func CopyStruct(src, dst any)

func DBCtoSBC

func DBCtoSBC(s string) string

全角转半角

func DESDecrypt

func DESDecrypt(data string, key string) string

func DESDecryptECB

func DESDecryptECB(data string, key string) string

func DESEncrypt

func DESEncrypt(data string, key string) string

func DESEncryptECB

func DESEncryptECB(data string, key string) string

func DateFormat

func DateFormat(t time.Time, format string) string

Format time.Time struct to string MM - month - 01 M - month - 1, single bit DD - day - 02 D - day 2 YYYY - year - 2006 YY - year - 06 HH - 24 hours - 03 H - 24 hours - 3 hh - 12 hours - 03 h - 12 hours - 3 mm - minute - 04 m - minute - 4 ss - second - 05 s - second = 5

func DecodeXMLToMap

func DecodeXMLToMap(r io.Reader) (m map[string]string, err error)

DecodeXMLToMap decodes xml reading from io.Reader and returns the first-level sub-node key-value set, if the first-level sub-node contains child nodes, skip it.

func Decompress

func Decompress(data []byte) ([]byte, error)

Decompress returns the decompressed bytes

func DeepCopy added in v1.19.17

func DeepCopy[D any](src any) D

func DefaultIfNil

func DefaultIfNil(value any, defaultValue any) any

DefaultIfNil checks if the value is nil, if true returns the default value otherwise the original

func DeleteArray

func DeleteArray(src []any, index int) (result []any)

删除数组

func DesDecrypt

func DesDecrypt(crypted, key []byte) ([]byte, error)

func DesEcbDecrypt

func DesEcbDecrypt(src, key []byte) ([]byte, error)

func DesEcbEncrypt

func DesEcbEncrypt(src, key []byte) ([]byte, error)

func DesEncrypt

func DesEncrypt(origData, key []byte) ([]byte, error)

func DifferenceStringSlice

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

求差集 slice1-并集

func Dir

func Dir(file string) string

get filepath dir name

func DirsUnder

func DirsUnder(dirPath string) ([]string, error)

list dirs under dirPath

func DisplaySize

func DisplaySize(raw float64) string

func DownloadFile

func DownloadFile(fileUrl, localPath string) (string, error)

func EncodeXMLFromMap

func EncodeXMLFromMap(w io.Writer, m map[string]string, rootname string) (err error)

EncodeXMLFromMap encodes map[string]string to io.Writer with xml format.

NOTE: This function requires the rootname argument and the keys of m (type map[string]string) argument
are legitimate xml name string that does not contain the required escape character!

func Existi

func Existi(src map[string]any, key string) bool

func Exists

func Exists(src map[string]string, key string) bool

func Ext

func Ext(file string) string

func FileMD5

func FileMD5(filename string) (string, error)

计算文件的MD5值

func FileMTime

func FileMTime(file string) (int64, error)

get file modified time

func FileSha256

func FileSha256(filename string) (string, error)

func FileSize

func FileSize(file string) (int64, error)

get file size as how many bytes

func FilesUnder

func FilesUnder(dirPath string) ([]string, error)

list files under dirPath

func FirstNonNil

func FirstNonNil(values ...any) any

FirstNonNil returns the first non nil parameter

func Float64ArrayContains

func Float64ArrayContains(src []float64, dst float64) bool

func Float64ArrayDelete

func Float64ArrayDelete(src []float64, index int) []float64

func FromJSON

func FromJSON(j string, o any) *any

func GbkToUtf8

func GbkToUtf8(gbkStr string) (string, error)

func GenerateRandString

func GenerateRandString(source string, l int) string

func Get0Hour

func Get0Hour(t time.Time) time.Time

Get0Hour 当天 0 点

func Get0LastMonth

func Get0LastMonth(t time.Time) time.Time

Get0LastMonth 上月第一天 0 点

func Get0LastWeek

func Get0LastWeek(t time.Time) time.Time

Get0LastWeek 上周一 0 点

func Get0Minute

func Get0Minute(t time.Time) time.Time

Get0Minute 0 分

func Get0Month

func Get0Month(t time.Time) time.Time

Get0Month 当月第一天 0 点

func Get0NextMonth

func Get0NextMonth(t time.Time) time.Time

Get0NextMonth 下月第一天 0 点

func Get0NextWeek

func Get0NextWeek(t time.Time) time.Time

Get0NextWeek 下周一 0 点

func Get0Second

func Get0Second(t time.Time) time.Time

Get0Second 0 秒

func Get0Tomorrow

func Get0Tomorrow(t time.Time) time.Time

Get0Tomorrow 昨天 0 点

func Get0Week

func Get0Week(t time.Time) time.Time

Get0Week 本周一 0 点

func Get0Yesterday

func Get0Yesterday(t time.Time) time.Time

Get0Yesterday 昨天 0 点

func GetDate

func GetDate() string

func GetGoroutineID

func GetGoroutineID() uint64

func GetIPv4ByInterface

func GetIPv4ByInterface(name string) ([]string, error)

GetIPv4ByInterface return IPv4 address from a specific interface IPv4 addresses

func GetLocalIpAddress

func GetLocalIpAddress() (ip string)

func GetMonthDays

func GetMonthDays(t time.Time) int

GetMonthDays 当月天数

func GetNowDateTime

func GetNowDateTime() string

func GetRandomCaseString

func GetRandomCaseString(l int) string

func GetRandomHexString

func GetRandomHexString(l int) string

func GetRandomIntString

func GetRandomIntString(l int) string

func GetRandomString

func GetRandomString(l int) string

func GetStructFields

func GetStructFields(obj any) []string

func GetStructJsonTags

func GetStructJsonTags(obj any) []string

func GetUUIDString

func GetUUIDString() string

func GinHeaders added in v1.1.1

func GinHeaders(c *gin.Context) map[string]string

func GinParamMap

func GinParamMap(c *gin.Context) map[string]string

GinParamMap 获取请求参数,转成Map

func GormTimeFormat

func GormTimeFormat(t string) string

func HmacSHA1

func HmacSHA1(key string, data string) []byte

func HmacSHA1Base64

func HmacSHA1Base64(key string, data string) string

func HmacSHA1Hex

func HmacSHA1Hex(key string, data string) string

func HmacSHA256

func HmacSHA256(key string, data string) []byte

func HmacSHA256Base64

func HmacSHA256Base64(key string, data string) string

func HmacSHA256Hex

func HmacSHA256Hex(key string, data string) string

func IfThen

func IfThen(condition bool, a any) any

IfThen evaluates a condition, if true returns the parameters otherwise nil

func IfThenElse

func IfThenElse(condition bool, a any, b any) any

IfThenElse evaluates a condition, if true returns the first parameter otherwise the second

func InsureDir

func InsureDir(path string) error

func Int64Unique

func Int64Unique(a []int64) []int64

Int64Unique 去重

func IntArrayContains

func IntArrayContains(src []int, dst int) bool

func IntArrayDelete

func IntArrayDelete(src []int, index int) []int

func IntersectStringSlice

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

求交集

func IsAlphaNum

func IsAlphaNum(c uint8) bool

IsAlphaNum reports whether the byte is an ASCII letter, number, or underscore

func IsAlphabet

func IsAlphabet(char uint8) bool

IsAlphabet char

func IsBlank

func IsBlank(text string) bool

IsBlank returns true if the string is blank (all whitespace)

func IsBlankBytes

func IsBlankBytes(bs []byte) bool

IsBlankBytes returns true if the given []byte is all space characters.

func IsChinaMobile

func IsChinaMobile(b []byte) bool

检验是否为合法的中国手机号, 不是那么太精细 只要是 13,14,15,18 开头的 11 位数字就认为是中国手机号

func IsChinaMobileString

func IsChinaMobileString(s string) bool

同 func IsChinaMobile(b []byte) bool

func IsChinese

func IsChinese(str string) bool

func IsChineseName

func IsChineseName(b []byte) bool

IsChineseName 检验是否为有效的中文姓名(比如 张三, 李四, 张三·李四)

func IsChineseNameEx

func IsChineseNameEx(b []byte) ([]byte, bool)

IsChineseNameEx 检验是否为有效的中文姓名(比如 张三, 李四, 张三·李四), 主要功能和 IsChineseName 相同, 但是如果姓名中包含不规范的间隔符, 会自动修正为正确的间隔符 '\u00B7', 并返回正确的结果.

func IsChineseNameString

func IsChineseNameString(s string) bool

同 IsChineseName(b []byte) bool

func IsChineseNameStringEx

func IsChineseNameStringEx(s string) (string, bool)

同 IsChineseNameEx(b []byte) ([]byte, bool)

func IsDir

func IsDir(s string) bool

IsDir 目录是否存在

func IsEmpty

func IsEmpty(text string) bool

IsEmpty returns true if the string is empty

func IsEndOf

func IsEndOf(s, sub string) bool

IsEndOf alias of the strings.HasSuffix

func IsExist

func IsExist(path string) bool

IsExist checks whether a file or directory exists. It returns false when the file or directory does not exist.

func IsFile

func IsFile(filePath string) bool

IsFile checks whether the path is a file, it returns false when it's a directory or does not exist.

func IsIdCard

func IsIdCard(cardNo string) bool

判断是否是18或15位身份证

func IsIntranetIP

func IsIntranetIP(ip string) bool

func IsMail

func IsMail(b []byte) bool

检验是否为合法的电子邮箱, 考虑到各个网站的 mail 要求不一样, 这里匹配比较宽松 邮箱用户名可以包含 0-9, A-Z, a-z, -, _, . 开头字母不能是 -, _, . 结尾字母不能是 -, _, . -, _, . 这三个连接字母任意两个不能连续, 如不能出现 --, __, .., -_, -., _. 邮箱的域名可以包含 0-9, A-Z, a-z, - 连接字符 - 只能出现在中间, 不能连续, 如不能 -- 支持多级域名, x@y.z, x@y.z.w, x@x.y.z.w.e

func IsMailString

func IsMailString(s string) bool

同 func IsMail(b []byte) bool

func IsMark

func IsMark(r rune) bool

IsMark determines whether the rune is a marker

func IsNickname

func IsNickname(b []byte) bool

检验是否为合法的昵称, 合法的字符有 0-9, A-Z, a-z, _, 汉字 字符 '_' 只能出现在中间且不能重复, 如 "__"

func IsNicknameString

func IsNicknameString(s string) bool

同 func IsNickname(b []byte) bool

func IsNotBlank

func IsNotBlank(text string) bool

IsNotBlank returns true if the string is not blank

func IsNotEmpty

func IsNotEmpty(text string) bool

IsNotEmpty returns true if the string is not empty

func IsNumeric

func IsNumeric(c byte) bool

IsNumeric returns true if the given character is a numeric, otherwise false.

func IsPortUse

func IsPortUse(port int) bool

IsPortUse 判断端口是否被占用

func IsSpace

func IsSpace(c byte) bool

IsSpace returns true if the given character is a space, otherwise false.

func IsSpaceRune

func IsSpaceRune(r rune) bool

IsSpaceRune returns true if the given rune is a space, otherwise false.

func IsStartOf

func IsStartOf(s, sub string) bool

IsStartOf alias of the strings.HasPrefix

func IsUserName

func IsUserName(b []byte) bool

检验是否为合法的用户名, 合法的字符有 0-9, A-Z, a-z, _ 第一个字母不能为 _, 0-9 最后一个字母不能为 _, 且 _ 不能连续

func IsUserNameString

func IsUserNameString(s string) bool

同 func IsName(b []byte) bool

func IsValidUUIDString

func IsValidUUIDString(s string) bool

IsValidUUIDString returns true, if the given string matches a valid UUID (version 4, variant 2).

func JSONPretty

func JSONPretty(in, prefix, indent string) string

JSONPrettyPrint pretty print raw json string to indent string

func Left

func Left(src string, size int) string

func LeftJustin

func LeftJustin(text string, size int) string

Left justifies the text to the left

func Length

func Length(text string) int

Length counts the input while respecting UTF8 encoding and combined characters

func LimitFreqSingle added in v1.19.0

func LimitFreqSingle(queueName string, count uint, timeWindow int64) bool

单机时间滑动窗口限流法

func LocalIPv4s

func LocalIPv4s() ([]string, error)

LocalIPs return all non-loopback IPv4 addresses

func LowerFirst

func LowerFirst(s string) string

LowerFirst lower first char

func Lowercase

func Lowercase(s string) string

func MD5Encode

func MD5Encode(content string) (md string)

func MapItoS

func MapItoS(src map[string]any) map[string]string

map转换

func MapMD5

func MapMD5(m map[string]string) string

func MapStoI

func MapStoI(src map[string]string) map[string]any

map转换

func NewECBDecrypter

func NewECBDecrypter(b cipher.Block) cipher.BlockMode

NewECBDecrypter returns a BlockMode which decrypts in electronic code book mode, using the given Block.

func NewECBEncrypter

func NewECBEncrypter(b cipher.Block) cipher.BlockMode

NewECBEncrypter returns a BlockMode which encrypts in electronic code book mode, using the given Block.

func NewLimitQueue added in v1.19.0

func NewLimitQueue()

func NewSafeGo added in v1.1.16

func NewSafeGo(argsF func(args ...any)) *safeGo

NewSafeGo 创建一个安全的协程调用

示例:
safeGo := NewSafeGo(func(args ...any) {

})
safeGo.SetGoBeforeHandler(func() map[string]any {
	return map[string]any{
		"preRoutineId": "123",
	}
})
safeGo.SetCallBeforeHandler(func(params map[string]any) {
	fmt.Println(params["preRoutineId"])
})
safeGo.Run("hello", "world")

func NewUUIDString

func NewUUIDString() string

func PKCS5Padding

func PKCS5Padding(cipherText []byte, blockSize int) []byte

func PKCS5UnPadding

func PKCS5UnPadding(origData []byte) ([]byte, error)

func PriKeyDecrypt

func PriKeyDecrypt(data, privateKey string) (string, error)

私钥解密

func PriKeyEncrypt

func PriKeyEncrypt(data, privateKey string) (string, error)

私钥加密

func PublicDecrypt

func PublicDecrypt(data, publicKey string) (string, error)

公钥解密

func PublicEncrypt

func PublicEncrypt(data, publicKey string) (string, error)

公钥加密

func ReadFileToBytes

func ReadFileToBytes(filePath string) ([]byte, error)

ReadFileToBytes reads data type '[]byte' from file by given path. It returns error when fail to finish operation.

func ReadFileToString

func ReadFileToString(filePath string) (string, error)

ReadFileToString reads data type 'string' from file by given path. It returns error when fail to finish operation.

func RealPath

func RealPath(file string) (string, error)

get absolute filepath, based on built executable file

func Rename

func Rename(file string, to string) error

rename file name

func ReplacePunctuation

func ReplacePunctuation(src, replaceWith string) string

func ReplacePunctuationWithSpace

func ReplacePunctuationWithSpace(src string) string
func Right(src string, size int) string

func RightJustin

func RightJustin(text string, size int) string

Right justifies the text to the right

func RunePos

func RunePos(s string, ru rune) int

RunePos alias of the strings.IndexRune

func SearchFile

func SearchFile(filename string, paths ...string) (fullPath string, err error)

Search a file in paths. this is often used in search config file in /etc ~/

func SelfDir

func SelfDir() string

SelfDir gets compiled executable file directory

func SelfPath

func SelfPath() string

SelfPath gets compiled executable file absolute path

func SftpClose

func SftpClose(sftpClient *sftp.Client, sshClient *ssh.Client)

func SftpConnect

func SftpConnect(user, password, host string, port int) (*sftp.Client, *ssh.Client, error)

func SftpUploadFile

func SftpUploadFile(sftpClient *sftp.Client, localFilePath string, remotePath string)

func Sha1

func Sha1(src string) string

func Sha256

func Sha256(src string) string

func SimpleUUID

func SimpleUUID() string

func SliceContains

func SliceContains(sl []any, v any) bool

func SliceContainsInt

func SliceContainsInt(sl []int, v int) bool

func SliceContainsInt64

func SliceContainsInt64(sl []int64, v int64) bool

func SliceContainsString

func SliceContainsString(sl []string, v string) bool

func SliceMerge

func SliceMerge(slice1, slice2 []any) (c []any)

SliceMerge merges interface slices to one slice.

func SliceMergeInt

func SliceMergeInt(slice1, slice2 []int) (c []int)

func SliceMergeInt64

func SliceMergeInt64(slice1, slice2 []int64) (c []int64)

func SliceMergeString

func SliceMergeString(slice1, slice2 []string) (c []string)

func SliceSumFloat64

func SliceSumFloat64(intslice []float64) (sum float64)

func SliceSumInt

func SliceSumInt(intslice []int) (sum int)

func SliceSumInt64

func SliceSumInt64(intslice []int64) (sum int64)

func SliceUniqueInt

func SliceUniqueInt(s []int) []int

func SliceUniqueInt64

func SliceUniqueInt64(s []int64) []int64

func SliceUniqueString

func SliceUniqueString(s []string) []string

func StrPos

func StrPos(s, sub string) int

StrPos alias of the strings.Index

func StringArrayContains

func StringArrayContains(src []string, dst string) bool

func StringArrayDelete

func StringArrayDelete(src []string, index int) []string

func StringToAny added in v1.19.42

func StringToAny[T any](src string) (T, error)

func StringUnique

func StringUnique(a []string) []string

StringUnique 去重

func Struct2Map

func Struct2Map(obj any) map[string]any

Struct2Map return map

func Struct2MapString added in v1.1.21

func Struct2MapString(obj any) map[string]string

func SubChineseString

func SubChineseString(str string, begin, length int) string

func TimeSubDays

func TimeSubDays(t1, t2 time.Time) int

func ToDateString

func ToDateString(date time.Time) string

func ToDateTimeString

func ToDateTimeString(date time.Time) string

func ToJSON

func ToJSON(o any) string

func ToTimeString

func ToTimeString(date time.Time) string

func TrimEmoji

func TrimEmoji(s string) string

清除emoji表情

func TrimSpaceStrInArray

func TrimSpaceStrInArray(str string, data []string) bool

str[TrimSpace] in string list

func TripleDESDecrypt

func TripleDESDecrypt(data string, key string, pcks5padding bool) string

func TripleDESEncrypt

func TripleDESEncrypt(data string, key string, pcks5padding bool) string

func TripleDesDecrypt

func TripleDesDecrypt(crypted, key []byte, pcks5padding bool) ([]byte, error)

3DES解密

func TripleDesEncrypt

func TripleDesEncrypt(origData, key []byte, pcks5padding bool) ([]byte, error)

3DES加密

func TripleEcbDesDecrypt

func TripleEcbDesDecrypt(crypted, key []byte) ([]byte, error)

[golang ECB 3DES Decrypt]

func TripleEcbDesEncrypt

func TripleEcbDesEncrypt(origData, key []byte) ([]byte, error)

[golang ECB 3DES Encrypt]

func UnSplitString

func UnSplitString(src []string, sep string) string

func UnicodeEmojiCode

func UnicodeEmojiCode(s string) string

表情转换

func UnicodeEmojiDecode

func UnicodeEmojiDecode(s string) string

表情解码

func UnionStringSlice

func UnionStringSlice(slice1, slice2 []string) []string
func Unlink(file string) error

delete file

func UpperFirst

func UpperFirst(s string) string

UpperFirst upper first char

func UpperWord

func UpperWord(s string) string

UpperWord Change the first character of each word to uppercase

func Uppercase

func Uppercase(s string) string

Uppercase alias of the strings.ToUpper()

func UrlDecode

func UrlDecode(encoded string) (string, error)

func UrlEncode

func UrlEncode(rawString string) string

func Utf8ToGbk

func Utf8ToGbk(uft8Str string) string

func Utf8len

func Utf8len(s string) int

Utf8Len of the string

func ValidUtf8String

func ValidUtf8String(s string) bool

ValidUtf8String check

func WaitNextMinute

func WaitNextMinute()

WaitNextMinute 下一分钟, 对齐时间, 0 秒

func WeekByDate

func WeekByDate(t time.Time) int

判断时间是当年的第几周

func WriteBytesToFile

func WriteBytesToFile(filePath string, b []byte) (int, error)

WriteBytesToFile saves content type '[]byte' to file by given path. It returns error when fail to finish operation.

func WriteStringToFile

func WriteStringToFile(filePath string, s string) (int, error)

WriteStringFile saves content type 'string' to file by given path. It returns error when fail to finish operation.

func ZeroPadding

func ZeroPadding(ciphertext []byte, blockSize int) []byte

func ZeroUnPadding

func ZeroUnPadding(origData []byte) []byte

func ZipFiles

func ZipFiles(filename string, files []string, srcpath string, aliasnames []string) error

ZIP压缩多个文件,带批量修改压缩包里的文件名功能

Types

type EscapeError

type EscapeError string

func (EscapeError) Error

func (e EscapeError) Error() string

type HashSet

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

func NewHashSet

func NewHashSet() *HashSet

func (*HashSet) Add

func (set *HashSet) Add(i string) bool

func (*HashSet) Exists

func (set *HashSet) Exists(i string) bool

func (*HashSet) Members

func (set *HashSet) Members() []string

func (*HashSet) Remove

func (set *HashSet) Remove(i string)

type LimitQueeMap added in v1.19.0

type LimitQueeMap struct {
	sync.RWMutex
	LimitQueue map[string][]int64
}

type Pair

type Pair struct {
	Key   string `json:"key"`
	Value any    `json:"value"`
}

按值排序

type PairList

type PairList []Pair

func SortMapByValue

func SortMapByValue(src map[string]any) PairList

func SortMapByValueDesc

func SortMapByValueDesc(src map[string]any) PairList

func (PairList) Len

func (p PairList) Len() int

func (PairList) Less

func (p PairList) Less(i, j int) bool

func (PairList) Swap

func (p PairList) Swap(i, j int)

type RSASecurity

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

func (*RSASecurity) GetPrivatekey

func (rsas *RSASecurity) GetPrivatekey() (*rsa.PrivateKey, error)

*rsa.PublicKey

func (*RSASecurity) GetPublickey

func (rsas *RSASecurity) GetPublickey() (*rsa.PublicKey, error)

*rsa.PrivateKey

func (*RSASecurity) PriKeyDECRYPT

func (rsas *RSASecurity) PriKeyDECRYPT(input []byte) ([]byte, error)

私钥解密

func (*RSASecurity) PriKeyENCTYPT

func (rsas *RSASecurity) PriKeyENCTYPT(input []byte) ([]byte, error)

私钥加密

func (*RSASecurity) PubKeyDECRYPT

func (rsas *RSASecurity) PubKeyDECRYPT(input []byte) ([]byte, error)

公钥解密

func (*RSASecurity) PubKeyENCTYPT

func (rsas *RSASecurity) PubKeyENCTYPT(input []byte) ([]byte, error)

公钥加密

func (*RSASecurity) SetPrivateKey

func (rsas *RSASecurity) SetPrivateKey(priStr string) (err error)

设置私钥

func (*RSASecurity) SetPublicKey

func (rsas *RSASecurity) SetPublicKey(pubStr string) (err error)

设置公钥

func (*RSASecurity) SignSha1WithRsa

func (rsas *RSASecurity) SignSha1WithRsa(data string) (string, error)

*

  • 使用RSAWithSHA1算法签名

func (*RSASecurity) SignSha256WithRsa

func (rsas *RSASecurity) SignSha256WithRsa(data string) (string, error)

*

  • 使用RSAWithSHA256算法签名

func (*RSASecurity) SignSha256WithRsaHex

func (rsas *RSASecurity) SignSha256WithRsaHex(data string) (string, error)

func (*RSASecurity) SignSha256WithRsaUrlSafe

func (rsas *RSASecurity) SignSha256WithRsaUrlSafe(data string) (string, error)

func (*RSASecurity) VerifySignSha1WithRsa

func (rsas *RSASecurity) VerifySignSha1WithRsa(data string, signData string) error

*

  • 使用RSAWithSHA1验证签名

func (*RSASecurity) VerifySignSha256WithRsa

func (rsas *RSASecurity) VerifySignSha256WithRsa(data string, signData string) error

*

  • 使用RSAWithSHA256验证签名

type UUID

type UUID [16]byte

UUID represent a universal identifier with 16 octets.

func MustNewUUID

func MustNewUUID() UUID

MustNewUUID returns a new uuid, if an error occurs it panics.

func NewUUID

func NewUUID() (UUID, error)

NewUUID generates a new version 4 UUID relying only on random numbers.

func UUIDFromString

func UUIDFromString(s string) (UUID, error)

func (UUID) Copy

func (uuid UUID) Copy() UUID

Copy returns a copy of the UUID.

func (UUID) Raw

func (uuid UUID) Raw() [16]byte

Raw returns a copy of the UUID bytes.

func (UUID) Simple

func (uuid UUID) Simple() string

func (UUID) String

func (uuid UUID) String() string

String returns a hexadecimal string representation with standardized separators.

type WeekDate

type WeekDate struct {
	WeekTh    int
	StartDate string
	EndDate   string
}

func GroupByWeekDate

func GroupByWeekDate(startTime, endTime time.Time) []WeekDate

将开始时间和结束时间分割为周为单位

Jump to

Keyboard shortcuts

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