yo

package
v2.0.1+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2023 License: MIT Imports: 38 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 ConfirmNoRegex = regexp.MustCompile(`^(?i)no?$`)
View Source
var ConfirmRejection = "<warn>Please respond with \"y\" or \"n\"\n\n"
View Source
var ConfirmYesRegex = regexp.MustCompile(`^(?i)y(es)?$`)
View Source
var (
	// DefaultTrimChars are the characters which are stripped by Trim* functions in default.
	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 RenderChooseOption = func(key, value string, size int) string {
	return fmt.Sprintf("%-"+fmt.Sprintf("%d", size+1)+"s %s\n", key+")", value)
}
View Source
var RenderChooseQuery = func() string {
	return "Choose: "
}
View Source
var RenderChooseQuestion = func(question string) string {
	return question + "\n"
}

cli选择

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 AesDe

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

aes解密 支持aes128 aes192 aes256

func AesEn

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

*

  • @Description: Aes加密
  • @param text
  • @param key ,分别代表AES-128, AES-192和 AES-256
  • @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 Ask

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

*

  • @Description: cli实现提示输入 qq:=php.Ask("请输入",nil)
  • @param str 提示字符串
  • @param check nil
  • @return string

func Associate

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

Associate[T any, K comparable, V any]

@Description: scile处理成map

Associate([]string("a","bb","cc"), func(str string) (string, int) {
	return str, len(str)
})

@param collection
@param transform
@return map[K]V

func Authcode

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

*

  • @Description: 对称加密解密函数
  • @param text 要加密或解密字符串
  • @param false解码 true加密

密钥 字符串 s:=php.Authcode("1234==+wo我们",true,"abc") s=php.Authcode(s,false,"abc")

  • @return string

func Average

func Average[T Integer | Float](numbers ...T) T

平均数

func Base642Img

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

*

  • @Description: base64还原成图片
  • @param path 当前 . qq/ss 最后不要带/
  • @param data 上传的base64
  • @return ps 路径

func Base64Decode

func Base64Decode(s string, isurl bool) string

*

  • @Description: 解码base64 str=php.Base64Decode(str,false)
  • @param s 要解码字符串
  • @param isurl 是否url
  • @return string

func Base64Encode

func Base64Encode(s string, isurl bool) (s1 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 Choose

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

*

  • @Description: cli选择
  • @param question 提示内容
  • @param choices map[string]string{ "1": "苹果", "2": "橘子", "3": "西瓜", }
  • @return string 返回key

func Chunk

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

Chunk[T any] Chunk([]int(1,2,3,4), 2) [1,2] [3,4]

@Description: 分割数组,切片,按照个数组成新的切片
@param collection
@param size
@return [][]T

func ChunkString

func ChunkString[T ~string](str T, size int) []T

ChunkString[T ~string] ChunkString("123456", 2) [1,2][3,4][5,6]

@Description: 分割字符串
@param str
@param size
@return []T

func ColorHexToRGB

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

颜色值十六进制转 rgb

func ColorRGBToHex

func ColorRGBToHex(red, green, blue int) string

颜色值 rgb 转十六进制

func Compact

func Compact[T comparable](collection []T) []T

Compact[T comparable] []string{"", "foo", "", "bar", ""} 返回["foo","bar"]

@Description: 返回非空切片的新切片
@param collection
@return []T

func Confirm

func Confirm(question string) bool

*

  • @Description: cli选择yes/no
  • @param question 提示内容支持回复 yes y/no n
  • @return bool

func Contain

func Contain[T comparable](slice []T, target T) bool

Contains[T comparable]

@Description: 判断sclie是否包含元素
@param collection
@param element
@return bool

func ContainSubSlice

func ContainSubSlice[T comparable](slice, subSlice []T) bool

是否包含子切片

func CopyFile

func CopyFile(srcPath string, dstPath string) error

拷贝文件,会覆盖原有的文件

func CreateDir

func CreateDir(absPath string) error

创建嵌套目录,例如/a/, /a/b/

func CreateFile

func CreateFile(path string) bool

创建文件,创建成功返回 true, 否则返回 false

func CurrentPath

func CurrentPath() string

返回绝对路径

func Date

func Date(format string, ts ...time.Time) string

Date

@Description: 格式化时间
@param format Y-m-d H:i:s
@param ts 事件类型
@return string

func DownloadFile

func DownloadFile(filepath string, url string) error

下载文件

func Drop

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

Drop[T any]

@Description: 删除scile元素,左边开始,返回新的
@param collection
@param n
@return []T

func DropRight

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

从右边删除,返回删除后的新切片

func DropRightWhile

func DropRightWhile[T any](collection []T, predicate func(item T) bool) []T

右边条件删除

func DropWhile

func DropWhile[T any](collection []T, predicate func(item T) bool) []T

DropWhile[T any]

@Description: 左边开始条件删除
@param collection
DropWhile(list, func(val int) bool {
	return val > 2
})
@return []T

func Emoji

func Emoji(s string) (ss string)

*

  • @Description: emoji编码成实体直接输出不需要转码
  • @param s
  • @return ss

func EmojiDecode

func EmojiDecode(s string) string

*

  • @Description: 解码emoji网页上显示
  • @param s
  • @return string

func EmojiEncode

func EmojiEncode(s string) string

*

  • @Description: 编码emoji成unicode
  • @param s
  • @return string

func Empty

func Empty[T any]() T

func EncodeUrl

func EncodeUrl(urlStr string) (string, error)

编码URL

func Err

func Err(err error)

显示错误

func FileCount

func FileCount(sizes int64) string

FileCount

@Description: 文件格式化
@param sizes
@return string

func FileSize

func FileSize(path string) (int64, error)

文件大小 字节

func Filter

func Filter[V any](collection []V, predicate func(item V, index int) bool) []V

Filter[V any] Filter([]int64{1, 2, 3, 4},func(a int64,i int)bool{ 返回被2整除 return a%2 ==0 })

@Description:刷选集合中元素
@param collection
@param predicate
@return []V

func FilterMap

func FilterMap[K comparable, V any](m map[K]V, predicate func(key K, value V) bool) map[K]V

func Flatten

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

Flatten[T any] [][]int{{0, 1, 2}, {3, 4, 5}}=> [0,1,2,3,4,5]

@Description: 转换数组维度
@param collection
@return []T

func ForEach

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

ForEach[T any]

@Description: scile循环处理
@param collection item值 index是key
@param iteratee

func ForEachMap

func ForEachMap[K comparable, V any](m map[K]V, iteratee func(key K, value V))

处理map

func Gbk2Utf8

func Gbk2Utf8(gbkStr string) string

*

  • @Description: 将GBK编码的字符串转换为utf-8编码
  • @param gbkStr
  • @return string

func Get

func Get(u string) string

*

  • @Description: GET请求,支持gzip
  • @param u 网址
  • @return string

func GetAppPath

func GetAppPath() string

获取exe路径

func GetIp

func GetIp() string

GetIp

@Description: 获取IP
@return string

func GetOsBits

func GetOsBits() int

获取当前操作系统位数(32/64)

func GetPinyin

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

获取汉字拼音,支持返回全拼音和拼音首字母,同时支持sp分隔符 php.GetPinyin(s,"")

func GetWeekday

func GetWeekday(ri string) string

根据年月日判断星期 2021-03-17

func HasKey

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

HasKey[K comparable, V any]

@Description:检查 map 是否包含某个 key
@param m mp := map[string]string{"a": "中国", "b": "日本"}
fmt.Println(yo.HasKey(mp, "a"))
@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 HideTel

func HideTel(phone string) (str string)

*

  • @Description: 隐藏手机中间四位或电话中间四位
  • @param phone 手机号 182XXXX7788
  • @return str

func HtmlDecode

func HtmlDecode(s string) string

*

  • @Description: html实体字符串还原
  • @param s
  • @return string

func HtmlEncode

func HtmlEncode(s string) string

*

  • @Description: html字符串转换实体
  • @param s
  • @return string

func Img2Base64

func Img2Base64(filename string) (s string)

*

  • @Description: 图片转换成base64

filename:="1.jpg" s:=php.Img2Base64(filename)

  • @param filename
  • @return s

func InsertAt

func InsertAt[T any](slice []T, index int, value any) []T

InsertAt[T any]

@Description: 在scile索引位置插入值
@param slice
@param index
@param value
@return []T

func Intersect

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

Intersect[T comparable] list1 := []int{0, 1, 2, 3, 4, 3}

list2 := []int{3, 4, 3}
@Description: 两个切片 交集
@param list1
@param list2
@return []T

func Invert

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

Invert[K comparable, V comparable] kv := map[string]int{"foo": 1, "bar": 2, "baz": 3, "new": 3}

@Description: 键值交换
@param in
@return map[V]K

func IsASCII

func IsASCII(str string) bool

func IsAsc

func IsAsc[T Ordered](slice []T) bool

是否升序

func IsBase64

func IsBase64(base64 string) bool

func IsChinese

func IsChinese(s string) bool

func IsChineseIdNum

func IsChineseIdNum(id string) bool

是否身份证

func IsDesc

func IsDesc[T Ordered](slice []T) bool

是否降序

func IsDir

func IsDir(path string) bool

判断参数是否是目录

func IsEmail

func IsEmail(email string) 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

判断文件或目录是否存在

func IsFloat

func IsFloat(v any) bool

是否浮点

func IsGBK

func IsGBK(data []byte) bool

func IsInt

func IsInt(v any) bool

是否整数

func IsIp

func IsIp(ipstr string) bool

func IsJSON

func IsJSON(str string) bool

func IsLeapYear

func IsLeapYear(year int) bool

是否闰年

func IsLinux

func IsLinux() bool

func IsMac

func IsMac() bool

func IsMobile

func IsMobile(mobileNum string) bool

是否手机号

func IsNumber

func IsNumber(v any) bool

是否是数字

func IsSorted

func IsSorted[T Ordered](slice []T) bool

检查切片元素是否是有序的(升序或降序)

func IsStrongPassword

func IsStrongPassword(password string, length int) bool

验证字符串是否是强密码:(字母+数字+特殊字符)

func IsUrl

func IsUrl(str string) bool

func IsUtf8

func IsUtf8(s string) bool

func IsWeekend

func IsWeekend(t time.Time) bool

判断是否周日

func IsWeixin

func IsWeixin(r *http.Request) bool

func IsWindows

func IsWindows() bool

func IsZipFile

func IsZipFile(filepath string) bool

判断是否zip

func Join

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

Join[T any]

@Description:用指定的分隔符链接切片元素
@param slice 切片转换字符串
@param separator Join(nums, ",")
@return string

func Keys

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

------------------字典开始----------------------- Keys[K comparable, V any]

@Description: 返回字典key
@param in
@return []K

func Last

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

Last[T any]

@Description: 返回最后一个值
@param collection
@return T
@return error

func ListFile

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

目录下所有文件名称

func MTime

func MTime(filepath string) (int64, error)

文件修改时间戳

func Map

func Map[T any, U any](slice []T, iteratee func(index int, item T) U) []U

Map[T any, U any]

@Description:对 slice 中的每个元素执行 map 函数以创建一个新切片
@param slice Map(nums,func(_ int, v int) int {
	return v + 1
})
@param iteratee
@return []U

func Map2Http

func Map2Http(param map[string]any) string

Map2Http

@Description: map转换成http字符串
@param param map 转换成a=1&b=2&c=3
@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转换scile,可以自己处理逻辑
@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

func Md5

func Md5(s string) string

func Merge

func Merge[T any](slices ...[]T) []T

Merge[T any]

@Description: 合并多个切片,同元素存在
@param slices
@return []T

func MergeMap

func MergeMap[K comparable, V any](maps ...map[K]V) map[K]V

合并多个map

func MiMeType

func MiMeType(file any) string

获取文件 mime 类型, 参数的类型必须是 string 或者*os.File

func MicroTime

func MicroTime() float64

*

  • @Description: 返回当前 Unix 时间戳和微秒数
  • @return float64

func Min

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

func NumberFormat

func NumberFormat(number float64, decimals int, decPoint, thousandsSep string) string

*

  • @Description: 四舍五入,分割字符
  • @param number 浮点数
  • @param decimals 保留位数2
  • @param decPoint .
  • @param thousandsSep , 分隔符
  • @return string

func Openurl

func Openurl(url string)

访问url

func PasswordHash

func PasswordHash(password string) (string, error)

*

  • @Description: 创建密码散列,password 密码
  • @param password 要加密字符串
  • @return string
  • @return error

func PasswordVerify

func PasswordVerify(password, hash string) bool

*

  • @Description: 验证密码,密码和密码散列
  • @param password 密码
  • @param hash 上面生成的散列密码
  • @return bool

func Percent

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

计算百分比

func PointDistance

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

计算两坐标点距离

func RandColor

func RandColor() string

*

  • @Description: 生成随机颜色
  • @return string

func RandInt

func RandInt(min, max int) int

随机一个值

func RandomString

func RandomString(size int, charset []rune) string

RandomString

@Description: 随机字符串
@param size 长度
@param charset
@return string

func Range

func Range[T Integer | Float](start T, elementNum int) []T

Range[T Integer | Float]

@Description: 生成数组
@param start Range(1,5)
@param elementNum
@return []T

func RangeWithStep

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

根据指定的起始值,结束值,步长,创建一个数字切片

func ReadCsvFile

func ReadCsvFile(filepath string) ([][]string, error)

读取csv

func ReadFile

func ReadFile(path string) (string, error)

读文件

func ReadFileByLine

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

按行读取文件内容,返回字符串切片包含每一行

func RemoveFile

func RemoveFile(path string) error

删除文件

func Reverse

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

Reverse[T any]

@Description: sclie反序
@param collection
@return []T

func RoundToFloat

func RoundToFloat(x float64, n int) float64

四舍五入到字符串

func RoundToString

func RoundToString(x float64, n int) string

四舍五入到 float64 n位保留

func RuneLength

func RuneLength(str string) int

RuneLength

@Description: 计算中文字符长度,len中文算3个,这个算1个
@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 Sample

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

Sample[T any]

@Description: 随机返回一个值

[]int64{1,2,3}

@param collection
@return T

func Samples

func Samples[T any](collection []T, count int) []T

Samples[T any]

@Description: 随即返回指定个数scile
@param collection
@param count
@return []T

func SendEmail

func SendEmail(from string, to1 string, subject string, body string, secret string, host string, port int) (err error)

*

  • @Description: 发送邮件不使用任何扩展 from :="logwwwove@qq.com" to1:="yobybxy@163.com,18291448834@163.com" secret := "abc" host :="smtp.qq.com" port := 25 subject:="主题" body:="内容是测试" err:=php.SendEmail(from,to1,subject,body,secret,host,port) php.CheckErr(err)
  • @param from 发送人邮箱
  • @param to1 收件人邮箱,多个用,隔开"yoby21bxy@163.com,182914114811834@163.com"
  • @param subject 标题
  • @param body 内容
  • @param secret 密钥,qq邮箱授权码密码
  • @param host 主机地址
  • @param port 端口25
  • @return err

func Sha1

func Sha1(str string) string

func Sha256

func Sha256(str string) string

func Shuffle

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

Shuffle[T any] Shuffle([]string{"a", "bb", "c", "ee"})

@Description: 打乱数组
@param collection
@return []T

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:切片转换字典
@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 SplitStr

func SplitStr(str, delimiter string, characterMask ...string) []string

SplitStr

@Description: 切割字符串为scile
@param str
@param delimiter 切割符号
@param characterMask 去除空格或其他
@return []string

func Str2Time

func Str2Time(s string) int64

Str2Time

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

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

*

  • @Description: 去除字符中HTML标记
  • @param content 字符串
  • @return string

func StructToMap

func StructToMap(value any) map[string]any

func Substring

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

字符串截取 字符串 位置 长度

func Sum

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

Sum[T Float | Integer | Complex]

@Description: 求和
@param collection
@return T

func TableArr

func TableArr(s string) [][]string

table转换成数组

func Ternary

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

Ternary[T any]

@Description: 三元运算符 字符串
@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 Time

func Time() int64

时间戳

func TimeLine

func TimeLine(t int64) string

TimeLine

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

func Timestr2Time

func Timestr2Time(str string) time.Time

Timestr2Time

@Description: 时间字符串转换时间类;
@param str
@return time.Time

func ToBool

func ToBool(s string) (bool, error)

转换成布尔

func ToBytes

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

ToBytes

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

func ToChar

func ToChar(s string) []string

转换字节 ToChar("abc") [a,b,c]

func ToFloat

func ToFloat(value any) (float64, error)

ToFloat

@Description: 转换成浮点数 float64
@param value
@return float64
@return error

func ToInt

func ToInt(value any) (int64, error)

ToInt

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

func ToInterface

func ToInterface(v reflect.Value) (value interface{}, ok bool)

ToInterface 将反射值转换成对应的 interface 类型

@Description:
@param v
@return value
@return ok

func ToJson

func ToJson(value any) (string, error)

func ToMap

func ToMap[T any, K comparable, V any](array []T, iteratee func(T) (K, V)) map[K]V

ToMap[T any, K comparable, V any]

@Description:将切片转为 map
@param array
@param iteratee
@return map[K]V

func ToString

func ToString(value any) string

ToString

@Description: 将值转换为字符串,对于数字、字符串、[]byte,将转换为字符串。 对于其他类型(切片、映射、数组、结构)将调用 json.Marshal
@param value
@return string

func Trim

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

开头结尾去除空格或指定字符

func TruncRound

func TruncRound(x float64, n int) float64

截断小数n位 不四舍五入

func Typeof

func Typeof(a any) reflect.Type

数据类型获取

func UUIdV4

func UUIdV4() (string, error)

func UnZip

func UnZip(zipFile string, destPath string) error

解压zip

func Unicode2utf8

func Unicode2utf8(str string) string

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

func Union

func Union[T comparable](slices ...[]T) []T

Union[T comparable]

@Description: 合并多个切片,相同元素也会合并
@param slices
@return []T

func Uniq

func Uniq[T comparable](collection []T) []T

Uniq[T comparable] Uniq([]string{"Samuel", "John", "Samuel"})

@Description: 去除scile中重复元素
@param collection
@return []T

func Uniqid

func Uniqid(prefix string) string

Uniqid

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

func Unix2Time

func Unix2Time(t int64) time.Time

Unix2Time

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

func Utf2Gbk

func Utf2Gbk(str string) string

*

  • @Description: 将utf-8编码的字符串转换为GBK编码
  • @param str 要转换字符串
  • @return string

func Utf82unicode

func Utf82unicode(str string) string

utf82unicode @Description: utf8转换unnicode @param str @return string unicode

func Values

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

Values[K comparable, V any]

@Description: 返回字典值
@param in
@return []V

func WriteCsvFile

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

写入csv

func WriteFile

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

写入文件字符

func Zip

func Zip(path string, destPath string) error

压缩文件 可以是文件或目录

func ZipAppendEntry

func ZipAppendEntry(fpath string, destPath string) error

单个文件或目录添加到zip

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 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 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 {
	Integer | Float | ~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