yo

package
v1.2.8 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2024 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxRounds      = 31
	MinRounds      = 4
	DefaultRounds  = 12
	SaltLen        = 16
	BlowfishRounds = 16
)
View Source
const ASCIISub = '\x1a'

ASCIISub is the ASCII substitute character, as recommended by https://unicode.org/reports/tr36/#Text_Comparison

Variables

View Source
var (
	InvalidRounds = errors.New("bcrypt: Invalid rounds parameter")
	InvalidSalt   = errors.New("bcrypt: Invalid salt supplied")
)
View Source
var (
	// ErrShortDst means that the destination buffer was too short to
	// receive all of the transformed bytes.
	ErrShortDst = errors.New("transform: short destination buffer")

	// ErrShortSrc means that the source buffer has insufficient data to
	// complete the transformation.
	ErrShortSrc = errors.New("transform: short source buffer")

	// ErrEndOfSpan means that the input and output (the transformed input)
	// are not identical.
	ErrEndOfSpan = errors.New("transform: input and output are not identical")
)

编码转换

View Source
var (
	// Discard is a Transformer for which all Transform calls succeed
	// by consuming all bytes and writing nothing.
	Discard Transformer = discard{}

	// Nop is a SpanningTransformer that copies src to dst.
	Nop SpanningTransformer = nop{}
)
View Source
var (
	DefaultTrimChars = string([]byte{
		'\t',
		'\v',
		'\n',
		'\r',
		'\f',
		' ',
		0x00,
		0x85,
		0xA0,
	})
)
View Source
var ErrASCIIReplacement = RepertoireError(ASCIISub)
View Source
var ErrInvalidUTF8 = errors.New("encoding: invalid UTF-8")

ErrInvalidUTF8 means that a transformer encountered invalid UTF-8.

View Source
var UTF8ValidatorTransformer = utf8Validator{}

UTF8Validator is a transformer that returns ErrInvalidUTF8 on the first input byte that is not valid UTF-8.

Functions

func AesDecode added in v1.2.7

func AesDecode(encrypted string, k string) (string, error)

AesDecode

@Description: AES解密
@param encrypted
@param k
@return string
@return error

func AesEncode added in v1.2.7

func AesEncode(text string, k string) (string, error)

AesEncode

@Description: AES加密,支持aes128 192 256
@param text
@param k
@return string
@return error

func Append

func Append(t Transformer, dst, src []byte) (result []byte, n int, err error)

Append appends the result of converting src[:n] using t to dst, where n <= len(src), If err == nil, n will be len(src). It calls Reset on t.

func Assign added in v1.2.7

func Assign[K comparable, V any, Map ~map[K]V](maps ...Map) Map

Assign[K comparable, V any, Map ~map[K]V]

@Description: 合并map
@param maps
@return Map

func AuthCode added in v1.2.7

func AuthCode(text string, params ...interface{}) string

Authcode("1234==+wo我们",true,"abc")

@Description:对称加密解密
@param text
@param params
@return string

func Average

func Average[T Float | Integer](collection []T) T

Average [T Float | Integer]

@Description: 数组求平均值
@param collection
@return T

func Base64Decode

func Base64Decode(s string) string

Base64Decode

@Description: base64解码
@param s
@return string

func Base64Encode

func Base64Encode(s string) string

Base64Encode

@Description: base64编码
@param s
@return string

func Bytes

func Bytes(t Transformer, b []byte) (result []byte, n int, err error)

Bytes returns a new byte slice with the result of converting b[:n] using t, where n <= len(b). If err == nil, n will be len(b). It calls Reset on t.

func CeilToFloat added in v1.2.7

func CeilToFloat[T Float | Integer](x T, n int) float64

CeilToFloat[T Float | Integer] CeilToFloat(3.14159, 1)3.2 CeilToFloat(5, 4) 5

@Description: 向上舍入(进一法),保留n位小数
@param x
@param n
@return float64

func Chunk

func Chunk[T any, Slice ~[]T](collection Slice, size int) []Slice

Chunk[T any, Slice ~[]T]

@Description: 分割数组
@param collection
@param size
@return []Slice

func CliInput added in v1.2.7

func CliInput(str string, check func(string) error) string

CliInput

@Description: cli输入
@param str
@param check nil
@return string

func CliSelect added in v1.2.7

func CliSelect(question string, choices map[string]string) string

CliSelect

@Description: cli选择多项
@param question
@param choices
@return string

func CliYesNo added in v1.2.7

func CliYesNo(question string) bool

CliYesNo

@Description: cli选择yes/no
@param question
@return bool

func ColorHexToRGB

func ColorHexToRGB(colorHex string) (red, green, blue int)

ColorHexToRGB

@Description: 十六进制转换rgb
@param colorHex
@return red
@return green
@return blue

func ColorRGBToHex

func ColorRGBToHex(red, green, blue int) string

ColorRGBToHex

@Description: rgb转换十六进制
@param red
@param green
@param blue
@return string

func Comma added in v1.2.7

func Comma[T Float | Integer | string](value T, prefixSymbol string) string

Comma[T Float | Integer | string]

@Description: 逗号分割数字或字符串,支持添加前缀
@param value
@param prefixSymbol
@return string

func Compact

func Compact[T comparable, Slice ~[]T](collection Slice) Slice

Compact[T comparable, Slice ~[]T]

@Description: 返回去除 "" nil字符的切片
@param collection
@return Slice

func Concat added in v1.2.7

func Concat[T any, Slice ~[]T](collections ...Slice) Slice

Concat[T any, Slice ~[]T]

@Description: 合并数组并排序
@param collections
@return Slice

func Contains added in v1.2.7

func Contains[T comparable](collection []T, element T) bool

Contains[T comparable]

@Description: 数组中是否包含某元素
@param collection
@param element
@return bool

func CopyDir added in v1.2.7

func CopyDir(srcPath string, dstPath string) error

CopyDir

@Description: 复制目录到目标路径
@param srcPath
@param dstPath
@return error

func CopyFile

func CopyFile(srcPath string, dstPath string) error

CopyFile

@Description: 复制文件
@param srcPath
@param dstPath
@return error

func CountBy added in v1.2.7

func CountBy[T any](collection []T, predicate func(item T) bool) (count int)

CountBy[T any]

@Description: 计算符合条件元素数量
@param collection
@param predicate
@return count

func CreateDir

func CreateDir(absPath string) error

CreateDir

@Description: 创建目录
@param absPath
@return error

func CreateFile

func CreateFile(path string) bool

CreateFile

@Description: 创建文件
@param path
@return bool

func CurrentPath

func CurrentPath() string

CurrentPath

@Description: 当前位置绝对路径
@return string

func DirSize added in v1.2.7

func DirSize(path string) (int64, error)

DirSize

@Description: 目录大小字节
@param path
@return int64
@return error

func DownloadFile

func DownloadFile(filepath string, url string) error

DownloadFile

@Description: 下载文件
@param filepath
@param url
@return error

func Drop

func Drop[T any, Slice ~[]T](collection Slice, n int) Slice

Drop[T any, Slice ~[]T]

@Description: slice开头删除元素
@param collection
@param n
@return Slice

func DropByIndex added in v1.2.7

func DropByIndex[T any](collection []T, indexes ...int) []T

DropByIndex[T any]

@Description: 根据索引删除元素
@param collection
@param indexes
@return []T

func DropRight

func DropRight[T any, Slice ~[]T](collection Slice, n int) Slice

DropRight[T any, Slice ~[]T]

@Description: slice末尾删除元素
@param collection
@param n
@return Slice

func Ellipsis added in v1.2.7

func Ellipsis(str string, length uint) string

Ellipsis

@Description: 字符串截取
@param str
@param length
@return string

func Emoji

func Emoji(s string) (ss string)

Emoji

@Description: emoji转换实体直接显示
@param s
@return ss

func EmojiDecode

func EmojiDecode(s string) string

EmojiDecode

@Description: emoji解码
@param s
@return string

func EmojiEncode

func EmojiEncode(s string) string

EmojiEncode

@Description: emoji编码
@param s
@return string

func Empty

func Empty[T any]() T

func EncodeUrl

func EncodeUrl(urlStr string) (string, error)

EncodeUrl ?a=1&b=[2] -> ?a=1&b=%5B2%5D

@Description: 编码url
@param urlStr
@return string
@return error

func Err

func Err(err error)

Err

@Description: 显示错误
@param err

func FileMode added in v1.2.7

func FileMode(path string) (fs.FileMode, error)

FileMode

@Description:获取文件信息
@param path
@return fs.FileMode
@return error

func FileSize

func FileSize(path string) (int64, error)

FileSize

@Description: 文件大小字节
@param path
@return int64
@return error

func FindKey added in v1.2.7

func FindKey[K comparable, V comparable](object map[K]V, value V) (K, bool)

FindKey[K comparable, V comparable]

@Description: 在map中查找值的键
@param object
@param value
@return K
@return bool

func First added in v1.2.7

func First[T any](collection []T, fallback T) T

FirstOr[T any]

@Description: 返回集合第一个元素,不存在则是默认值
@param collection
@param fallback
@return T

func Flatten

func Flatten[T any, Slice ~[]T](collection []Slice) Slice

Flatten[T any, Slice ~[]T]

@Description: 多维数组转换一维
@param collection
@return Slice

func FloorToFloat added in v1.2.7

func FloorToFloat[T Float | Integer](x T, n int) float64

FloorToFloat[T Float | Integer] FloorToFloat(3.14159, 2) 3.14 FloorToFloat(5, 4) 5

@Description: 向下舍入/去尾法 保留n位
@param x
@param n
@return float64

func ForEach

func ForEach[T any](collection []T, iteratee func(item T, index int))

ForEach[T any]

@Description:循环输出
@param collection
@param iteratee

func FromEntries added in v1.2.7

func FromEntries[K comparable, V any](entries []Entry[K, V]) map[K]V

FromEntries[K comparable, V any]

@Description: 键值对数组转换map
@param entries
@param V]
@return map[K]V

func GbkToUtf8 added in v1.2.7

func GbkToUtf8(bs []byte) []byte

GbkToUtf8

@Description: gbk转换utf8
@param bs
@return []byte
@return error

func Get

func Get(u string) string

Get

@Description: get请求http
@param u
@return string

func GetAppPath

func GetAppPath() string

GetAppPath

@Description: 获取当前程序路径
@return string

func GetDate added in v1.2.7

func GetDate() string

GetDate

@Description: 日期
@return string

func GetDateTime added in v1.2.7

func GetDateTime() string

GetDateTime

@Description: 日期时间
@return string

func GetInternalIp added in v1.2.7

func GetInternalIp() string

GetInternalIp

@Description: 获取内部ipv4
@return string

func GetIps added in v1.2.7

func GetIps() []string

GetIps

@Description: 获取本地ip列表
@return []string

func GetMacAddrs added in v1.2.7

func GetMacAddrs() []string

GetMacAddrs

@Description: 获取Mac地址
@return []string

func GetOsBits

func GetOsBits() int

GetOsBits

@Description: 获取系统位数
@return int

func GetPinyin

func GetPinyin(s, sp string) (pinyin, shortpinyin string)

func GetProcessName added in v1.2.7

func GetProcessName(pid int) string

GetProcessName

@Description: 根据进程pid返回进程名称,此函数用于win,可以用来判断是否双击打开exe

GetProcessName(os.Getppid()) == "explorer.exe" 是双击 GetProcessName(os.Getpid()) 当前程序名称

@param pid
@return string

func GetTime added in v1.2.7

func GetTime() string

GetTime

@Description: 时间
@return string

func HasKey

func HasKey[K comparable, V any](in map[K]V, key K) bool

HasKey[K comparable, V any]

@Description:判断key是否存在
@param in
@param key
@return bool

func Hash

func Hash(password string, salt ...string) (ps string, err error)

func HashBytes

func HashBytes(password []byte, salt ...[]byte) (hash []byte, err error)

func HideString

func HideString(origin string, start, end int, replaceChar string) string

HideString

@Description:隐藏字符串中某些字符
@param origin
@param start 开始
@param end 结束
@param replaceChar 要替换如 *
@return string

func ImgToDebase64 added in v1.2.7

func ImgToDebase64(path, data string) (ps string)

ImgToDebase64

@Description: 图片解码base64成文件
@param path
@param data
@return ps

func ImgToEnbase64 added in v1.2.7

func ImgToEnbase64(filename string) (s string)

ImgToEnbase64

@Description: 图片文件转换成base64字符
@param filename
@return s

func IndexOf added in v1.2.7

func IndexOf[T comparable](collection []T, element T) int

IndexOf[T comparable]

@Description: 元素在数组中首次出现的索引,没有-1
@param collection
@param element
@return int

func Intersect

func Intersect[T comparable, Slice ~[]T](list1 Slice, list2 Slice) Slice

Intersect[T comparable, Slice ~[]T]

@Description: 计算交集
@param list1
@param list2
@return Slice

func Invert

func Invert[K comparable, V comparable](in map[K]V) map[V]K

Invert[K comparable, V comparable]

@Description: map键值对调
@param in
@return map[V]K

func IsASCII

func IsASCII(str string) bool

IsASCII

@Description: 是否ascii
@param str
@return bool

func IsBase64

func IsBase64(base64 string) bool

IsBase64

@Description: 是否base64
@param base64
@return bool

func IsBase64URL added in v1.2.7

func IsBase64URL(v string) bool

IsBase64URL

@Description: 是否base64url
@param v
@return bool

func IsChinese

func IsChinese(s string) bool

IsChinese

@Description: 是否包含中文
@param s
@return bool

func IsChineseIdNum

func IsChineseIdNum(id string) bool

IsChineseIdNum

@Description: 是否身份证
@param id
@return bool

func IsChineseMobile added in v1.2.7

func IsChineseMobile(mobileNum string) bool

IsChineseMobile check if the string is chinese mobile number.

@Description: 是否手机号
@param mobileNum
@return bool

func IsCreditCard added in v1.2.7

func IsCreditCard(creditCart string) bool

func IsDir

func IsDir(path string) bool

IsDir

@Description: 判断是否目录
@param path
@return bool

func IsEmail

func IsEmail(email string) bool

IsEmail

@Description: 是否email
@param email
@return bool

func IsEmpty

func IsEmpty[T comparable](v T) bool

IsEmpty[T comparable]

@Description: 判断是否为空,0,""都是空
@param v
@return bool

func IsExist

func IsExist(path string) bool

IsExist

@Description: 判断文件或目录是否存在
@param path
@return bool

func IsFloat

func IsFloat(v any) bool

IsFloat

@Description: 是否浮点数
@param v
@return bool

func IsGBK

func IsGBK(data []byte) bool

IsGBK

@Description: 是否GBK
@param data
@return bool

func IsHex added in v1.2.7

func IsHex(v string) bool

IsHex

@Description: 是否16进制
@param v
@return bool

func IsInt

func IsInt(v any) bool

IsInt

@Description: 是否整数
@param v
@return bool

func IsInternalIP added in v1.2.7

func IsInternalIP(IP net.IP) bool

IsInternalIP

@Description: 是否内网IP
@param IP
@return bool

func IsIp

func IsIp(ipstr string) bool

IsIp

@Description: 是否IP
@param ipstr
@return bool

func IsIpV6 added in v1.2.7

func IsIpV6(ipstr string) bool

IsIpV6

@Description: 是否ipv6
@param ipstr
@return bool

func IsJSON

func IsJSON(str string) bool

IsJSON

@Description: 是否json
@param str
@return bool

func IsJWT added in v1.2.7

func IsJWT(v string) bool

IsJWT

@Description: 是否jwt
@param v
@return bool

func IsLeapYear

func IsLeapYear(year int) bool

IsLeapYear

@Description: 是否闰年
@param year
@return bool
func IsLink(path string) bool

IsLink

@Description: 判断文件是否链接
@param path
@return bool

func IsLinux

func IsLinux() bool

IsLinux

@Description: 是否linux
@return bool

func IsMac

func IsMac() bool

IsMac

@Description: 是否Mac
@return bool

func IsNil added in v1.2.7

func IsNil(x any) bool

IsNil

@Description: 判断是否nil
@param x
@return bool

func IsNumber

func IsNumber(v any) bool

IsNumber

@Description: 是否数字
@param v
@return bool

func IsPublicIP added in v1.2.7

func IsPublicIP(IP net.IP) bool

IsPublicIP

@Description: 是否公网IP
@param IP
@return bool

func IsString added in v1.2.7

func IsString(v any) bool

IsString

@Description: 是否字符串
@param v
@return bool

func IsStrongPassword

func IsStrongPassword(password string, length int) bool

IsStrongPassword

@Description: 是否强密码
@param password
@param length
@return bool

func IsUrl

func IsUrl(str string) bool

IsUrl

@Description: 是否url
@param str
@return bool

func IsUtf8

func IsUtf8(s string) bool

IsUtf8

@Description: 是否utf8
@param s
@return bool

func IsWeakPassword added in v1.2.7

func IsWeakPassword(password string) bool

IsWeakPassword

@Description: 是否弱密码数字或大小写
@param password
@return bool

func IsWeixin

func IsWeixin(r *http.Request) bool

IsWeixin

@Description: 是否微信
@param r
@return bool

func IsWindows

func IsWindows() bool

IsWindows

@Description: 是否win系统
@return bool

func IsZipFile

func IsZipFile(filepath string) bool

IsZipFile

@Description: 是否zip压缩文件
@param filepath
@return bool

func Join

func Join[T any](slice []T, separator string) string

Join[T any]

@Description: 分隔符链接切片元素,切片转换字符串用分隔符链接
@param slice
@param separator
@return string

func Keys

func Keys[K comparable, V any](in ...map[K]V) []K

Keys[K comparable, V any]

@Description: 返回map的key组成的切片,去重用Uniq
@param in
@return []K

func Last

func Last[T any](collection []T, fallback T) T

func LastIndexOf added in v1.2.7

func LastIndexOf[T comparable](collection []T, element T) int

LastIndexOf[T comparable]

@Description:数组中找到值的最后一次出现的索引,如果找不到该值,则返回 -1
@param collection
@param element
@return int

func ListFileNames added in v1.2.7

func ListFileNames(path string) ([]string, error)

ListFileNames

@Description: 返回目录下所有文件名
@param path
@return []string
@return error

func MTime

func MTime(filepath string) (int64, error)

MTime

@Description: 文件修改时间戳
@param filepath
@return int64
@return error

func MapToQueryString added in v1.2.7

func MapToQueryString(param map[string]any) string

MapToQueryString

var m = map[string]any{
       "c": 3,
       "a": 1,
       "b": 2,
   }  a=1&b=2&c=3
	@Description:map转换成http查询
	@param param
	@return string

func MapToSlice

func MapToSlice[K comparable, V any, R any](in map[K]V, iteratee func(key K, value V) R) []R

MapToSlice[K comparable, V any, R any]

@Description: map转换slice
@param in
@param iteratee
@return []R

func Match

func Match(password, hash string) bool

func MatchBytes

func MatchBytes(password []byte, hash []byte) bool

func Max

func Max[T Ordered](collection []T) T

Max[T Ordered]

@Description: 切片求最大值
@param collection
@return T

func Md5

func Md5(s string) string

Md5

@Description: 计算字符串md5
@param s
@return string

func MiMeType

func MiMeType(file any) string

MiMeType

@Description: 获取文件mime类型,字符串或*os.File
@param file f, _ := os.Open("./file.go") 或"1.txt"
@return string

func Min

func Min[T Ordered](collection []T) T

Min[T Ordered]

@Description: 切片求最小值
@param collection
@return T

func Nth added in v1.2.7

func Nth[T any, N Integer](collection []T, nth N) (T, error)

Nth[T any, N Integer]

@Description: 返回索引处元素
@param collection
@param nth
@return T
@return error

func OpenURL added in v1.2.7

func OpenURL(url string)

OpenURL

@Description: 访问URL,用于cli
@param url

func Openurl

func Openurl(url string)

Openurl

@Description: 打开URL
@param url

func PasswordHash

func PasswordHash(password string) (string, error)

PasswordHash

@Description: 散列密码加密
@param password 密码
@return string 散列密码
@return error

func PasswordVerify

func PasswordVerify(password, hash string) bool

PasswordVerify

@Description: 验证散列密码
@param password 密码
@param hash 散列密码
@return bool

func Percent

func Percent(val, total float64, n int) float64

Percent

@Description: 计算百分比,保留n位小数
@param val
@param total
@param n
@return float64

func PickByKeys added in v1.2.7

func PickByKeys[K comparable, V any, Map ~map[K]V](in Map, keys []K) Map

PickByKeys[K comparable, V any, Map ~map[K]V]

@Description: 根据给定key选取map
@param in
@param keys
@return Map

func PickByValues added in v1.2.7

func PickByValues[K comparable, V comparable, Map ~map[K]V](in Map, values []V) Map

PickByValues[K comparable, V comparable, Map ~map[K]V]

@Description: 根据值选择map组成的新map
@param in
@param values
@return Map

func PointDistance

func PointDistance(x1, y1, x2, y2 float64) float64

PointDistance

@Description: 计算两个坐标距离
@param x1
@param y1
@param x2
@param y2
@return float64

func RandColor

func RandColor() string

RandColor

@Description: 随机颜色
@return string

func RandInt

func RandInt(min, max int) int

RandInt

@Description: 随机返回两个整数之间的数
@param min
@param max 不含最大值
@return int

func RandomSlice added in v1.2.7

func RandomSlice[T any, Slice ~[]T](collection Slice, count int) Slice

RandomSlice[T any, Slice ~[]T]

@Description:数组中随机返回n个元素
@param collection
@param count
@return Slice

func RandomString

func RandomString(size int) string

RandomString

@Description:随机字符串,不包含oO
@param size
@param charset
@return string

func Range

func Range[T Integer | Float](start, end, step T) []T

Range[T Integer | Float]

@Description: 生成数组
@param start
@param end
@param step 步长
@return []T

func ReadCsvFile

func ReadCsvFile(filepath string, delimiter ...rune) ([][]string, error)

ReadCsvFile

@Description: 读取csv文件
@param filepath
@param delimiter
@return [][]string
@return error

func ReadFile

func ReadFile(path string) (reader io.ReadCloser, closeFn func(), err error)

ReadFile reader, fn, err := fileutil.ReadFile("https://httpbin.org/robots.txt")

   if err != nil {
       return
   }
   defer fn()

   dat, err := io.ReadAll(reader)
   if err != nil {
       return
   }

   fmt.Println(string(dat))
	@Description: 读取文件或URL文件
	@param path
	@return reader
	@return closeFn
	@return err

func ReadFileByLine

func ReadFileByLine(path string) ([]string, error)

ReadFileByLine

@Description:按行读取文件内容
@param path
@return []string
@return error

func ReadFileToString added in v1.2.7

func ReadFileToString(path string) (string, error)

ReadFileToString

@Description: 读取文件到字符串
@param path
@return string
@return error

func RemoveFile

func RemoveFile(path string) error

RemoveFile

@Description: 删除文件
@param path
@return error

func Replace added in v1.2.7

func Replace[T comparable, Slice ~[]T](collection Slice, old T, new T, n int) Slice

Replace[T comparable, Slice ~[]T]

@Description: 替换元素
@param collection
@param old
@param new
@param n -1是全部替换
@return Slice

func Reverse

func Reverse[T any, Slice ~[]T](collection Slice) Slice

Reverse[T any, Slice ~[]T]

@Description: 反序数组
@param collection
@return Slice

func RoundToFloat

func RoundToFloat[T Float | Integer](x T, n int) float64

RoundToFloat[T Float | Integer]

@Description: 四舍五入返回 float64
@param x
@param n 保留小数位数
@return float64

func RoundToString

func RoundToString[T Float | Integer](x T, n int) string

RoundToString[T Float | Integer]

@Description: 四舍五入到字符串
@param x
@param n
@return string

func RuneLength

func RuneLength(str string) int

RuneLength

@Description: 中文字符统计
@param str
@return int

func Salt

func Salt(rounds ...int) (string, error)

Salt generation

func SaltBytes

func SaltBytes(rounds ...int) (salt []byte, err error)

func Sha added in v1.2.7

func Sha(filepath string, shaType ...int) (string, error)

Sha

@Description: 返回文件sha值,参数`shaType` 应传值为: 1, 256,512
@param filepath
@param shaType
@return string
@return error

func Sha1

func Sha1(str string) string

Sha1

@Description: 计算sha1值
@param str
@return string

func Sha256

func Sha256(str string) string

Sha256

@Description: sha256字符串值
@param str
@return string

func Sha512 added in v1.2.7

func Sha512(str string) string

Sha512

@Description: sha512值
@param str
@return string

func Shuffle

func Shuffle[T any, Slice ~[]T](collection Slice) Slice

Shuffle[T any, Slice ~[]T]

@Description: 洗牌打乱数组
@param collection
@return Slice

func Slice added in v1.2.7

func Slice[T any, Slice ~[]T](collection Slice, start int, end int) Slice

Slice[T any, Slice ~[]T]

@Description: 截取切片,不包括结尾索引
@param collection
@param start
@param end
@return Slice

func SliceToMap

func SliceToMap[T any, K comparable, V any](collection []T, transform func(item T) (K, V)) map[K]V

SliceToMap[T any, K comparable, V any]

@Description: slice转换map
@param collection
@param transform
@return map[K]V

func Sort

func Sort[T Ordered](slice []T, sortOrder ...string)

Sort[T Ordered]

@Description: 切片排序,数组排序
@param slice
@param sortOrder

func Splice added in v1.2.7

func Splice[T any, Slice ~[]T](collection Slice, i int, elements ...T) Slice

Splice[T any, Slice ~[]T]

@Description: 在索引处插入多个值
@param collection
@param i
@param elements
@return Slice

func SplitEx added in v1.2.7

func SplitEx(s, sep string, removeEmptyString bool) []string

SplitEx

@Description: 字符串分割为切片
@param s
@param sep 分隔符号
@param removeEmptyString 是否移除空字符串
@return []string

func String

func String(t Transformer, s string) (result string, n int, err error)

String returns a string with the result of converting s[:n] using t, where n <= len(s). If err == nil, n will be len(s). It calls Reset on t.

func StripTags

func StripTags(content string) string

StripTags

@Description: 去除HTML中标签
@param content
@return string

func Subset added in v1.2.7

func Subset[T any, Slice ~[]T](collection Slice, offset int, length uint) Slice

Subset[T any, Slice ~[]T]

@Description: slice截取
@param collection
@param offset 开始
@param length 长度
@return Slice

func Substring

func Substring(s string, offset int, length uint) string

Substring[T ~string]

@Description: 子字符串截取
@param str
@param offset
@param length
@return T

func Sum

func Sum[T Float | Integer | Complex](collection []T) T

Sum[T Float | Integer | Complex]

@Description: 数组求和
@param collection
@return T

func TableToSlice added in v1.2.7

func TableToSlice(s string) [][]string

TableToSlice

@Description: html表格转换切片,去除html标签
@param s
@return [][]string

func Ternary

func Ternary[T any](condition bool, ifOutput T, elseOutput T) T

Ternary[T any]

@Description:三元运算,相当于if-else,是语句
@param condition
@param ifOutput
@param elseOutput
@return T

func TernaryF

func TernaryF[T any](condition bool, ifFunc func() T, elseFunc func() T) T

TernaryF[T any]

@Description: 三元运算,是函数
@param condition
@param ifFunc
@param elseFunc
@return T

func TimeAddDay added in v1.2.7

func TimeAddDay(t time.Time, day int64) time.Time

TimeAddDay

@Description: 加减日期,实现昨天明天
@param t
@param day
@return time.Time

func TimeAddHour added in v1.2.7

func TimeAddHour(t time.Time, hour int64) time.Time

TimeAddHour add or sub hour to the time.

@Description: 添加减少小时
@param t
@param hour
@return time.Time

func TimeAddMinute added in v1.2.7

func TimeAddMinute(t time.Time, minute int64) time.Time

TimeAddMinute

@Description: 添加减少分钟
@param t
@param minute
@return time.Time

func TimeAddYear added in v1.2.7

func TimeAddYear(t time.Time, year int64) time.Time

TimeAddYear

@Description: 添加减少年
@param t
@param year
@return time.Time

func TimeDaysBetween added in v1.2.7

func TimeDaysBetween(start, end time.Time) int

TimeDaysBetween

@Description: 日期之间天数差
@param start
@param end
@return int

func TimeLine

func TimeLine(t int64) string

TimeLine

@Description: 时间戳友好显示
@param t
@return string

func TimeToStr added in v1.2.7

func TimeToStr(t time.Time, format string, timezone ...string) string

TimeToStr

@Description: 时间转换字符串格式化
@param t
@param format
@param timezone
@return string

func Times added in v1.2.7

func Times[T any](count int, iteratee func(index int) T) []T

Times[T any]

@Description: 调用多次迭代
@param count
@param iteratee
@return []T

func Timestamp added in v1.2.7

func Timestamp(timezone ...string) int64

Timestamp

@Description: 当前秒级时间戳
@param timezone
@return int64

func TimestampToStr added in v1.2.7

func TimestampToStr(t int64) string

TimestampToStr

@Description: 时间戳转换时间字符串
@param t
@return string

func TimestampToTime added in v1.2.7

func TimestampToTime(t int64) time.Time

TimestampToTime

@Description: 时间戳转换go时间
@param t
@return time.Time

func TimestrToTime added in v1.2.7

func TimestrToTime(str, format string, timezone ...string) (time.Time, error)

TimestrToTime

@Description: 字符串转换go时间格式
@param str
@param format
@param timezone
@return time.Time
@return error

func TimestrToTimestamp added in v1.2.7

func TimestrToTimestamp(s string) int64

TimestrToTimestamp

@Description: 时间字符串转换时间戳
@param s
@return int64

func ToAnySlice added in v1.2.7

func ToAnySlice[T any](collection []T) []any

ToAnySlice[T any]

@Description: 转换成any类型切片
@param collection
@return []any

func ToBits added in v1.2.7

func ToBits(s uint64) string

ToBits

@Description: 字节格式化
@param s
@return string

func ToBool

func ToBool(s string) (bool, error)

ToBool

@Description: 转换成布尔
@param s
@return bool
@return error

func ToBytes

func ToBytes(value any) ([]byte, error)

ToBytes

@Description: 转换成字节切片
@param value
@return []byte
@return error

func ToChar

func ToChar(s string) []string

ToChar

@Description: 转换字符切片
@param s
@return []string

func ToFloat

func ToFloat(value any) (float64, error)

ToFloat

@Description: 转换float
@param value
@return float64
@return error

func ToInt

func ToInt(value any) (int64, error)

ToInt

@Description: 转换int
@param value
@return int64
@return error

func ToJson

func ToJson(value any) (string, error)

ToJson

@Description: 转换json
@param value
@return string
@return error

func ToSlice added in v1.2.7

func ToSlice[T any](items ...T) []T

ToSlice[T any]

@Description: 字符转换成切片
@param items
@return []T

func ToString

func ToString(value any) string

ToString

@Description: 任意类型转换字符串
@param value
@return string

func ToUrlBase64 added in v1.2.7

func ToUrlBase64(value any) string

ToUrlBase64

@Description: 转换成urlbase64
@param value
@return string

func Trim

func Trim(str string, characterMask ...string) string

Trim

@Description: 去除字符串两边空格
@param str
@param characterMask 可指定其他去除字符
@return string

func TruncRound

func TruncRound[T Float | Integer](x T, n int) T

TruncRound[T Float | Integer]

@Description: 截断n位小数不四舍五入
@param x
@param n
@return T

func Typeof

func Typeof(a any) reflect.Type

Typeof

@Description: 返回变量类型
@param a
@return reflect.Type

func UnZip

func UnZip(zipFile string, destPath string) error

UnZip

@Description: 解压zip
@param zipFile
@param destPath
@return error

func UnicodeToUtf8 added in v1.2.7

func UnicodeToUtf8(str string) string

UnicodeToUtf8 @Description: unicode转换utf8 @param str @return string utf8

func Union

func Union[T comparable, Slice ~[]T](lists ...Slice) Slice

Union[T comparable, Slice ~[]T]

@Description: 并集
@param lists
@return Slice

func Uniq

func Uniq[T comparable, Slice ~[]T](collection Slice) Slice

Uniq[T comparable, Slice ~[]T]

@Description:返回数组的无重复版本
@param collection
@return Slice

func UniqBy added in v1.2.7

func UniqBy[T any, U comparable, Slice ~[]T](collection Slice, iteratee func(item T) U) Slice

UniqBy[T any, U comparable, Slice ~[]T]

@Description: 返回无重复数组处理后结果
@param collection
@param iteratee
@return Slice

func Uniqid

func Uniqid(prefix string) string

Uniqid

@Description: 生成时间戳随机字符串
@param prefix 前缀
@return string

func Utf8ToGbk added in v1.2.7

func Utf8ToGbk(bs []byte) []byte

Utf8ToGbk

@Description: uft8转gbk
@param bs
@return []byte
@return error

func Utf8ToUnicode added in v1.2.7

func Utf8ToUnicode(str string) string

Utf8ToUnicode

@Description: uft8转换unicode
@param str
@return string

func ValueOr added in v1.2.7

func ValueOr[K comparable, V any](in map[K]V, key K, fallback V) V

ValueOr[K comparable, V any]

@Description: 根据key返回map值,不存在返回默认值
@param in
@param key
@param fallback 默认值
@return V

func Values

func Values[K comparable, V any](in ...map[K]V) []V

Values[K comparable, V any]

@Description: 返回map的val组成的新切片
@param in
@return []V

func WriteBytesToFile added in v1.2.7

func WriteBytesToFile(filepath string, content []byte) error

WriteBytesToFile

@Description: bytes写入文件
@param filepath
@param content
@return error

func WriteCsvFile

func WriteCsvFile(filepath string, records [][]string, append bool, delimiter ...rune) error

WriteCsvFile

data := [][]string{
       {"Lili", "22", "female"},
       {"Jim", "21", "male"},
   }
	@Description: 写入csv文件
	@param filepath
	@param records
	@param append 是否追加
	@param delimiter
	@return error

func WriteMapsToCsv added in v1.2.7

func WriteMapsToCsv(filepath string, records []map[string]any, appendToExistingFile bool, delimiter rune,
	headers ...[]string) error

WriteMapsToCsv

	@Description: 将map切片写入csv文件中
	@param filepath
	@param records []map[string]any{
       {"Name": "Lili", "Age": "22", "Gender": "female"},
       {"Name": "Jim", "Age": "21", "Gender": "male"},
   }
	@param appendToExistingFile 是否追加
	@param delimiter 分隔符号 ;
	@param headers []string{"Name", "Age", "Gender"}
	@return error

func WriteStringToFile added in v1.2.7

func WriteStringToFile(filepath string, content string, append bool) error

WriteStringToFile

@Description: 写字符串到文件
@param filepath
@param content
@param append
@return error

func Zip

func Zip(path string, destPath string) error

Zip

@Description: 压缩文件或目录到zip
@param path
@param destPath
@return error

func ZipAppendEntry

func ZipAppendEntry(fpath string, destPath string) error

ZipAppendEntry

@Description: 通过将单个文件或目录追加到现有的zip文件
@param fpath
@param destPath
@return error

Types

type Complex

type Complex interface {
	~complex64 | ~complex128
}

type Decoder

type Decoder struct {
	Transformer
	// contains filtered or unexported fields
}

A Decoder converts bytes to UTF-8. It implementsTransformer.

Transforming source bytes that are not of that encoding will not result in an error per se. Each byte that cannot be transcoded will be represented in the output by the UTF-8 encoding of '\uFFFD', the replacement rune.

func (*Decoder) Bytes

func (d *Decoder) Bytes(b []byte) ([]byte, error)

Bytes converts the given encoded bytes to UTF-8. It returns the converted bytes or nil, err if any error occurred.

func (*Decoder) Reader

func (d *Decoder) Reader(r io.Reader) io.Reader

Reader wraps another Reader to decode its bytes.

The Decoder may not be used for any other operation as long as the returned Reader is in use.

func (*Decoder) String

func (d *Decoder) String(s string) (string, error)

String converts the given encoded string to UTF-8. It returns the converted string or "", err if any error occurred.

type Encoder

type Encoder struct {
	Transformer
	// contains filtered or unexported fields
}

An Encoder converts bytes from UTF-8. It implementsTransformer.

Each rune that cannot be transcoded will result in an error. In this case, the transform will consume all source byte up to, not including the offending rune. Transforming source bytes that are not valid UTF-8 will be replaced by `\uFFFD`. To return early with an error instead, useChain to preprocess the data with a UTF8Validator.

func HTMLEscapeUnsupported

func HTMLEscapeUnsupported(e *Encoder) *Encoder

HTMLEscapeUnsupported wraps encoders to replace source runes outside the repertoire of the destination encoding with HTML escape sequences.

This wrapper exists to comply to URL and HTML forms requiring a non-terminating legacy encoder. The produced sequences may lead to data loss as they are indistinguishable from legitimate input. To avoid this issue, use UTF-8 encodings whenever possible.

func ReplaceUnsupported

func ReplaceUnsupported(e *Encoder) *Encoder

ReplaceUnsupported wraps encoders to replace source runes outside the repertoire of the destination encoding with an encoding-specific replacement.

This wrapper is only provided for backwards compatibility and legacy handling. Its use is strongly discouraged. Use UTF-8 whenever possible.

func (*Encoder) Bytes

func (e *Encoder) Bytes(b []byte) ([]byte, error)

Bytes converts bytes from UTF-8. It returns the converted bytes or nil, err if any error occurred.

func (*Encoder) String

func (e *Encoder) String(s string) (string, error)

String converts a string from UTF-8. It returns the converted string or "", err if any error occurred.

func (*Encoder) Writer

func (e *Encoder) Writer(w io.Writer) io.Writer

Writer wraps another Writer to encode its UTF-8 output.

The Encoder may not be used for any other operation as long as the returned Writer is in use.

type Encoding

type Encoding interface {
	// NewDecoder returns a Decoder.
	NewDecoder() *Decoder

	// NewEncoder returns an Encoder.
	NewEncoder() *Encoder
}

第二波

var (
	GBK Encoding = &gbk
)
var Replacement Encoding = replacement{}

Replacement is the replacement encoding. Decoding from the replacement encoding yields a single '\uFFFD' replacement rune. Encoding from UTF-8 to the replacement encoding yields the same as the source bytes except that invalid UTF-8 is converted to '\uFFFD'.

It is defined at http://encoding.spec.whatwg.org/#replacement

type Encoding1

type Encoding1 struct {
	Encoding
	Name string
	MIB  MIB
}

func (*Encoding1) ID

func (e *Encoding1) ID() (mib MIB, other string)

func (*Encoding1) String

func (e *Encoding1) String() string

type Entry added in v1.2.7

type Entry[K comparable, V any] struct {
	Key   K
	Value V
}

func Entries added in v1.2.7

func Entries[K comparable, V any](in map[K]V) []Entry[K, V]

Entries[K comparable, V any]

@Description: map键值对转换数组
@param in
@return []Entry[K
@return V]

type Float

type Float interface {
	~float32 | ~float64
}

type FuncEncoding

type FuncEncoding struct {
	Decoder func() Transformer
	Encoder func() Transformer
}

FuncEncoding is an Encoding that combines two functions returning a new Transformer.

func (FuncEncoding) NewDecoder

func (e FuncEncoding) NewDecoder() *Decoder

func (FuncEncoding) NewEncoder

func (e FuncEncoding) NewEncoder() *Encoder

type Integer

type Integer interface {
	Signed | Unsigned
}

type Interface

type Interface interface {
	// ID returns an encoding identifier. Exactly one of the mib and other
	// values should be non-zero.
	//
	// In the usual case it is only necessary to indicate the MIB code. The
	// other string can be used to specify encodings for which there is no MIB,
	// such as "x-mac-dingbat".
	//
	// The other string may only contain the characters a-z, A-Z, 0-9, - and _.
	ID() (mib MIB, other string)
}

----------------------------------

type MIB

type MIB uint16

A MIB identifies an encoding. It is derived from the IANA MIB codes and adds some identifiers for some encodings that are not covered by the IANA standard.

See http://www.iana.org/assignments/ianacharset-mib.

const (
	Unofficial MIB = 10000 + iota
)

These additional MIB types are not defined in IANA. They are added because they are common and defined within the text repo.

type Map

type Map = map[string]any

type MapIntAny added in v1.2.7

type MapIntAny = map[int]any

type MapIntInt added in v1.2.7

type MapIntInt = map[int]int

type MapIntStr added in v1.2.7

type MapIntStr = map[int]string

type MapStrAny added in v1.2.7

type MapStrAny = map[string]any

type MapStrInt added in v1.2.7

type MapStrInt = map[string]int

type MapStrStr added in v1.2.7

type MapStrStr = map[string]string

type NopResetter

type NopResetter struct{}

NopResetter can be embedded by implementations of Transformer to add a nop Reset method.

func (NopResetter) Reset

func (NopResetter) Reset()

Reset implements the Reset method of the Transformer interface.

type Ordered

type Ordered interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64 |
		~string
}

type Reader

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

Reader wraps another io.Reader by transforming the bytes read.

func NewReader

func NewReader(r io.Reader, t Transformer) *Reader

NewReader returns a new Reader that wraps r by transforming the bytes read via t. It calls Reset on t.

func (*Reader) Read

func (r *Reader) Read(p []byte) (int, error)

Read implements the io.Reader interface.

type RepertoireError

type RepertoireError byte

A RepertoireError indicates a rune is not in the repertoire of a destination encoding. It is associated with an encoding-specific suggested replacement byte.

func (RepertoireError) Error

func (r RepertoireError) Error() string

Error implements the error interrface.

func (RepertoireError) Replacement

func (r RepertoireError) Replacement() byte

Replacement returns the replacement string associated with this error.

type Signed

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

type SimpleEncoding

type SimpleEncoding struct {
	Decoder Transformer
	Encoder Transformer
}

SimpleEncoding is an Encoding that combines two Transformers.

func (*SimpleEncoding) NewDecoder

func (e *SimpleEncoding) NewDecoder() *Decoder

func (*SimpleEncoding) NewEncoder

func (e *SimpleEncoding) NewEncoder() *Encoder

type SpanningTransformer

type SpanningTransformer interface {
	Transformer

	// Span returns a position in src such that transforming src[:n] results in
	// identical output src[:n] for these bytes. It does not necessarily return
	// the largest such n. The atEOF argument tells whether src represents the
	// last bytes of the input.
	//
	// Callers should always account for the n bytes consumed before
	// considering the error err.
	//
	// A nil error means that all input bytes are known to be identical to the
	// output produced by the Transformer. A nil error can be returned
	// regardless of whether atEOF is true. If err is nil, then n must
	// equal len(src); the converse is not necessarily true.
	//
	// ErrEndOfSpan means that the Transformer output may differ from the
	// input after n bytes. Note that n may be len(src), meaning that the output
	// would contain additional bytes after otherwise identical output.
	// ErrShortSrc means that src had insufficient data to determine whether the
	// remaining bytes would change. Other than the error conditions listed
	// here, implementations are free to report other errors that arise.
	//
	// Calling Span can modify the Transformer state as a side effect. In
	// effect, it does the transformation just as calling Transform would, only
	// without copying to a destination buffer and only up to a point it can
	// determine the input and output bytes are the same. This is obviously more
	// limited than calling Transform, but can be more efficient in terms of
	// copying and allocating buffers. Calls to Span and Transform may be
	// interleaved.
	Span(src []byte, atEOF bool) (n int, err error)
}

SpanningTransformer extends the Transformer interface with a Span method that determines how much of the input already conforms to the Transformer.

type Transformer

type Transformer interface {
	// Transform writes to dst the transformed bytes read from src, and
	// returns the number of dst bytes written and src bytes read. The
	// atEOF argument tells whether src represents the last bytes of the
	// input.
	//
	// Callers should always process the nDst bytes produced and account
	// for the nSrc bytes consumed before considering the error err.
	//
	// A nil error means that all of the transformed bytes (whether freshly
	// transformed from src or left over from previous Transform calls)
	// were written to dst. A nil error can be returned regardless of
	// whether atEOF is true. If err is nil then nSrc must equal len(src);
	// the converse is not necessarily true.
	//
	// ErrShortDst means that dst was too short to receive all of the
	// transformed bytes. ErrShortSrc means that src had insufficient data
	// to complete the transformation. If both conditions apply, then
	// either error may be returned. Other than the error conditions listed
	// here, implementations are free to report other errors that arise.
	Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error)

	// Reset resets the state and allows a Transformer to be reused.
	Reset()
}

Transformer transforms bytes.

func Chain

func Chain(t ...Transformer) Transformer

Chain returns a Transformer that applies t in sequence.

func RemoveFunc deprecated

func RemoveFunc(f func(r rune) bool) Transformer

Deprecated: Use runes.Remove instead.

type Unsigned

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}

type Writer

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

Writer wraps another io.Writer by transforming the bytes read. The user needs to call Close to flush unwritten bytes that may be buffered.

func NewWriter

func NewWriter(w io.Writer, t Transformer) *Writer

NewWriter returns a new Writer that wraps w by transforming the bytes written via t. It calls Reset on t.

func (*Writer) Close

func (w *Writer) Close() error

Close implements the io.Closer interface.

func (*Writer) Write

func (w *Writer) Write(data []byte) (n int, err error)

Write implements the io.Writer interface. If there are not enough bytes available to complete a Transform, the bytes will be buffered for the next write. Call Close to convert the remaining bytes.

Jump to

Keyboard shortcuts

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