com

package module
v1.3.19 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2024 License: Apache-2.0 Imports: 52 Imported by: 672

README

Common functions

This is an open source project for commonly used functions for the Go programming language.

This package need >= go 1.2

Documentation

Overview

Package com is an open source project for commonly used functions for the Go programming language.

Index

Constants

View Source
const (
	// VersionCompareGt 左大于右
	VersionCompareGt = 1
	// VersionCompareEq 左等于右
	VersionCompareEq = 0
	// VersionCompareLt 左小于右
	VersionCompareLt = -1
)
View Source
const (
	Byte  = 1
	KByte = Byte * 1024
	MByte = KByte * 1024
	GByte = MByte * 1024
	TByte = GByte * 1024
	PByte = TByte * 1024
	EByte = PByte * 1024
)

Storage unit constants.

View Source
const (
	IsWindows = runtime.GOOS == "windows"
	IsLinux   = runtime.GOOS == "linux"
	IsMac     = runtime.GOOS == "darwin"
	Is32Bit   = runtime.GOARCH == "386"
	Is64Bit   = runtime.GOARCH == "amd64"
)
View Source
const (
	TB      byte = '\t'
	LF      byte = '\n'
	CR      byte = '\r'
	StrLF        = "\n"
	StrR         = "\r"
	StrCRLF      = "\r\n"
	StrTB        = "\t"
)
View Source
const HalfSecond = 500 * time.Millisecond // 0.5秒

Variables

View Source
var (
	DefaultMonitor      = NewMonitor()
	MonitorEventEmptyFn = func(string) {}
)
View Source
var (
	ErrPasswordLength0     = errors.New("password length cannot be 0")
	ErrInvalidPasswordHash = errors.New("invalid password hash")
	ErrPasswordMismatch    = errors.New("password did not match")
	// ErrIncompatibleVariant is returned by ComparePasswordAndHash if the
	// provided hash was created using a unsupported variant of Argon2.
	// Currently only argon2id is supported by this package.
	ErrIncompatibleVariant = errors.New("incompatible variant of argon2")

	// ErrIncompatibleVersion is returned by ComparePasswordAndHash if the
	// provided hash was created using a different version of Argon2.
	ErrIncompatibleVersion = errors.New("incompatible version of argon2")
)
View Source
var (
	ErrNoHeaderContentLength = errors.New(`No Content-Length Provided`)
	ErrMd5Unmatched          = errors.New("WARNING: MD5 Sums don't match")
)
View Source
var (
	BreakLine       = []byte("\n")
	BreakLineString = StrLF
)
View Source
var (

	// TimeUnits 多语言时间单位
	TimeUnits = map[string]map[string]string{`zh-cn`: timeUnitsZhCN}

	// TimeShortUnits 时间单位(简写)
	TimeShortUnits = map[string]map[string]string{
		`zh-cn`: {`s`: `秒`, `ns`: `纳秒`, `us`: `微秒`, `ms`: `毫秒`, `m`: `分钟`, `h`: `小时`, `d`: `天`, `w`: `周`},
	}
)
View Source
var DateFormatReplacer = strings.NewReplacer(datePatterns...)

DateFormatReplacer .

View Source
var ErrCannotFindHomeDir = errors.New("cannot find user-specific home dir")
View Source
var ErrCmdNotRunning = errors.New(`command is not running`)
View Source
var (
	ErrExitedByContext = context.Canceled
)
View Source
var ErrFolderNotFound = errors.New("unable to locate source folder path")
View Source
var ErrNotSliceType = errors.New("expects a slice type")
View Source
var MaxYear = 9999
View Source
var MinYear = 1000
View Source
var OnCmdExitError = func(params []string, err *exec.ExitError) {
	fmt.Printf("[%v]The process exited abnormally: PID(%d) PARAMS(%v) ERR(%v)\n", time.Now().Format(`2006-01-02 15:04:05`), err.Pid(), params, err)
}
View Source
var StartTime = time.Now()

StartTime 开始时间

View Source
var UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1541.0 Safari/537.36"

Functions

func AbsURL

func AbsURL(pageURL string, relURL string) string

AbsURL 获取页面内相对网址的绝对路径

func AbsURLx added in v0.2.9

func AbsURLx(pageURLInfo *url.URL, relURL string, onlyRelative ...bool) string

func AddCSlashes

func AddCSlashes(s string, b ...rune) string

func AddRSlashes added in v0.6.2

func AddRSlashes(s string) string

func AddSlashes

func AddSlashes(s string, args ...rune) string

func AppendStr

func AppendStr(strs []string, str string) []string

AppendStr appends string to slice with no duplicates.

func Argon2CheckPassword added in v1.2.13

func Argon2CheckPassword(hash, password string) error

Argon2CheckPassword compares an argon2 hash against plaintext password

func Argon2MakePassword added in v1.2.13

func Argon2MakePassword(password string, salt ...string) (string, error)

Argon2MakePassword takes a plaintext password and generates an argon2 hash

func Argon2MakePasswordShortly added in v1.2.13

func Argon2MakePasswordShortly(password string, salt ...string) (string, error)

Argon2MakePasswordShortly takes a plaintext password and generates an argon2 hash

func Argon2MakePasswordWithParams added in v1.2.13

func Argon2MakePasswordWithParams(password string, params *Argon2Params, salt ...string) (string, error)

func AsType added in v1.3.19

func AsType(typ string, val interface{}) interface{}

func BCryptCheckPassword added in v1.2.13

func BCryptCheckPassword(hashedPassword, password string) error

BCryptCheckPassword 检查密码

func BCryptMakePassword added in v1.2.13

func BCryptMakePassword(password string) ([]byte, error)

BCryptMakePassword 创建密码(生成60个字符)

func Base64Decode

func Base64Decode(str string) (string, error)

Base64Decode base64 decode

func Base64Encode

func Base64Encode(str string) string

Base64Encode base64 encode

func BaseFileName added in v1.2.7

func BaseFileName(ppath string) string

func Bool

func Bool(i interface{}) bool

func Br2nl added in v0.2.11

func Br2nl(str string) string

Br2nl change <br/> to \n

func ByteMd5

func ByteMd5(b []byte) string

func Bytes added in v1.3.19

func Bytes(val interface{}) []byte

func Bytes2readCloser

func Bytes2readCloser(b []byte) io.ReadCloser

func Bytes2str

func Bytes2str(b []byte) string

func CallFunc

func CallFunc(getFuncByName func(string) (interface{}, bool), funcName string, params ...interface{}) ([]reflect.Value, error)

CallFunc 根据名称调用对应函数

func CalledAtFileLine

func CalledAtFileLine(skip int) string

func CamelCase

func CamelCase(s string) string

CamelCase : webx_top => webxTop

func CamelCaseWith added in v1.3.14

func CamelCaseWith(s string, sep ...rune) string

func CheckPassword

func CheckPassword(rawPassword string, hashedPassword string, salt string, positions ...uint) bool

CheckPassword 检查密码(密码原文,数据库中保存的哈希过后的密码,数据库中保存的盐值)

func ChunkSlicex added in v1.3.0

func ChunkSlicex[T any](slice []T, size int) (chunkslice [][]T)

func CleanMoreNl added in v0.2.11

func CleanMoreNl(src string) string

CleanMoreNl remove all \n(2+)

func CleanMoreSpace added in v0.2.11

func CleanMoreSpace(src string) string

CleanMoreSpace remove all spaces(2+)

func CleanSpaceLine

func CleanSpaceLine(b []byte) []byte

func CleanSpaceLineString

func CleanSpaceLineString(b string) string

func ClearHTMLAttr

func ClearHTMLAttr(src string) string

ClearHTMLAttr clear all attributes

func CloseProcessFromCmd

func CloseProcessFromCmd(cmd *exec.Cmd) error

func CloseProcessFromPid

func CloseProcessFromPid(pid int) error

func CloseProcessFromPidFile

func CloseProcessFromPidFile(pidFile string) error

func CmdIsRunning

func CmdIsRunning(cmd *exec.Cmd) bool

func CompareSliceStr

func CompareSliceStr(s1, s2 []string) bool

CompareSliceStr compares two 'string' type slices. It returns true if elements and order are both the same.

func CompareSliceStrU

func CompareSliceStrU(s1, s2 []string) bool

CompareSliceStrU compares two 'string' type slices. It returns true if elements are the same, and ignores the order.

func ContainsWord added in v1.3.3

func ContainsWord(src string, word string) bool

func ConvDateFormat

func ConvDateFormat(format string) string

ConvDateFormat Convert PHP time format.

func ConvertNumberArToCh added in v1.3.11

func ConvertNumberArToCh(num int64) string

ConvertNumberArToCh 阿拉伯数字转中文数字

func ConvertNumberArToChUpper added in v1.3.11

func ConvertNumberArToChUpper(num int64) string

ConvertNumberArToChUpper 阿拉伯数字转大写中文数字

func ConvertNumberChToAr added in v1.3.11

func ConvertNumberChToAr(inputStrNum string) (ansNum int64)

ConvertNumberChToAr 中文数字转阿拉伯数字

func Copy

func Copy(src, dest string) error

Copy copies file from source to target path.

func CopyDir

func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error

CopyDir copy files recursively from source to target directory.

The filter accepts a function that process the path info. and should return true for need to filter.

It returns error when error occurs in underlying functions.

func CreateCmd

func CreateCmd(params []string, recvResult func([]byte) error) *exec.Cmd

func CreateCmdStr

func CreateCmdStr(command string, recvResult func([]byte) error) *exec.Cmd

func CreateCmdStrWithContext added in v0.6.1

func CreateCmdStrWithContext(ctx context.Context, command string, recvResult func([]byte) error) *exec.Cmd

func CreateCmdStrWithWriter

func CreateCmdStrWithWriter(command string, writer ...io.Writer) *exec.Cmd

func CreateCmdStrWriterWithContext added in v0.6.1

func CreateCmdStrWriterWithContext(ctx context.Context, command string, writer ...io.Writer) *exec.Cmd

func CreateCmdWithContext added in v0.6.1

func CreateCmdWithContext(ctx context.Context, params []string, recvResult func([]byte) error) *exec.Cmd

func CreateCmdWithWriter

func CreateCmdWithWriter(params []string, writer ...io.Writer) *exec.Cmd

func CreateCmdWriterWithContext added in v0.6.1

func CreateCmdWriterWithContext(ctx context.Context, params []string, writer ...io.Writer) *exec.Cmd

func CreateFile added in v0.8.3

func CreateFile(filename string) (fp *os.File, err error)

CreateFile create file

func Date

func Date(ti int64, format string) string

Date Format unix time int64 to string

func DateFormat

func DateFormat(format string, timestamp interface{}) (t string)

DateFormat 将时间戳格式化为日期字符窜

func DateFormatShort

func DateFormatShort(timestamp interface{}) string

DateFormatShort 格式化耗时

func DateParse

func DateParse(dateString, format string) (time.Time, error)

DateParse Parse Date use PHP time format.

func DateS

func DateS(ts string, format string) string

DateS Format unix time string to string

func DateT

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

DateT 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 Decode

func Decode(data []byte, to interface{}, args ...string) error

func DiffSlicex added in v1.3.0

func DiffSlicex[T comparable](slice1, slice2 []T) (diffslice []T)

func Dump

func Dump(m interface{}, args ...bool) (r string)

Dump 输出对象和数组的结构信息

func ElapsedMemory

func ElapsedMemory() (ret string)

ElapsedMemory 内存占用

func Encode

func Encode(data interface{}, args ...string) ([]byte, error)

func ExecCmd

func ExecCmd(cmdName string, args ...string) (string, string, error)

ExecCmd executes system command and return stdout, stderr in string type, along with possible error.

func ExecCmdBytes

func ExecCmdBytes(cmdName string, args ...string) ([]byte, []byte, error)

ExecCmdBytes executes system command and return stdout, stderr in bytes type, along with possible error.

func ExecCmdBytesWithContext added in v0.6.1

func ExecCmdBytesWithContext(ctx context.Context, cmdName string, args ...string) ([]byte, []byte, error)

ExecCmdBytesWithContext executes system command and return stdout, stderr in bytes type, along with possible error.

func ExecCmdDir

func ExecCmdDir(dir, cmdName string, args ...string) (string, string, error)

ExecCmdDir executes system command in given directory and return stdout, stderr in string type, along with possible error.

func ExecCmdDirBytes

func ExecCmdDirBytes(dir, cmdName string, args ...string) ([]byte, []byte, error)

ExecCmdDirBytes executes system command in given directory and return stdout, stderr in bytes type, along with possible error.

func ExecCmdDirBytesWithContext added in v0.6.1

func ExecCmdDirBytesWithContext(ctx context.Context, dir, cmdName string, args ...string) ([]byte, []byte, error)

ExecCmdDirBytesWithContext executes system command in given directory and return stdout, stderr in bytes type, along with possible error.

func ExecCmdDirWithContext added in v0.6.1

func ExecCmdDirWithContext(ctx context.Context, dir, cmdName string, args ...string) (string, string, error)

ExecCmdDirWithContext executes system command in given directory and return stdout, stderr in string type, along with possible error.

func ExecCmdWithContext added in v0.6.1

func ExecCmdWithContext(ctx context.Context, cmdName string, args ...string) (string, string, error)

ExecCmdWithContext executes system command and return stdout, stderr in string type, along with possible error.

func ExitOnFailure added in v0.1.3

func ExitOnFailure(msg string, errCodes ...int)

ExitOnFailure 失败时退出程序

func ExitOnSuccess added in v0.1.3

func ExitOnSuccess(msg string)

ExitOnSuccess 成功时退出程序

func Expand

func Expand(template string, match map[string]string, subs ...string) string

Expand replaces {k} in template with match[k] or subs[atoi(k)] if k is not in match.

func ExtractSlicex added in v1.3.9

func ExtractSlicex[T any](parts []T, recv ...*T)

func FetchFiles

func FetchFiles(client *http.Client, files []RawFile, header http.Header) error

FetchFiles fetches files specified by the rawURL field in parallel.

func FetchFilesCurl

func FetchFilesCurl(files []RawFile, curlOptions ...string) error

FetchFilesCurl uses command `curl` to fetch files specified by the rawURL field in parallel.

func FileExists

func FileExists(name string) bool

FileExists reports whether the named file or directory exists.

func FileIsCompleted added in v0.3.0

func FileIsCompleted(file *os.File, start time.Time) (bool, error)

FileIsCompleted 等待文件有数据且已写完 费时操作 放在子线程中执行 @param file 文件 @param start 需要传入 time.Now.Local(),用于兼容遍历的情况 @return true:已写完 false:外部程序阻塞或者文件不存在 翻译自:https://blog.csdn.net/northernice/article/details/115986671

func FileMTime

func FileMTime(file string) (int64, error)

FileMTime returns file modified time and possible error.

func FileSize

func FileSize(file string) (int64, error)

FileSize returns file size in bytes and possible error.

func FindChineseWords added in v0.9.6

func FindChineseWords(text string, n ...int) []string

FindChineseWords find chinese words

func FindNotExistsDirs added in v0.2.4

func FindNotExistsDirs(dir string) ([]string, error)

func FixDateString added in v0.3.2

func FixDateString(dateStr string) string

func FixDateTimeString added in v0.3.2

func FixDateTimeString(dateTimeStr string) []string

func FixDirSeparator

func FixDirSeparator(fpath string) string

func FixTimeString added in v0.3.2

func FixTimeString(timeStr string) string

func Float2int

func Float2int(v interface{}) int

func Float2int64

func Float2int64(v interface{}) int64

func Float2uint

func Float2uint(v interface{}) uint

func Float2uint64

func Float2uint64(v interface{}) uint64

func Float32

func Float32(i interface{}) float32

func Float64

func Float64(i interface{}) float64

func FormatByte

func FormatByte(args ...interface{}) string

FormatByte 兼容以前的版本,FormatBytes别名 @param float64 size @param int precision @param bool trimRightZero

func FormatBytes

func FormatBytes(args ...interface{}) string

FormatBytes 格式化字节。 FormatBytes(字节整数,保留小数位数, 是否裁剪掉小数中的后缀0) 不设置 参数 2 和 参数 3 时,默认保留2为小数并裁剪小数中的后缀0 @param float64 size @param int precision @param bool trimRightZero

func FormatPastTime

func FormatPastTime(timestamp interface{}, args ...string) string

FormatPastTime 格式化耗时 @param number timestamp @param string args[0] 时间格式 @param string args[1] 已过去时间后缀 @param string args[2] 语种

func FriendlyTime

func FriendlyTime(d time.Duration, args ...interface{}) (r string)

FriendlyTime 对人类友好的经历时间格式 @param time.Duration d @param string suffix @param int precision @param bool trimRightZero @param string language

func FullURL added in v0.8.0

func FullURL(domianURL string, myURL string) string

func FuncFullPath

func FuncFullPath(i interface{}) (pkgName string, objName string, funcName string)

FuncFullPath 返回完整路径包名、实例名和函数名

func FuncName

func FuncName(i interface{}) string

FuncName 函数名

func FuncPath

func FuncPath(i interface{}) (pkgName string, objName string, funcName string)

FuncPath 返回包名、实例名和函数名

func GetAllSubDirs

func GetAllSubDirs(rootPath string) ([]string, error)

GetAllSubDirs returns all subdirectories of given root path. Slice does not include given path itself.

func GetEnvVarName added in v1.1.0

func GetEnvVarName(s string) string

func GetGOPATHs

func GetGOPATHs() []string

GetGOPATHs returns all paths in GOPATH variable.

func GetJSON

func GetJSON(dat *string, s interface{}) error

GetJSON Read json data, writes in struct f

func GetMatchedByIndex added in v1.3.2

func GetMatchedByIndex(content string, v []int, recv ...*string)

GetMatchedByIndex 通过 FindAllStringSubmatchIndex 的值获取匹配结果 matches = FindAllStringSubmatchIndex

 for _, match := range matches {
		var fullmatch string
		GetMatchedByIndex(contet, match, &fullmatch)
 }

func GetPathSeperator added in v1.2.8

func GetPathSeperator(ppath string) string

func GetSrcPath

func GetSrcPath(importPath string) (appPath string, err error)

GetSrcPath returns app. source code path. It only works when you have src. folder in GOPATH, it returns error not able to locate source folder path.

func GetWinEnvVarName added in v1.1.0

func GetWinEnvVarName(s string) string

func Getenv added in v0.4.0

func Getenv(key string, defaults ...string) string

func GetenvBool added in v0.9.5

func GetenvBool(key string, defaults ...bool) bool

func GetenvDuration added in v0.4.0

func GetenvDuration(key string, defaults ...time.Duration) time.Duration

func GetenvFloat32 added in v0.4.0

func GetenvFloat32(key string, defaults ...float32) float32

func GetenvFloat64 added in v0.4.0

func GetenvFloat64(key string, defaults ...float64) float64

func GetenvInt added in v0.4.0

func GetenvInt(key string, defaults ...int) int

func GetenvInt32 added in v0.4.0

func GetenvInt32(key string, defaults ...int32) int32

func GetenvInt64 added in v0.4.0

func GetenvInt64(key string, defaults ...int64) int64

func GetenvOr added in v1.1.0

func GetenvOr(key string) string

func GetenvUint added in v0.4.0

func GetenvUint(key string, defaults ...uint) uint

func GetenvUint32 added in v0.4.0

func GetenvUint32(key string, defaults ...uint32) uint32

func GetenvUint64 added in v0.4.0

func GetenvUint64(key string, defaults ...uint64) uint64

func GobDecode

func GobDecode(data []byte, to interface{}) error

func GobEncode

func GobEncode(data interface{}) ([]byte, error)

func GonicCase

func GonicCase(name string) string

GonicCase : webxTop => webx_top

func GrepFile

func GrepFile(patten string, filename string) (lines []string, err error)

GrepFile like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read

func HTML2JS

func HTML2JS(data []byte) []byte

HTML2JS converts []byte type of HTML content into JS format.

func HTMLDecode

func HTMLDecode(str string) string

HTMLDecode decode string to html chars

func HTMLDecodeAll added in v0.9.8

func HTMLDecodeAll(text string) string

HTMLDecodeAll decode string to html chars

func HTMLEncode

func HTMLEncode(str string) string

HTMLEncode encode html chars to string

func HTTPCanRetry added in v0.8.2

func HTTPCanRetry(code int) bool

func HTTPClientWithTimeout

func HTTPClientWithTimeout(timeout time.Duration, options ...HTTPClientOptions) *http.Client

func HTTPGet

func HTTPGet(client *http.Client, url string, header http.Header) (io.ReadCloser, error)

HTTPGet gets the specified resource. ErrNotFound is returned if the server responds with status 404.

func HTTPGetBytes

func HTTPGetBytes(client *http.Client, url string, header http.Header) ([]byte, error)

HTTPGetBytes gets the specified resource. ErrNotFound is returned if the server responds with status 404.

func HTTPGetJSON

func HTTPGetJSON(client *http.Client, url string, v interface{}) error

HTTPGetJSON gets the specified resource and mapping to struct. ErrNotFound is returned if the server responds with status 404.

func HTTPGetToFile

func HTTPGetToFile(client *http.Client, url string, header http.Header, fileName string) error

HTTPGetToFile gets the specified resource and writes to file. ErrNotFound is returned if the server responds with status 404.

func HTTPPost

func HTTPPost(client *http.Client, url string, body []byte, header http.Header) (io.ReadCloser, error)

HTTPPost ==============================

func HTTPPostBytes

func HTTPPostBytes(client *http.Client, url string, body []byte, header http.Header) ([]byte, error)

func HTTPPostJSON

func HTTPPostJSON(client *http.Client, url string, body []byte, header http.Header) ([]byte, error)

func HasChinese

func HasChinese(str string) bool

HasChinese contains Chinese

func HasChineseFirst added in v0.2.13

func HasChineseFirst(str string) bool

func HasPathSeperatorPrefix added in v1.2.8

func HasPathSeperatorPrefix(ppath string) bool

func HasPathSeperatorSuffix added in v1.2.8

func HasPathSeperatorSuffix(ppath string) bool

func HasTableAlias

func HasTableAlias(alias string, sqlStr string, quotes ...string) (bool, error)

HasTableAlias 检查sql语句中是否包含指定表别名 sqlStr 可以由"<where子句>,<select子句>,<orderBy子句>,<groupBy子句>"组成

func Hash

func Hash(str string) string

Hash 生成哈希值

func HomeDir

func HomeDir() (string, error)

HomeDir returns path of '~'(in Linux) on Windows, it returns error when the variable does not exist.

func HumaneFileSize

func HumaneFileSize(s uint64) string

HumaneFileSize calculates the file size and generate user-friendly string.

func InInt16Slice

func InInt16Slice(v int16, sl []int16) bool

func InInt32Slice

func InInt32Slice(v int32, sl []int32) bool

func InInt64Slice

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

func InIntSlice

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

func InInterfaceSlice

func InInterfaceSlice(v interface{}, sl []interface{}) bool

func InRunes added in v1.3.14

func InRunes(v rune, sep []rune) bool

func InSet added in v0.7.2

func InSet(v string, sl string, seperator ...string) bool

func InSlice

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

func InSliceIface

func InSliceIface(v interface{}, sl []interface{}) bool

func InSlicex added in v1.3.0

func InSlicex[T comparable](v T, sl []T) bool

func InStringSlice

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

func InUint16Slice

func InUint16Slice(v uint16, sl []uint16) bool

func InUint32Slice

func InUint32Slice(v uint32, sl []uint32) bool

func InUint64Slice

func InUint64Slice(v uint64, sl []uint64) bool

func InUintSlice

func InUintSlice(v uint, sl []uint) bool

func Int

func Int(i interface{}) int

func Int16 added in v1.3.13

func Int16(i interface{}) int16

func Int32

func Int32(i interface{}) int32

func Int32SliceGet added in v0.3.1

func Int32SliceGet(slice []int32, index int, defautls ...int32) int32

func Int64

func Int64(i interface{}) int64

func Int64SliceDiff

func Int64SliceDiff(slice1, slice2 []int64) (diffslice []int64)

func Int64SliceGet added in v0.3.1

func Int64SliceGet(slice []int64, index int, defautls ...int64) int64

func Int8 added in v1.3.13

func Int8(i interface{}) int8

func IntSliceDiff

func IntSliceDiff(slice1, slice2 []int) (diffslice []int)

func IntSliceGet added in v0.3.1

func IntSliceGet(slice []int, index int, defautls ...int) int

func IntersectSlicex added in v1.3.0

func IntersectSlicex[T comparable](slice1, slice2 []T) (inslice []T)

func IsASCIIUpper

func IsASCIIUpper(r rune) bool

func IsAlpha

func IsAlpha(r rune) bool

func IsAlphaNumeric

func IsAlphaNumeric(r rune) bool

func IsAlphaNumericUnderscore added in v0.3.5

func IsAlphaNumericUnderscore(s string) bool

IsAlphaNumericUnderscore 是否仅仅包含字母、数字、和下划线

func IsAlphaNumericUnderscoreHyphen added in v0.3.5

func IsAlphaNumericUnderscoreHyphen(s string) bool

IsAlphaNumericUnderscoreHyphen 是否仅仅包含字母、数字、下划线和连字符(-)

func IsChinese

func IsChinese(str string) bool

IsChinese validate string is Chinese

func IsDir

func IsDir(dir string) bool

IsDir returns true if given path is a directory, or returns false when it's a file or does not exist.

func IsEmail

func IsEmail(email string) bool

IsEmail validate string is an email address, if not return false basically validation can match 99% cases

func IsEmailRFC

func IsEmailRFC(email string) bool

IsEmailRFC validate string is an email address, if not return false this validation omits RFC 2822

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 returns true if given path is a file, or returns false when it's a directory or does not exist.

func IsFloat added in v0.1.2

func IsFloat(val string) bool

IsFloat validate string is a float number

func IsFullURL added in v0.8.0

func IsFullURL(purl string) bool

func IsInteger added in v0.1.2

func IsInteger(val string) bool

IsInteger validate string is a integer

func IsLetter

func IsLetter(l uint8) bool

IsLetter returns true if the 'l' is an English letter.

func IsLocalhost

func IsLocalhost(host string) bool

IsLocalhost 是否是本地主机

func IsMultiLineText

func IsMultiLineText(text string) bool

IsMultiLineText validate string is a multi-line text

func IsNetworkOrHostDown added in v0.8.2

func IsNetworkOrHostDown(err error, expectTimeouts bool) bool

IsNetworkOrHostDown - if there was a network error or if the host is down. expectTimeouts indicates that *context* timeouts are expected and does not indicate a downed host. Other timeouts still returns down.

func IsNumeric

func IsNumeric(r rune) bool

func IsSingleLineText

func IsSingleLineText(text string) bool

IsSingleLineText validate string is a single-line text

func IsSliceContainsInt64

func IsSliceContainsInt64(sl []int64, i int64) bool

IsSliceContainsInt64 returns true if the int64 exists in given slice.

func IsSliceContainsStr

func IsSliceContainsStr(sl []string, str string) bool

IsSliceContainsStr returns true if the string exists in given slice.

func IsURL

func IsURL(url string) bool

IsURL validate string is a url link, if not return false simple validation can match 99% cases

func IsUnsignedInteger added in v0.1.2

func IsUnsignedInteger(val string) bool

IsUnsignedInteger validate string is a unsigned-integer

func IsUpperLetter

func IsUpperLetter(r rune) bool

func IsUsername

func IsUsername(username string) bool

IsUsername validate string is a available username

func JSONDecode

func JSONDecode(data []byte, to interface{}) error

func JSONDecodeString added in v1.3.16

func JSONDecodeString(data string, to interface{}) error

func JSONEncode

func JSONEncode(data interface{}, indents ...string) ([]byte, error)

func JSONEncodeToString added in v1.3.16

func JSONEncodeToString(data interface{}, indents ...string) (string, error)

func JoinKVRows added in v1.2.5

func JoinKVRows(value interface{}, seperator ...string) string

func JoinNumbers added in v1.3.1

func JoinNumbers[T Number](slice []T, sep string) string

func LeftPadZero

func LeftPadZero(input string, padLength int) string

LeftPadZero 字符串指定长度,长度不足的时候左边补零

func ListToJSONArray added in v1.3.18

func ListToJSONArray(list string, unique ...bool) string

func ListToJSONUintArray added in v1.3.19

func ListToJSONUintArray(list string, unique ...bool) string

func Loop

func Loop(ctx context.Context, exec func() error, duration time.Duration) error

func LowerCaseFirst

func LowerCaseFirst(name string) string

LowerCaseFirst : WEBX => wEBX

func Ltrim

func Ltrim(str string) string

Ltrim trim space on left

func MBToSBText added in v1.3.11

func MBToSBText(s string) string

MBToSBText 全角转半角

func MakePassword

func MakePassword(password string, salt string, positions ...uint) string

MakePassword 创建密码(生成64个字符) 可以指定positions用来在hash处理后的密码的不同位置插入salt片段(数量取决于positions的数量),然后再次hash

func MapKeys added in v1.3.17

func MapKeys[K Scalar, V any](m map[K]V) []K

func MarshalStream

func MarshalStream(w io.Writer, m interface{}) error

MarshalStream .

func MaskString

func MaskString(v string, width ...float64) string

MaskString 0123456789 => 012****789

func Md5

func Md5(str string) string

Md5 md5 hash string

func Md5file

func Md5file(file string) string

func MergeSlicex added in v1.3.0

func MergeSlicex[T any](slice1, slice2 []T) (c []T)

func MkdirAll added in v0.2.1

func MkdirAll(dir string, mode os.FileMode) error

func Monitor

func Monitor(rootDir string, callback *MonitorEvent, args ...func(string) bool) error

Monitor 文件监测

func NewCookie

func NewCookie(name string, value string, args ...interface{}) *http.Cookie

NewCookie is a helper method that returns a new http.Cookie object. Duration is specified in seconds. If the duration is zero, the cookie is permanent. This can be used in conjunction with ctx.SetCookie.

func Nl2br

func Nl2br(str string) string

Nl2br change \n to <br/>

func Notify added in v0.2.6

func Notify(sig ...os.Signal) chan os.Signal

Notify 等待系统信号 <-Notify()

func NowStr

func NowStr() string

NowStr 当前时间字符串

func NumberFormat

func NumberFormat(number interface{}, precision int, separator ...string) string

func NumberTrim

func NumberTrim(number string, precision int, separator ...string) string

func NumberTrimZero

func NumberTrimZero(number string) string

func Offset

func Offset(page uint, limit uint) uint

Offset 根据页码计算偏移值

func PBKDF2Key

func PBKDF2Key(password, salt []byte, iter, keyLen int, hFunc ...func() hash.Hash) string

PBKDF2Key derives a key from the password, salt and iteration count, returning a []byte of length keylen that can be used as cryptographic key. The key is derived based on the method described as PBKDF2 with the HMAC variant using the supplied hash function.

For example, to use a HMAC-SHA-1 based PBKDF2 key derivation function, you can get a derived key for e.g. AES-256 (which needs a 32-byte key) by doing:

dk := pbkdf2.Key([]byte("some password"), salt, 4096, 32, sha1.New)

Remember to get a good random salt. At least 8 bytes is recommended by the RFC.

Using a higher iteration count will increase the cost of an exhaustive search but will also make derivation proportionally slower.

func ParseArgs

func ParseArgs(command string, disableParseEnvVar ...bool) (params []string)

func ParseCmdArgs added in v1.3.4

func ParseCmdArgs(inputArgs ...string) map[string]string

func ParseEnvVar added in v1.0.2

func ParseEnvVar(v string, cb ...func(string) string) string

func ParseFields added in v1.2.6

func ParseFields(row string) (fields []string)

func ParseFuncName

func ParseFuncName(funcString string) (pkgName string, objName string, funcName string)

ParseFuncName 解析函数名

func ParseHTTPRetryAfter added in v0.8.2

func ParseHTTPRetryAfter(res http.ResponseWriter) time.Duration

func ParseRetryAfter added in v0.8.2

func ParseRetryAfter(r string) time.Duration

func ParseWindowsEnvVar added in v1.0.2

func ParseWindowsEnvVar(v string, cb ...func(string) string) string

func PascalCase

func PascalCase(s string) string

PascalCase : webx_top => WebxTop

func PascalCaseWith added in v1.3.14

func PascalCaseWith(s string, sep ...rune) string

func PowInt

func PowInt(x int, y int) int

PowInt is int type of math.Pow function.

func RandFloat32

func RandFloat32() float32

RandFloat32 获取范围为[0.0, 1.0],类型为float32的随机小数

func RandFloat64

func RandFloat64() float64

RandFloat64 获取范围为[0.0, 1.0],类型为float64的随机小数

func RandInt

func RandInt(max int) int

RandInt Get in the range [0, max], a random integer type int

func RandPerm

func RandPerm(max int) []int

RandPerm 获取范围为[0,max],数量为max,类型为int的随机整数slice

func RandRangeInt

func RandRangeInt(min, max int) int

RandRangeInt 生成区间随机数 @param int min 最小值 @param int max 最大值 @return int 生成的随机数

func RandRangeInt64

func RandRangeInt64(min, max int64) int64

RandRangeInt64 生成区间随机数 @param int64 min 最小值 @param int64 max 最大值 @return int64 生成的随机数

func RandSlicex added in v1.3.0

func RandSlicex[T any](a []T) (b T)

func RandStr

func RandStr(count int) (r string)

RandStr .

func RandomASCII

func RandomASCII(count uint) string

RandomASCII Creates a random string whose length is the number of characters specified. Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive).

func RandomAlphabetic

func RandomAlphabetic(count uint) string

RandomAlphabetic Creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alphabetic characters.

func RandomAlphanumeric

func RandomAlphanumeric(count uint) string

RandomAlphanumeric Creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alpha-numeric characters.

func RandomCreateBytes

func RandomCreateBytes(n int, alphabets ...byte) []byte

RandomCreateBytes generate random []byte by specify chars.

func RandomNumeric

func RandomNumeric(count uint) string

RandomNumeric Creates a random string whose length is the number of characters specified. Characters will be chosen from the set of numeric characters.

func RandomString

func RandomString(count uint) string

func RandomStringSpec0

func RandomStringSpec0(count uint, set []rune) string

func RandomStringSpec1

func RandomStringSpec1(count uint, set string) string

func RangeDownload

func RangeDownload(url string, saveTo string, args ...int) error

func RawURLDecode added in v0.8.4

func RawURLDecode(str string) (string, error)

RawURLDecode rawurldecode()

func RawURLEncode added in v0.8.4

func RawURLEncode(str string) string

RawURLEncode rawurlencode()

func ReadFile

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

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

func ReadFileS

func ReadFileS(filePath string) (string, error)

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

func ReadJSON

func ReadJSON(path string, s interface{}) error

ReadJSON Json data read from the specified file

func Readbuf

func Readbuf(r io.Reader, length int) ([]byte, error)

func RealPath added in v1.2.10

func RealPath(fullPath string) string

func ReduceSlicex added in v1.3.0

func ReduceSlicex[T any](slice []T, a func(T) T) (dslice []T)

func Remove added in v0.5.0

func Remove(name string) error

func RemoveEOL

func RemoveEOL(text string) string

RemoveEOL remove \r and \n

func RemoveXSS

func RemoveXSS(v string) (r string)

RemoveXSS 删除XSS代码

func Rename added in v0.3.7

func Rename(src, dest string) error

GoLang: os.Rename() give error "invalid cross-device link" for Docker container with Volumes. Rename(source, destination) will work moving file between folders

func ReplaceByMatchedIndex added in v1.3.2

func ReplaceByMatchedIndex(content string, matches [][]int, replaced *string) func(k int, v []int, newInnerStr ...string)

ReplaceByMatchedIndex 通过 FindAllStringSubmatchIndex 的值来替换

 matches = FindAllStringSubmatchIndex
 var replaced string
	replacer := ReplaceByMatchedIndex(content, matches, &replaced)
 for k, v := range matches {
		var fullmatch string
		replacer(k, v, `newContent`)
 }

func RestoreTime

func RestoreTime(str string, args ...string) time.Time

RestoreTime 从字符串还原时间 RestoreTime(`2001-01-01T00:00:03Z`).Format(`2006-01-02 15:04:05`) => 2001-01-01 00:00:03

func Reverse

func Reverse(s string) string

Reverse s string, support unicode

func ReverseSortIndex added in v1.2.0

func ReverseSortIndex[T any](values []T) []T

func Round

func Round(f float64, n int) float64

Round 保留几位小数(四舍五入)

func Rtrim

func Rtrim(str string) string

Rtrim trim space on right

func RunCmd

func RunCmd(params []string, recvResult func([]byte) error) *exec.Cmd

func RunCmdReaderWriterWithContext added in v0.6.1

func RunCmdReaderWriterWithContext(ctx context.Context, params []string, reader io.Reader, writer ...io.Writer) *exec.Cmd

func RunCmdStr

func RunCmdStr(command string, recvResult func([]byte) error) *exec.Cmd

func RunCmdStrWithContext added in v0.6.1

func RunCmdStrWithContext(ctx context.Context, command string, recvResult func([]byte) error) *exec.Cmd

func RunCmdStrWithWriter

func RunCmdStrWithWriter(command string, writer ...io.Writer) *exec.Cmd

func RunCmdStrWriterWithContext added in v0.6.1

func RunCmdStrWriterWithContext(ctx context.Context, command string, writer ...io.Writer) *exec.Cmd

func RunCmdWithContext added in v0.6.1

func RunCmdWithContext(ctx context.Context, params []string, recvResult func([]byte) error) *exec.Cmd

func RunCmdWithReaderWriter

func RunCmdWithReaderWriter(params []string, reader io.Reader, writer ...io.Writer) *exec.Cmd

func RunCmdWithWriter

func RunCmdWithWriter(params []string, writer ...io.Writer) *exec.Cmd

func RunCmdWithWriterx

func RunCmdWithWriterx(params []string, wait time.Duration, writer ...io.Writer) (cmd *exec.Cmd, err error, newOut *CmdStartResultCapturer, newErr *CmdStartResultCapturer)

func RunCmdWriterWithContext added in v0.6.1

func RunCmdWriterWithContext(ctx context.Context, params []string, writer ...io.Writer) *exec.Cmd

func RunCmdWriterxWithContext added in v0.6.1

func RunCmdWriterxWithContext(ctx context.Context, params []string, wait time.Duration, writer ...io.Writer) (cmd *exec.Cmd, err error, newOut *CmdStartResultCapturer, newErr *CmdStartResultCapturer)

func SBToMBText added in v1.3.11

func SBToMBText(s string) string

SBToMBText 半角转全角

func SafeBase64Decode

func SafeBase64Decode(str string) (string, error)

SafeBase64Decode base64 decode

func SafeBase64Encode

func SafeBase64Encode(str string) string

SafeBase64Encode base64 encode

func Salt

func Salt() string

Salt 盐值加密(生成64个字符)

func SaveFile

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

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

func SaveFileS

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

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

func SearchFile

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

SearchFile search a file in paths. this is offen used in search config file in /etc ~/

func SeekFileLines

func SeekFileLines(filename string, callback func(string) error) error

func SeekLines added in v0.2.2

func SeekLines(r io.Reader, callback func(string) error) (err error)

func SeekRangeNumbers

func SeekRangeNumbers(expr string, fn func(int) bool)

SeekRangeNumbers 遍历范围数值,支持设置步进值。格式例如:1-2,2-3:2

func SelfDir

func SelfDir() string

func SelfPath

func SelfPath() string

func SemVerCompare added in v0.9.3

func SemVerCompare(a, b string) (int, error)

func SetJSON

func SetJSON(s interface{}) (string, error)

SetJSON Struct s will be converted to json format

func Sha1

func Sha1(str string) string

Sha1 sha1 hash string

func Sha256

func Sha256(str string) string

Sha256 sha256 hash string

func Shuffle added in v0.0.5

func Shuffle(arr interface{}) error

Shuffle 打乱数组

func SliceChunk

func SliceChunk(slice []interface{}, size int) (chunkslice [][]interface{})

func SliceDiff

func SliceDiff(slice1, slice2 []interface{}) (diffslice []interface{})

func SliceExtract added in v1.1.3

func SliceExtract(parts []string, recv ...*string)

func SliceExtractCallback added in v1.1.3

func SliceExtractCallback[T Scalar](parts []string, cb func(string) T, recv ...*T)

func SliceFilter

func SliceFilter(slice []interface{}, a filtertype) (ftslice []interface{})

func SliceGet added in v0.3.1

func SliceGet(slice []interface{}, index int, defautls ...interface{}) interface{}

func SliceInsert

func SliceInsert(slice, insertion []interface{}, index int) []interface{}

func SliceIntersect

func SliceIntersect(slice1, slice2 []interface{}) (inslice []interface{})

func SliceMerge

func SliceMerge(slice1, slice2 []interface{}) (c []interface{})

func SlicePad

func SlicePad(slice []interface{}, size int, val interface{}) []interface{}

func SliceRand

func SliceRand(a []interface{}) (b interface{})

func SliceRandList

func SliceRandList(min, max int) []int

func SliceRange

func SliceRange(start, end, step int64) (intslice []int64)

func SliceReduce

func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{})

func SliceRemove

func SliceRemove(slice []interface{}, start int, args ...int) []interface{}

SliceRemove SliceRomove(a,4,5) //a[4]

func SliceRemoveCallback

func SliceRemoveCallback(length int, callback func(int) func(bool) error) error

SliceRemoveCallback : 根据条件删除 a=[]int{1,2,3,4,5,6}

SliceRemoveCallback(len(a), func(i int) func(bool)error{
	if a[i]!=4 {
	 	return nil
	}
	return func(inside bool)error{
		if inside {
			a=append(a[0:i],a[i+1:]...)
		}else{
			a=a[0:i]
		}
		return nil
	}
})

func SliceShuffle

func SliceShuffle(slice []interface{}) []interface{}

func SliceSum

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

func SliceUnique

func SliceUnique(slice []interface{}) (uniqueslice []interface{})

func SnakeCase

func SnakeCase(name string) string

SnakeCase : WebxTop => webx_top

func SnakeCaseWith added in v1.3.14

func SnakeCaseWith(name string, sep ...rune) string

func SplitFileDirAndName added in v1.2.8

func SplitFileDirAndName(ppath string) (dir string, name string)

func SplitHost

func SplitHost(hostport string) string

SplitHost localhost:8080 => localhost

func SplitHostPort added in v0.3.3

func SplitHostPort(hostport string) (host string, port string)

func SplitKVRows added in v1.2.1

func SplitKVRows(rows string, seperator ...string) map[string]string

func SplitKVRowsCallback added in v1.2.1

func SplitKVRowsCallback(rows string, callback func(k, v string) error, seperator ...string) (err error)

func SplitSliceByGroup added in v1.3.17

func SplitSliceByGroup[K Scalar, V any](rows []V, groupValue func(V) K) map[K][]V

func StatDir

func StatDir(rootPath string, includeDir ...bool) ([]string, error)

StatDir gathers information of given directory by depth-first. It returns slice of file list and includes subdirectories if enabled; it returns error and nil slice when error occurs in underlying functions, or given path is not a directory or does not exist.

Slice does not include given path itself. If subdirectories is enabled, they will have suffix '/'.

func Str

func Str(i interface{}) string

func Str2bytes

func Str2bytes(s string) []byte

func StrIsASCIIUpper

func StrIsASCIIUpper(s string) bool

func StrIsAlpha

func StrIsAlpha(s string) bool

func StrIsAlphaNumeric

func StrIsAlphaNumeric(s string) bool

func StrIsLetter

func StrIsLetter(s string) bool

func StrIsNumeric

func StrIsNumeric(s string) bool

func StrIsUpperLetter

func StrIsUpperLetter(s string) bool

func StrRepeat

func StrRepeat(str string, times int) string

StrRepeat repeat string times

func StrReplace

func StrReplace(str string, find string, to string) string

StrReplace replace find all occurs to string

func StrSliceGet added in v0.3.1

func StrSliceGet(slice []string, index int, defautls ...string) string

func StrToTime

func StrToTime(str string, args ...string) (unixtime int)

StrToTime 日期字符窜转为时间戳数字

func String

func String(v interface{}) string

func StringSliceDiff

func StringSliceDiff(slice1, slice2 []string) (diffslice []string)

func StripSlashes

func StripSlashes(s string) string

func StripTags

func StripTags(src string, singleLine ...bool) string

StripTags strip tags in html string

func Substr

func Substr(s string, dot string, lengthAndStart ...int) string

Substr returns the substr from start to length.

func TarGz

func TarGz(srcDirPath string, destFilePath string, args ...*regexp.Regexp) error

TarGz 压缩为tar.gz args: regexpFileName, regexpIgnoreFile

func TestReflect

func TestReflect(v interface{})

TestReflect 测试反射:显示字段和方法信息

func TextLine

func TextLine(src string) string

TextLine Single line of text

func Title added in v0.8.0

func Title(v string) string

func TitleCase

func TitleCase(name string) string

TitleCase : webx_top => Webx_Top

func ToASCIIUpper

func ToASCIIUpper(r rune) rune

func ToStr

func ToStr(value interface{}, args ...int) (s string)

ToStr Convert any type to string.

func ToUpperLetter

func ToUpperLetter(r rune) rune

func Token

func Token(key string, val []byte, args ...string) string

func Token256

func Token256(key string, val []byte, args ...string) string

func TokenEqual added in v1.2.13

func TokenEqual(mac1 []byte, mac2 []byte) bool

func TotalPages

func TotalPages(totalRows uint, limit uint) uint

TotalPages 总页数

func TotalRunTime

func TotalRunTime() string

TotalRunTime 总运行时长

func Trim

func Trim(str string) string

Trim trim space in all string length

func TrimFileName added in v1.1.2

func TrimFileName(ppath string) string

TrimFileName trim the file name

func TrimSpaceForRows added in v1.2.1

func TrimSpaceForRows(rows string) []string

func URLDecode

func URLDecode(str string) (string, error)

URLDecode url decode string

func URLEncode

func URLEncode(str string) string

URLEncode url encode string, is + not %20

func URLSafeBase64

func URLSafeBase64(str string, encode bool) string

URLSafeBase64 base64字符串编码为URL友好的字符串

func URLSeparator added in v0.2.12

func URLSeparator(pageURL string) string

func Uint

func Uint(i interface{}) uint

func Uint16 added in v1.3.13

func Uint16(i interface{}) uint16

func Uint32

func Uint32(i interface{}) uint32

func Uint32SliceGet added in v0.3.1

func Uint32SliceGet(slice []uint32, index int, defautls ...uint32) uint32

func Uint64

func Uint64(i interface{}) uint64

func Uint64SliceDiff

func Uint64SliceDiff(slice1, slice2 []uint64) (diffslice []uint64)

func Uint64SliceGet added in v0.3.1

func Uint64SliceGet(slice []uint64, index int, defautls ...uint64) uint64

func Uint8 added in v1.3.13

func Uint8(i interface{}) uint8

func UintSliceDiff

func UintSliceDiff(slice1, slice2 []uint) (diffslice []uint)

func UintSliceGet added in v0.3.1

func UintSliceGet(slice []uint, index int, defautls ...uint) uint

func UnTarGz

func UnTarGz(srcFilePath string, destDirPath string) ([]string, error)

UnTarGz ungzips and untars .tar.gz file to 'destPath' and returns sub-directories. It returns error when fail to finish operation.

func Unlink(file string) bool

func UnmarshalStream

func UnmarshalStream(r io.Reader, m interface{}, fn func()) error

UnmarshalStream .

func Unzip

func Unzip(srcPath, destPath string) error

Unzip unzips .zip file to 'destPath'. It returns error when fail to finish operation.

func UpperCaseFirst

func UpperCaseFirst(name string) string

UpperCaseFirst : webx => Webx

func UpperChNumber added in v1.3.11

func UpperChNumber(s string) string

UpperChNumber 大写中文数字

func VersionCompare

func VersionCompare(a, b string) (ret int)

VersionCompare compare two versions in x.y.z form @param {string} a version string @param {string} b version string @return {int} 1 = a is higher, 0 = equal, -1 = b is higher

func VersionComparex

func VersionComparex(a, b string, op string) bool

VersionComparex compare two versions in x.y.z form @param {string} a version string @param {string} b version string @param {string} op <,<=,>,>=,= or lt,le,elt,gt,ge,egt,eq @return {bool}

func WatchingStdin added in v1.0.3

func WatchingStdin(ctx context.Context, name string, fn func(string) error)

WatchingStdin Watching os.Stdin example: go WatchingStdin(ctx,`name`,fn)

func WithPrefix

func WithPrefix(strs []string, prefix string) []string

func WithSuffix

func WithSuffix(strs []string, suffix string) []string

func WithURLParams added in v0.8.0

func WithURLParams(urlStr string, key string, value string, args ...string) string

func WriteFile

func WriteFile(filename string, data []byte) error

WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it and its upper level paths.

func WriteJSON

func WriteJSON(path string, dat *string) error

WriteJSON The json data is written to the specified file

func WritePidFile

func WritePidFile(pidFile string, pidNumbers ...int) error

WritePidFile writes the process ID to the file at PidFile. It does nothing if PidFile is not set.

func Zip

func Zip(srcDirPath string, destFilePath string, args ...*regexp.Regexp) (n int64, err error)

Zip 压缩为zip args: regexpFileName, regexpIgnoreFile

Types

type Argon2Params added in v1.2.13

type Argon2Params struct {
	Type string

	// The amount of memory used by the algorithm (in kibibytes).
	Memory uint32

	// The number of iterations over the memory.
	Iterations uint32

	// The number of threads (or lanes) used by the algorithm.
	// Recommended value is between 1 and runtime.NumCPU().
	Parallelism uint8

	// Length of the random salt. 16 bytes is recommended for password hashing.
	SaltLength uint32

	// Length of the generated key. 16 bytes or more is recommended.
	KeyLength uint32

	Shortly bool
}

Params describes the input parameters used by the Argon2id algorithm. The Memory and Iterations parameters control the computational cost of hashing the password. The higher these figures are, the greater the cost of generating the hash and the longer the runtime. It also follows that the greater the cost will be for any attacker trying to guess the password. If the code is running on a machine with multiple cores, then you can decrease the runtime without reducing the cost by increasing the Parallelism parameter. This controls the number of threads that the work is spread across. Important note: Changing the value of the Parallelism parameter changes the hash output.

For guidance and an outline process for choosing appropriate parameters see https://tools.ietf.org/html/draft-irtf-cfrg-argon2-04#section-4

func NewArgon2Params added in v1.2.13

func NewArgon2Params() *Argon2Params

func (*Argon2Params) Parse added in v1.2.13

func (a *Argon2Params) Parse(hash string) (salt, key []byte, err error)

func (*Argon2Params) SetDefaults added in v1.2.13

func (a *Argon2Params) SetDefaults()

type CmdChanReader

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

func NewCmdChanReader

func NewCmdChanReader() *CmdChanReader

func (*CmdChanReader) Close

func (c *CmdChanReader) Close()

func (*CmdChanReader) Read

func (c *CmdChanReader) Read(p []byte) (n int, err error)

func (*CmdChanReader) Send

func (c *CmdChanReader) Send(b []byte) *CmdChanReader

func (*CmdChanReader) SendAndWait added in v1.0.3

func (c *CmdChanReader) SendAndWait(b []byte) *CmdChanReader

func (*CmdChanReader) SendReader added in v1.0.3

func (c *CmdChanReader) SendReader(r io.Reader) *CmdChanReader

func (*CmdChanReader) SendReaderAndWait added in v1.0.3

func (c *CmdChanReader) SendReaderAndWait(r io.Reader) *CmdChanReader

func (*CmdChanReader) SendString

func (c *CmdChanReader) SendString(s string) *CmdChanReader

func (*CmdChanReader) SendStringAndWait added in v1.0.3

func (c *CmdChanReader) SendStringAndWait(s string) *CmdChanReader

type CmdResultCapturer

type CmdResultCapturer struct {
	Do func([]byte) error
}

func (CmdResultCapturer) Write

func (c CmdResultCapturer) Write(p []byte) (n int, err error)

func (CmdResultCapturer) WriteString

func (c CmdResultCapturer) WriteString(p string) (n int, err error)

type CmdStartResultCapturer

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

func NewCmdStartResultCapturer

func NewCmdStartResultCapturer(writer io.Writer, duration time.Duration) *CmdStartResultCapturer

func (*CmdStartResultCapturer) Buffer

func (c *CmdStartResultCapturer) Buffer() *bytes.Buffer

func (*CmdStartResultCapturer) Write

func (c *CmdStartResultCapturer) Write(p []byte) (n int, err error)

func (*CmdStartResultCapturer) Writer

func (c *CmdStartResultCapturer) Writer() io.Writer

type DelayOncer added in v1.0.0

type DelayOncer interface {
	Do(parentCtx context.Context, key string, f func() error, delayAndTimeout ...time.Duration) (isNew bool)
	DoWithState(parentCtx context.Context, key string, f func(func() bool) error, delayAndTimeout ...time.Duration) (isNew bool)
	CloseKey(key string) bool
	Close() error
}

func NewDelayOnce added in v0.6.0

func NewDelayOnce(delay time.Duration, timeout time.Duration, debugMode ...bool) DelayOncer

type Durafmt

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

Durafmt holds the parsed duration and the original input duration.

func ParseDuration

func ParseDuration(dinput time.Duration, args ...interface{}) *Durafmt

ParseDuration creates a new *Durafmt struct, returns error if input is invalid.

func ParseDurationString

func ParseDurationString(input string, args ...interface{}) (*Durafmt, error)

ParseDurationString creates a new *Durafmt struct from a string. returns an error if input is invalid.

func (*Durafmt) Duration

func (d *Durafmt) Duration() time.Duration

func (*Durafmt) String

func (d *Durafmt) String() string

String parses d *Durafmt into a human readable duration.

type HTTPClientOptions

type HTTPClientOptions func(c *http.Client)

type IntArgs added in v0.3.1

type IntArgs []int

func (IntArgs) Get added in v0.3.1

func (a IntArgs) Get(index int, defaults ...int) (r int)

type LineReader added in v0.2.2

type LineReader interface {
	ReadLine() (line []byte, isPrefix bool, err error)
}

type MonitorEvent

type MonitorEvent struct {
	//文件事件
	Create func(string) //创建
	Delete func(string) //删除(包含文件夹和文件。因为已经删除,无法确定是文件夹还是文件)
	Modify func(string) //修改(包含修改权限。如果是文件夹,则内部的文件被更改也会触发此事件)
	Chmod  func(string) //修改权限(windows不支持)
	Rename func(string) //重命名

	//其它
	Channel chan bool //管道
	Debug   bool
	// contains filtered or unexported fields
}

MonitorEvent 监控事件函数

func NewMonitor

func NewMonitor() *MonitorEvent

func (*MonitorEvent) AddDir

func (m *MonitorEvent) AddDir(dir string) error

func (*MonitorEvent) AddFile

func (m *MonitorEvent) AddFile(file string) error

func (*MonitorEvent) AddFilter

func (m *MonitorEvent) AddFilter(args ...func(string) bool) *MonitorEvent

func (*MonitorEvent) Close

func (m *MonitorEvent) Close() error

func (*MonitorEvent) IsDir

func (m *MonitorEvent) IsDir(path string) bool

func (*MonitorEvent) Remove

func (m *MonitorEvent) Remove(fileOrDir string) error

func (*MonitorEvent) SetFilters

func (m *MonitorEvent) SetFilters(args ...func(string) bool) *MonitorEvent

func (*MonitorEvent) Watch

func (m *MonitorEvent) Watch(args ...func(string) bool) *MonitorEvent

func (*MonitorEvent) Watcher

func (m *MonitorEvent) Watcher() *fsnotify.Watcher

type NotFoundError

type NotFoundError struct {
	Message string
}

func (NotFoundError) Error

func (e NotFoundError) Error() string

type Number added in v1.1.3

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

type OrderlySafeMap

type OrderlySafeMap[K comparable, V any] struct {
	*SafeMap[K, V]
	// contains filtered or unexported fields
}

func InitOrderlySafeMap added in v1.3.6

func InitOrderlySafeMap[K comparable, V any]() OrderlySafeMap[K, V]

func NewOrderlySafeMap

func NewOrderlySafeMap[K comparable, V any]() *OrderlySafeMap[K, V]

func (*OrderlySafeMap[K, V]) ClearEmpty added in v1.3.6

func (m *OrderlySafeMap[K, V]) ClearEmpty(f func(key K, val V) bool)

func (*OrderlySafeMap[K, V]) Delete

func (m *OrderlySafeMap[K, V]) Delete(k K)

func (*OrderlySafeMap[K, V]) Keys

func (m *OrderlySafeMap[K, V]) Keys() []K

func (*OrderlySafeMap[K, V]) Remove added in v1.3.6

func (m *OrderlySafeMap[K, V]) Remove(keys ...K)

func (*OrderlySafeMap[K, V]) Reset added in v1.3.6

func (m *OrderlySafeMap[K, V]) Reset()

func (*OrderlySafeMap[K, V]) Set

func (m *OrderlySafeMap[K, V]) Set(k K, v V)

func (*OrderlySafeMap[K, V]) Values

func (m *OrderlySafeMap[K, V]) Values(force ...bool) []V

func (*OrderlySafeMap[K, V]) VisitAll

func (m *OrderlySafeMap[K, V]) VisitAll(callback func(int, K, V))

type RawFile

type RawFile interface {
	Name() string
	RawUrl() string
	Data() []byte
	SetData([]byte)
}

A RawFile describes a file that can be downloaded.

type RemoteError

type RemoteError struct {
	Host string
	Err  error
}

func (*RemoteError) Error

func (e *RemoteError) Error() string

type SafeMap

type SafeMap[K comparable, V any] struct {
	// contains filtered or unexported fields
}

func InitSafeMap added in v1.3.6

func InitSafeMap[K comparable, V any]() SafeMap[K, V]

func NewSafeMap

func NewSafeMap[K comparable, V any]() *SafeMap[K, V]

func (*SafeMap[K, V]) ClearEmpty added in v1.3.6

func (m *SafeMap[K, V]) ClearEmpty(f func(key K, val V) bool)

func (*SafeMap[K, V]) Delete

func (m *SafeMap[K, V]) Delete(k K)

func (*SafeMap[K, V]) Exists added in v1.3.6

func (m *SafeMap[K, V]) Exists(k K) bool

Exists returns true if k is exist in the map.

func (*SafeMap[K, V]) Get

func (m *SafeMap[K, V]) Get(k K) V

Get from maps return the k's value

func (*SafeMap[K, V]) GetOk added in v1.3.6

func (m *SafeMap[K, V]) GetOk(k K) (V, bool)

func (*SafeMap[K, V]) Gets added in v1.3.6

func (m *SafeMap[K, V]) Gets(keys ...K) []V

func (*SafeMap[K, V]) Items

func (m *SafeMap[K, V]) Items() map[K]V

func (*SafeMap[K, V]) Range added in v1.3.6

func (m *SafeMap[K, V]) Range(f func(key K, val V) bool)

func (*SafeMap[K, V]) Remove added in v1.3.6

func (m *SafeMap[K, V]) Remove(keys ...K)

func (*SafeMap[K, V]) Reset added in v1.3.6

func (m *SafeMap[K, V]) Reset()

func (*SafeMap[K, V]) Set

func (m *SafeMap[K, V]) Set(k K, v V)

Set maps the given key and value. Returns false if the key is already in the map and changes nothing.

func (*SafeMap[K, V]) Size added in v1.3.6

func (m *SafeMap[K, V]) Size() int

type Scalar added in v1.1.3

type Scalar interface {
	Number | ~bool | ~string
}

type Time

type Time struct {
	time.Time
}

func NewTime

func NewTime(t time.Time) *Time

func (Time) IsAfter

func (t Time) IsAfter(timestamp interface{}, agoDays int, units ...int) bool

func (Time) IsAgo

func (t Time) IsAgo(timestamp interface{}, days int, units ...int) bool

func (Time) IsFuture

func (t Time) IsFuture(timestamp interface{}, days int, units ...int) bool

func (Time) IsThisMonth

func (t Time) IsThisMonth(timestamp interface{}) bool

func (Time) IsThisYear

func (t Time) IsThisYear(timestamp interface{}) bool

func (Time) IsToday

func (t Time) IsToday(timestamp interface{}) bool

func (Time) ParseTimestamp

func (t Time) ParseTimestamp(timestamp interface{}) time.Time

func (Time) SubTimestamp

func (t Time) SubTimestamp(timestamp interface{}) time.Duration

Directories

Path Synopsis
cmd
encoding
test

Jump to

Keyboard shortcuts

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