com

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2022 License: Apache-2.0 Imports: 43 Imported by: 0

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.

Copyright 2016 Wenhui Shen <www.webx.top>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

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"
)

Variables

View Source
var (
	DefaultMonitor      = NewMonitor()
	MonitorEventEmptyFn = func(string) {}
)
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 ErrCmdNotRunning = errors.New(`command is not running`)
View Source
var ErrExitedByContext = errors.New(`Received an exit notification from the context`)
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 AddCSlashes

func AddCSlashes(s string, b ...rune) 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 Base64Decode

func Base64Decode(str string) (string, error)

Base64Decode base64 decode

func Base64Encode

func Base64Encode(str string) string

Base64Encode base64 encode

func Bool

func Bool(i interface{}) bool

func ByteMd5

func ByteMd5(b []byte) string

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 CheckPassword

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

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

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) (err error)

func CloseProcessFromPidFile

func CloseProcessFromPidFile(pidFile string) (err 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 ConvDateFormat

func ConvDateFormat(format string) string

ConvDateFormat Convert PHP time format.

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 CreateCmdStrWithWriter

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

func CreateCmdWithWriter

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

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 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 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 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 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 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 FixDirSeparator

func FixDirSeparator(fpath 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(字节整数,保留小数位数) param float64 size param int precision param bool trimRightZero

func FormatPastTime

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

FormatPastTime 格式化耗时

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 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 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 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 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 HTMLEncode

func HTMLEncode(str string) string

HTMLEncode encode html chars to string

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 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 HexStr2int

func HexStr2int(hexStr string) (int, error)

HexStr2int converts hex format string to decimal number.

func HomeDir

func HomeDir() (home string, err 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 InSlice

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

func InSliceIface

func InSliceIface(v interface{}, sl []interface{}) 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 Int2HexStr

func Int2HexStr(num int) (hex string)

Int2HexStr converts decimal number to hex format string.

func Int32

func Int32(i interface{}) int32

func Int64

func Int64(i interface{}) int64

func Int64SliceDiff

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

func IntSliceDiff

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

func IsASCIIUpper

func IsASCIIUpper(r rune) bool

func IsAlpha

func IsAlpha(r rune) bool

func IsAlphaNumeric

func IsAlphaNumeric(r rune) bool

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 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 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 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 JSONEncode

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

func LeftPadZero

func LeftPadZero(input string, padLength int) string

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

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 MakePassword

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

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

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 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 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) (params []string)

func ParseFuncName

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

ParseFuncName 解析函数名

func PascalCase

func PascalCase(s string) string

PascalCase : webx_top => WebxTop

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 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 RandomAlphaOrNumeric

func RandomAlphaOrNumeric(count uint, letters, numbers bool) string

RandomAlphaOrNumeric Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.

Param count - the length of random string to create Param letters - if true, generated string will include

alphabetic characters

Param numbers - if true, generated string will include

numeric characters

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 RandomSpec0

func RandomSpec0(count uint, start, end int, letters, numbers bool,
	chars []rune, rand *rand.Rand) string

RandomSpec0 Creates a random string based on a variety of options, using supplied source of randomness.

If start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used, unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32.

If set is not nil, characters between start and end are chosen.

This method accepts a user-supplied rand.Rand instance to use as a source of randomness. By seeding a single rand.Rand instance with a fixed seed and using it for each call, the same random sequence of strings can be generated repeatedly and predictably.

func RandomSpec1

func RandomSpec1(count uint, start, end int, letters, numbers bool) string

RandomSpec1 Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments.

Param count - the length of random string to create Param start - the position in set of chars to start at Param end - the position in set of chars to end before Param letters - if true, generated string will include

alphabetic characters

Param numbers - if true, generated string will include

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 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 RemoveEOL

func RemoveEOL(text string) string

RemoveEOL remove \r and \n

func RemoveXSS

func RemoveXSS(v string) (r string)

RemoveXSS 删除XSS代码

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 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 RunCmdStr

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

func RunCmdStrWithWriter

func RunCmdStrWithWriter(command string, writer ...io.Writer) *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 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) (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 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 SliceChunk

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

func SliceDiff

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

func SliceFilter

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

func SliceInsert

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

func SliceIntersect

func SliceIntersect(slice1, slice2 []interface{}) (diffslice []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 SplitHost

func SplitHost(host string) (domain string, port string)

SplitHost localhost:8080 => localhost,8080

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 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) 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) error

func TestReflect

func TestReflect(v interface{})

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

func TextLine

func TextLine(src string) string

TextLine Single line of text

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 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 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 Uint

func Uint(i interface{}) uint

func Uint32

func Uint32(i interface{}) uint32

func Uint64

func Uint64(i interface{}) uint64

func Uint64SliceDiff

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

func UintSliceDiff

func UintSliceDiff(slice1, slice2 []uint) (diffslice []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 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 WithPrefix

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

func WithSuffix

func WithSuffix(strs []string, suffix 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) 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

Types

type CmdChanReader

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

func NewCmdChanReader

func NewCmdChanReader(timeouts ...time.Duration) *CmdChanReader

func (*CmdChanReader) Close

func (c *CmdChanReader) Close()

func (*CmdChanReader) Debug

func (c *CmdChanReader) Debug(on bool) *CmdChanReader

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) SendString

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

type CmdResultCapturer

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

func (CmdResultCapturer) Write

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

func (CmdResultCapturer) WriteString

func (this 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 (this CmdStartResultCapturer) Buffer() *bytes.Buffer

func (CmdStartResultCapturer) Write

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

func (CmdStartResultCapturer) Writer

func (this CmdStartResultCapturer) Writer() io.Writer

type DoOnce

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

func (*DoOnce) CanSet

func (u *DoOnce) CanSet(reqTag interface{}) bool

CanSet 同一时刻只有一个请求能获取执行权限,获得执行权限的线程接下来需要执行具体的业务逻辑,完成后调用release方法通知其他线程,操作完成,获取资源即可,其他请求接下来需要调用wait方法 reqTag 请求标识 用于标识同一个资源

func (*DoOnce) Release

func (u *DoOnce) Release(reqTag interface{})

Release 获得执行权限的线程需要在执行完业务逻辑后调用该方法通知其他处于阻塞状态的线程

func (*DoOnce) Wait

func (u *DoOnce) Wait(reqTag interface{})

Wait 调用wait方法将处于阻塞状态,直到获得执行权限的线程处理完具体的业务逻辑,调用release方法来通知其他线程资源ok了

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 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 OrderlySafeMap

type OrderlySafeMap struct {
	*SafeMap
	// contains filtered or unexported fields
}

func NewOrderlySafeMap

func NewOrderlySafeMap() *OrderlySafeMap

func (*OrderlySafeMap) Delete

func (m *OrderlySafeMap) Delete(k interface{})

func (*OrderlySafeMap) Keys

func (m *OrderlySafeMap) Keys() []interface{}

func (*OrderlySafeMap) Set

func (m *OrderlySafeMap) Set(k interface{}, v interface{}) bool

func (*OrderlySafeMap) Values

func (m *OrderlySafeMap) Values(force ...bool) []interface{}

func (*OrderlySafeMap) VisitAll

func (m *OrderlySafeMap) VisitAll(callback func(int, interface{}, interface{}))

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 struct {
	// contains filtered or unexported fields
}

func NewSafeMap

func NewSafeMap() *SafeMap

func (*SafeMap) Check

func (m *SafeMap) Check(k interface{}) bool

Check returns true if k is exist in the map.

func (*SafeMap) Delete

func (m *SafeMap) Delete(k interface{})

func (*SafeMap) Get

func (m *SafeMap) Get(k interface{}) interface{}

Get from maps return the k's value

func (*SafeMap) Items

func (m *SafeMap) Items() map[interface{}]interface{}

func (*SafeMap) Set

func (m *SafeMap) Set(k interface{}, v interface{}) bool

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

type StrTo

type StrTo string

StrTo Convert string to specify type.

func (StrTo) Bool

func (f StrTo) Bool() (bool, error)

func (StrTo) Exist

func (f StrTo) Exist() bool

func (StrTo) Float32

func (f StrTo) Float32() (float32, error)

func (StrTo) Float64

func (f StrTo) Float64() (float64, error)

func (StrTo) Int

func (f StrTo) Int() (int, error)

func (StrTo) Int64

func (f StrTo) Int64() (int64, error)

func (StrTo) MustBool

func (f StrTo) MustBool() bool

func (StrTo) MustFloat32

func (f StrTo) MustFloat32() float32

func (StrTo) MustFloat64

func (f StrTo) MustFloat64() float64

func (StrTo) MustInt

func (f StrTo) MustInt() int

func (StrTo) MustInt64

func (f StrTo) MustInt64() int64

func (StrTo) MustUint

func (f StrTo) MustUint() uint

func (StrTo) MustUint64

func (f StrTo) MustUint64() uint64

func (StrTo) MustUint8

func (f StrTo) MustUint8() uint8

func (StrTo) String

func (f StrTo) String() string

func (StrTo) Uint

func (f StrTo) Uint() (uint, error)

func (StrTo) Uint64

func (f StrTo) Uint64() (uint64, error)

func (StrTo) Uint8

func (f StrTo) Uint8() (uint8, error)

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
test

Jump to

Keyboard shortcuts

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