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
- Variables
- func AbsURL(pageURL string, relURL string) string
- func AddCSlashes(s string, b ...rune) string
- func AddSlashes(s string, args ...rune) string
- func AppendStr(strs []string, str string) []string
- func Base64Decode(str string) (string, error)
- func Base64Encode(str string) string
- func Bool(i interface{}) bool
- func ByteMd5(b []byte) string
- func Bytes2readCloser(b []byte) io.ReadCloser
- func Bytes2str(b []byte) string
- func CallFunc(getFuncByName func(string) (interface{}, bool), funcName string, ...) ([]reflect.Value, error)
- func CalledAtFileLine(skip int) string
- func CamelCase(s string) string
- func CheckPassword(rawPassword string, hashedPassword string, salt string, positions ...uint) bool
- func CleanSpaceLine(b []byte) []byte
- func CleanSpaceLineString(b string) string
- func ClearHTMLAttr(src string) string
- func CloseProcessFromCmd(cmd *exec.Cmd) error
- func CloseProcessFromPid(pid int) (err error)
- func CloseProcessFromPidFile(pidFile string) (err error)
- func CmdIsRunning(cmd *exec.Cmd) bool
- func CompareSliceStr(s1, s2 []string) bool
- func CompareSliceStrU(s1, s2 []string) bool
- func ConvDateFormat(format string) string
- func Copy(src, dest string) error
- func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error
- func CreateCmd(params []string, recvResult func([]byte) error) *exec.Cmd
- func CreateCmdStr(command string, recvResult func([]byte) error) *exec.Cmd
- func CreateCmdStrWithWriter(command string, writer ...io.Writer) *exec.Cmd
- func CreateCmdWithWriter(params []string, writer ...io.Writer) *exec.Cmd
- func Date(ti int64, format string) string
- func DateFormat(format string, timestamp interface{}) (t string)
- func DateFormatShort(timestamp interface{}) string
- func DateParse(dateString, format string) (time.Time, error)
- func DateS(ts string, format string) string
- func DateT(t time.Time, format string) string
- func Decode(data []byte, to interface{}, args ...string) error
- func Dump(m interface{}, args ...bool) (r string)
- func ElapsedMemory() (ret string)
- func Encode(data interface{}, args ...string) ([]byte, error)
- func ExecCmd(cmdName string, args ...string) (string, string, error)
- func ExecCmdBytes(cmdName string, args ...string) ([]byte, []byte, error)
- func ExecCmdDir(dir, cmdName string, args ...string) (string, string, error)
- func ExecCmdDirBytes(dir, cmdName string, args ...string) ([]byte, []byte, error)
- func Expand(template string, match map[string]string, subs ...string) string
- func FetchFiles(client *http.Client, files []RawFile, header http.Header) error
- func FetchFilesCurl(files []RawFile, curlOptions ...string) error
- func FileExists(name string) bool
- func FileMTime(file string) (int64, error)
- func FileSize(file string) (int64, error)
- func FixDirSeparator(fpath string) string
- func Float2int(v interface{}) int
- func Float2int64(v interface{}) int64
- func Float2uint(v interface{}) uint
- func Float2uint64(v interface{}) uint64
- func Float32(i interface{}) float32
- func Float64(i interface{}) float64
- func FormatByte(args ...interface{}) string
- func FormatBytes(args ...interface{}) string
- func FormatPastTime(timestamp interface{}, args ...string) string
- func FriendlyTime(d time.Duration, args ...interface{}) (r string)
- func FuncFullPath(i interface{}) (pkgName string, objName string, funcName string)
- func FuncName(i interface{}) string
- func FuncPath(i interface{}) (pkgName string, objName string, funcName string)
- func GetAllSubDirs(rootPath string) ([]string, error)
- func GetGOPATHs() []string
- func GetJSON(dat *string, s interface{}) error
- func GetSrcPath(importPath string) (appPath string, err error)
- func GobDecode(data []byte, to interface{}) error
- func GobEncode(data interface{}) ([]byte, error)
- func GonicCase(name string) string
- func GrepFile(patten string, filename string) (lines []string, err error)
- func HTML2JS(data []byte) []byte
- func HTMLDecode(str string) string
- func HTMLEncode(str string) string
- func HTTPClientWithTimeout(timeout time.Duration, options ...HTTPClientOptions) *http.Client
- func HTTPGet(client *http.Client, url string, header http.Header) (io.ReadCloser, error)
- func HTTPGetBytes(client *http.Client, url string, header http.Header) ([]byte, error)
- func HTTPGetJSON(client *http.Client, url string, v interface{}) error
- func HTTPGetToFile(client *http.Client, url string, header http.Header, fileName string) error
- func HTTPPost(client *http.Client, url string, body []byte, header http.Header) (io.ReadCloser, error)
- func HTTPPostBytes(client *http.Client, url string, body []byte, header http.Header) ([]byte, error)
- func HTTPPostJSON(client *http.Client, url string, body []byte, header http.Header) ([]byte, error)
- func HasChinese(str string) bool
- func HasTableAlias(alias string, sqlStr string, quotes ...string) (bool, error)
- func Hash(str string) string
- func HexStr2int(hexStr string) (int, error)
- func HomeDir() (home string, err error)
- func HumaneFileSize(s uint64) string
- func InInt16Slice(v int16, sl []int16) bool
- func InInt32Slice(v int32, sl []int32) bool
- func InInt64Slice(v int64, sl []int64) bool
- func InIntSlice(v int, sl []int) bool
- func InInterfaceSlice(v interface{}, sl []interface{}) bool
- func InSlice(v string, sl []string) bool
- func InSliceIface(v interface{}, sl []interface{}) bool
- func InStringSlice(v string, sl []string) bool
- func InUint16Slice(v uint16, sl []uint16) bool
- func InUint32Slice(v uint32, sl []uint32) bool
- func InUint64Slice(v uint64, sl []uint64) bool
- func InUintSlice(v uint, sl []uint) bool
- func Int(i interface{}) int
- func Int2HexStr(num int) (hex string)
- func Int32(i interface{}) int32
- func Int64(i interface{}) int64
- func Int64SliceDiff(slice1, slice2 []int64) (diffslice []int64)
- func IntSliceDiff(slice1, slice2 []int) (diffslice []int)
- func IsASCIIUpper(r rune) bool
- func IsAlpha(r rune) bool
- func IsAlphaNumeric(r rune) bool
- func IsChinese(str string) bool
- func IsDir(dir string) bool
- func IsEmail(email string) bool
- func IsEmailRFC(email string) bool
- func IsExist(path string) bool
- func IsFile(filePath string) bool
- func IsLetter(l uint8) bool
- func IsLocalhost(host string) bool
- func IsMultiLineText(text string) bool
- func IsNumeric(r rune) bool
- func IsSingleLineText(text string) bool
- func IsSliceContainsInt64(sl []int64, i int64) bool
- func IsSliceContainsStr(sl []string, str string) bool
- func IsURL(url string) bool
- func IsUpperLetter(r rune) bool
- func IsUsername(username string) bool
- func JSONDecode(data []byte, to interface{}) error
- func JSONEncode(data interface{}, indents ...string) ([]byte, error)
- func LeftPadZero(input string, padLength int) string
- func Loop(ctx context.Context, exec func() error, duration time.Duration) error
- func LowerCaseFirst(name string) string
- func Ltrim(str string) string
- func MakePassword(password string, salt string, positions ...uint) string
- func MarshalStream(w io.Writer, m interface{}) error
- func MaskString(v string, width ...float64) string
- func Md5(str string) string
- func Md5file(file string) string
- func Monitor(rootDir string, callback *MonitorEvent, args ...func(string) bool) error
- func NewCookie(name string, value string, args ...interface{}) *http.Cookie
- func Nl2br(str string) string
- func NowStr() string
- func NumberFormat(number interface{}, precision int, separator ...string) string
- func NumberTrim(number string, precision int, separator ...string) string
- func NumberTrimZero(number string) string
- func Offset(page uint, limit uint) uint
- func PBKDF2Key(password, salt []byte, iter, keyLen int, hFunc ...func() hash.Hash) string
- func ParseArgs(command string) (params []string)
- func ParseFuncName(funcString string) (pkgName string, objName string, funcName string)
- func PascalCase(s string) string
- func PowInt(x int, y int) int
- func RandFloat32() float32
- func RandFloat64() float64
- func RandInt(max int) int
- func RandPerm(max int) []int
- func RandRangeInt(min, max int) int
- func RandRangeInt64(min, max int64) int64
- func RandStr(count int) (r string)
- func RandomASCII(count uint) string
- func RandomAlphaOrNumeric(count uint, letters, numbers bool) string
- func RandomAlphabetic(count uint) string
- func RandomAlphanumeric(count uint) string
- func RandomCreateBytes(n int, alphabets ...byte) []byte
- func RandomNumeric(count uint) string
- func RandomSpec0(count uint, start, end int, letters, numbers bool, chars []rune, ...) string
- func RandomSpec1(count uint, start, end int, letters, numbers bool) string
- func RandomString(count uint) string
- func RandomStringSpec0(count uint, set []rune) string
- func RandomStringSpec1(count uint, set string) string
- func RangeDownload(url string, saveTo string, args ...int) error
- func ReadFile(filePath string) ([]byte, error)
- func ReadFileS(filePath string) (string, error)
- func ReadJSON(path string, s interface{}) error
- func Readbuf(r io.Reader, length int) ([]byte, error)
- func RemoveEOL(text string) string
- func RemoveXSS(v string) (r string)
- func RestoreTime(str string, args ...string) time.Time
- func Reverse(s string) string
- func Round(f float64, n int) float64
- func Rtrim(str string) string
- func RunCmd(params []string, recvResult func([]byte) error) *exec.Cmd
- func RunCmdStr(command string, recvResult func([]byte) error) *exec.Cmd
- func RunCmdStrWithWriter(command string, writer ...io.Writer) *exec.Cmd
- func RunCmdWithReaderWriter(params []string, reader io.Reader, writer ...io.Writer) *exec.Cmd
- func RunCmdWithWriter(params []string, writer ...io.Writer) *exec.Cmd
- func RunCmdWithWriterx(params []string, wait time.Duration, writer ...io.Writer) (cmd *exec.Cmd, err error, newOut *CmdStartResultCapturer, ...)
- func SafeBase64Decode(str string) (string, error)
- func SafeBase64Encode(str string) string
- func Salt() string
- func SaveFile(filePath string, b []byte) (int, error)
- func SaveFileS(filePath string, s string) (int, error)
- func SearchFile(filename string, paths ...string) (fullpath string, err error)
- func SeekFileLines(filename string, callback func(string) error) (err error)
- func SeekRangeNumbers(expr string, fn func(int) bool)
- func SelfDir() string
- func SelfPath() string
- func SetJSON(s interface{}) (string, error)
- func Sha1(str string) string
- func Sha256(str string) string
- func SliceChunk(slice []interface{}, size int) (chunkslice [][]interface{})
- func SliceDiff(slice1, slice2 []interface{}) (diffslice []interface{})
- func SliceFilter(slice []interface{}, a filtertype) (ftslice []interface{})
- func SliceInsert(slice, insertion []interface{}, index int) []interface{}
- func SliceIntersect(slice1, slice2 []interface{}) (diffslice []interface{})
- func SliceMerge(slice1, slice2 []interface{}) (c []interface{})
- func SlicePad(slice []interface{}, size int, val interface{}) []interface{}
- func SliceRand(a []interface{}) (b interface{})
- func SliceRandList(min, max int) []int
- func SliceRange(start, end, step int64) (intslice []int64)
- func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{})
- func SliceRemove(slice []interface{}, start int, args ...int) []interface{}
- func SliceRemoveCallback(length int, callback func(int) func(bool) error) error
- func SliceShuffle(slice []interface{}) []interface{}
- func SliceSum(intslice []int64) (sum int64)
- func SliceUnique(slice []interface{}) (uniqueslice []interface{})
- func SnakeCase(name string) string
- func SplitHost(host string) (domain string, port string)
- func StatDir(rootPath string, includeDir ...bool) ([]string, error)
- func Str(i interface{}) string
- func Str2bytes(s string) []byte
- func StrIsASCIIUpper(s string) bool
- func StrIsAlpha(s string) bool
- func StrIsAlphaNumeric(s string) bool
- func StrIsLetter(s string) bool
- func StrIsNumeric(s string) bool
- func StrIsUpperLetter(s string) bool
- func StrRepeat(str string, times int) string
- func StrReplace(str string, find string, to string) string
- func StrToTime(str string, args ...string) (unixtime int)
- func String(v interface{}) string
- func StringSliceDiff(slice1, slice2 []string) (diffslice []string)
- func StripSlashes(s string) string
- func StripTags(src string) string
- func Substr(s string, dot string, lengthAndStart ...int) string
- func TarGz(srcDirPath string, destFilePath string) error
- func TestReflect(v interface{})
- func TextLine(src string) string
- func TitleCase(name string) string
- func ToASCIIUpper(r rune) rune
- func ToStr(value interface{}, args ...int) (s string)
- func ToUpperLetter(r rune) rune
- func Token(key string, val []byte, args ...string) string
- func Token256(key string, val []byte, args ...string) string
- func TotalPages(totalRows uint, limit uint) uint
- func TotalRunTime() string
- func Trim(str string) string
- func URLDecode(str string) (string, error)
- func URLEncode(str string) string
- func URLSafeBase64(str string, encode bool) string
- func Uint(i interface{}) uint
- func Uint32(i interface{}) uint32
- func Uint64(i interface{}) uint64
- func Uint64SliceDiff(slice1, slice2 []uint64) (diffslice []uint64)
- func UintSliceDiff(slice1, slice2 []uint) (diffslice []uint)
- func UnTarGz(srcFilePath string, destDirPath string) ([]string, error)
- func Unlink(file string) bool
- func UnmarshalStream(r io.Reader, m interface{}, fn func()) error
- func Unzip(srcPath, destPath string) error
- func UpperCaseFirst(name string) string
- func VersionCompare(a, b string) (ret int)
- func VersionComparex(a, b string, op string) bool
- func WithPrefix(strs []string, prefix string) []string
- func WithSuffix(strs []string, suffix string) []string
- func WriteFile(filename string, data []byte) error
- func WriteJSON(path string, dat *string) error
- func WritePidFile(pidFile string) error
- func Zip(srcDirPath string, destFilePath string, args ...*regexp.Regexp) (n int64, err error)
- type CmdChanReader
- type CmdResultCapturer
- type CmdStartResultCapturer
- type DoOnce
- type Durafmt
- type HTTPClientOptions
- type MonitorEvent
- func (m *MonitorEvent) AddDir(dir string) error
- func (m *MonitorEvent) AddFile(file string) error
- func (m *MonitorEvent) AddFilter(args ...func(string) bool) *MonitorEvent
- func (m *MonitorEvent) Close() error
- func (m *MonitorEvent) IsDir(path string) bool
- func (m *MonitorEvent) Remove(fileOrDir string) error
- func (m *MonitorEvent) SetFilters(args ...func(string) bool) *MonitorEvent
- func (m *MonitorEvent) Watch(args ...func(string) bool) *MonitorEvent
- func (m *MonitorEvent) Watcher() *fsnotify.Watcher
- type NotFoundError
- type OrderlySafeMap
- type RawFile
- type RemoteError
- type SafeMap
- type StrTo
- func (f StrTo) Bool() (bool, error)
- func (f StrTo) Exist() bool
- func (f StrTo) Float32() (float32, error)
- func (f StrTo) Float64() (float64, error)
- func (f StrTo) Int() (int, error)
- func (f StrTo) Int64() (int64, error)
- func (f StrTo) MustBool() bool
- func (f StrTo) MustFloat32() float32
- func (f StrTo) MustFloat64() float64
- func (f StrTo) MustInt() int
- func (f StrTo) MustInt64() int64
- func (f StrTo) MustUint() uint
- func (f StrTo) MustUint64() uint64
- func (f StrTo) MustUint8() uint8
- func (f StrTo) String() string
- func (f StrTo) Uint() (uint, error)
- func (f StrTo) Uint64() (uint64, error)
- func (f StrTo) Uint8() (uint8, error)
- type Time
- func (t Time) IsAfter(timestamp interface{}, agoDays int, units ...int) bool
- func (t Time) IsAgo(timestamp interface{}, days int, units ...int) bool
- func (t Time) IsFuture(timestamp interface{}, days int, units ...int) bool
- func (t Time) IsThisMonth(timestamp interface{}) bool
- func (t Time) IsThisYear(timestamp interface{}) bool
- func (t Time) IsToday(timestamp interface{}) bool
- func (t Time) ParseTimestamp(timestamp interface{}) time.Time
- func (t Time) SubTimestamp(timestamp interface{}) time.Duration
Constants ¶
const ( // VersionCompareGt 左大于右 VersionCompareGt = 1 // VersionCompareEq 左等于右 VersionCompareEq = 0 // VersionCompareLt 左小于右 VersionCompareLt = -1 )
const ( Byte = 1 KByte = Byte * 1024 MByte = KByte * 1024 GByte = MByte * 1024 TByte = GByte * 1024 PByte = TByte * 1024 EByte = PByte * 1024 )
Storage unit constants.
const ( IsWindows = runtime.GOOS == "windows" IsLinux = runtime.GOOS == "linux" IsMac = runtime.GOOS == "darwin" Is32Bit = runtime.GOARCH == "386" Is64Bit = runtime.GOARCH == "amd64" )
const ( TB byte = '\t' LF byte = '\n' CR byte = '\r' StrLF = "\n" StrR = "\r" StrCRLF = "\r\n" StrTB = "\t" )
Variables ¶
var ( DefaultMonitor = NewMonitor() MonitorEventEmptyFn = func(string) {} )
var ( ErrNoHeaderContentLength = errors.New(`No Content-Length Provided`) ErrMd5Unmatched = errors.New("WARNING: MD5 Sums don't match") )
var ( BreakLine = []byte("\n") BreakLineString = StrLF )
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`: `周`}, } )
var DateFormatReplacer = strings.NewReplacer(datePatterns...)
DateFormatReplacer .
var ErrCmdNotRunning = errors.New(`command is not running`)
var ErrExitedByContext = errors.New(`Received an exit notification from the context`)
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) }
var StartTime = time.Now()
StartTime 开始时间
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 AddCSlashes ¶
func AddSlashes ¶
func Bytes2readCloser ¶
func Bytes2readCloser(b []byte) io.ReadCloser
func CallFunc ¶
func CallFunc(getFuncByName func(string) (interface{}, bool), funcName string, params ...interface{}) ([]reflect.Value, error)
CallFunc 根据名称调用对应函数
func CalledAtFileLine ¶
func CheckPassword ¶
CheckPassword 检查密码(密码原文,数据库中保存的哈希过后的密码,数据库中保存的盐值)
func CleanSpaceLine ¶
func CleanSpaceLineString ¶
func CloseProcessFromCmd ¶
func CloseProcessFromPid ¶
func CloseProcessFromPidFile ¶
func CmdIsRunning ¶
func CompareSliceStr ¶
CompareSliceStr compares two 'string' type slices. It returns true if elements and order are both the same.
func CompareSliceStrU ¶
CompareSliceStrU compares two 'string' type slices. It returns true if elements are the same, and ignores the order.
func ConvDateFormat ¶
ConvDateFormat Convert PHP time format.
func CopyDir ¶
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 CreateCmdStrWithWriter ¶
func DateFormat ¶
DateFormat 将时间戳格式化为日期字符窜
func DateT ¶
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 ExecCmd ¶
ExecCmd executes system command and return stdout, stderr in string type, along with possible error.
func ExecCmdBytes ¶
ExecCmdBytes executes system command and return stdout, stderr in bytes type, along with possible error.
func ExecCmdDir ¶
ExecCmdDir executes system command in given directory and return stdout, stderr in string type, along with possible error.
func ExecCmdDirBytes ¶
ExecCmdDirBytes executes system command in given directory and return stdout, stderr in bytes type, along with possible error.
func FetchFiles ¶
FetchFiles fetches files specified by the rawURL field in parallel.
func FetchFilesCurl ¶
FetchFilesCurl uses command `curl` to fetch files specified by the rawURL field in parallel.
func FileExists ¶
FileExists reports whether the named file or directory exists.
func FixDirSeparator ¶
func Float2int64 ¶
func Float2int64(v interface{}) int64
func Float2uint ¶
func Float2uint(v interface{}) uint
func Float2uint64 ¶
func Float2uint64(v interface{}) uint64
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 ¶
FormatPastTime 格式化耗时
func FriendlyTime ¶
FriendlyTime 对人类友好的经历时间格式 @param time.Duration d @param string suffix @param int precision @param bool trimRightZero @param string language
func FuncFullPath ¶
FuncFullPath 返回完整路径包名、实例名和函数名
func GetAllSubDirs ¶
GetAllSubDirs returns all subdirectories of given root path. Slice does not include given path itself.
func GetSrcPath ¶
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 GrepFile ¶
GrepFile like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read
func HTTPClientWithTimeout ¶
func HTTPClientWithTimeout(timeout time.Duration, options ...HTTPClientOptions) *http.Client
func HTTPGet ¶
HTTPGet gets the specified resource. ErrNotFound is returned if the server responds with status 404.
func HTTPGetBytes ¶
HTTPGetBytes gets the specified resource. ErrNotFound is returned if the server responds with status 404.
func HTTPGetJSON ¶
HTTPGetJSON gets the specified resource and mapping to struct. ErrNotFound is returned if the server responds with status 404.
func HTTPGetToFile ¶
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 HTTPPostJSON ¶
func HasTableAlias ¶
HasTableAlias 检查sql语句中是否包含指定表别名 sqlStr 可以由"<where子句>,<select子句>,<orderBy子句>,<groupBy子句>"组成
func HexStr2int ¶
HexStr2int converts hex format string to decimal number.
func HomeDir ¶
HomeDir returns path of '~'(in Linux) on Windows, it returns error when the variable does not exist.
func HumaneFileSize ¶
HumaneFileSize calculates the file size and generate user-friendly string.
func InInt16Slice ¶
func InInt32Slice ¶
func InInt64Slice ¶
func InIntSlice ¶
func InInterfaceSlice ¶
func InInterfaceSlice(v interface{}, sl []interface{}) bool
func InSliceIface ¶
func InSliceIface(v interface{}, sl []interface{}) bool
func InStringSlice ¶
func InUint16Slice ¶
func InUint32Slice ¶
func InUint64Slice ¶
func InUintSlice ¶
func Int2HexStr ¶
Int2HexStr converts decimal number to hex format string.
func Int64SliceDiff ¶
func IntSliceDiff ¶
func IsASCIIUpper ¶
func IsAlphaNumeric ¶
func IsDir ¶
IsDir returns true if given path is a directory, or returns false when it's a file or does not exist.
func IsEmail ¶
IsEmail validate string is an email address, if not return false basically validation can match 99% cases
func IsEmailRFC ¶
IsEmailRFC validate string is an email address, if not return false this validation omits RFC 2822
func IsExist ¶
IsExist checks whether a file or directory exists. It returns false when the file or directory does not exist.
func IsFile ¶
IsFile returns true if given path is a file, or returns false when it's a directory or does not exist.
func IsMultiLineText ¶
IsMultiLineText validate string is a multi-line text
func IsSingleLineText ¶
IsSingleLineText validate string is a single-line text
func IsSliceContainsInt64 ¶
IsSliceContainsInt64 returns true if the int64 exists in given slice.
func IsSliceContainsStr ¶
IsSliceContainsStr returns true if the string exists in given slice.
func IsURL ¶
IsURL validate string is a url link, if not return false simple validation can match 99% cases
func IsUpperLetter ¶
func IsUsername ¶
IsUsername validate string is a available username
func JSONDecode ¶
func JSONEncode ¶
func LeftPadZero ¶
LeftPadZero 字符串指定长度,长度不足的时候左边补零
func MakePassword ¶
MakePassword 创建密码(生成64个字符) 可以指定positions用来在hash处理后的密码的不同位置插入salt片段(数量取决于positions的数量),然后再次hash
func MaskString ¶
MaskString 0123456789 => 012****789
func Monitor ¶
func Monitor(rootDir string, callback *MonitorEvent, args ...func(string) bool) error
Monitor 文件监测
func NewCookie ¶
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 NumberFormat ¶
func NumberTrimZero ¶
func PBKDF2Key ¶
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 ParseFuncName ¶
ParseFuncName 解析函数名
func RandRangeInt ¶
RandRangeInt 生成区间随机数 @param int min 最小值 @param int max 最大值 @return int 生成的随机数
func RandRangeInt64 ¶
RandRangeInt64 生成区间随机数 @param int64 min 最小值 @param int64 max 最大值 @return int64 生成的随机数
func RandomASCII ¶
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 ¶
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 ¶
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 ¶
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 ¶
RandomCreateBytes generate random []byte by specify chars.
func RandomNumeric ¶
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 ¶
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 RandomStringSpec0 ¶
func RandomStringSpec1 ¶
func ReadFile ¶
ReadFile reads data type '[]byte' from file by given path. It returns error when fail to finish operation.
func ReadFileS ¶
ReadFileS reads data type 'string' from file by given path. It returns error when fail to finish operation.
func RestoreTime ¶
RestoreTime 从字符串还原时间 RestoreTime(`2001-01-01T00:00:03Z`).Format(`2006-01-02 15:04:05`) => 2001-01-01 00:00:03
func RunCmdWithReaderWriter ¶
func RunCmdWithWriterx ¶
func RunCmdWithWriterx(params []string, wait time.Duration, writer ...io.Writer) (cmd *exec.Cmd, err error, newOut *CmdStartResultCapturer, newErr *CmdStartResultCapturer)
func SafeBase64Decode ¶
SafeBase64Decode base64 decode
func SaveFile ¶
SaveFile saves content type '[]byte' to file by given path. It returns error when fail to finish operation.
func SaveFileS ¶
SaveFileS saves content type 'string' to file by given path. It returns error when fail to finish operation.
func SearchFile ¶
SearchFile search a file in paths. this is offen used in search config file in /etc ~/
func SeekRangeNumbers ¶
SeekRangeNumbers 遍历范围数值,支持设置步进值。格式例如:1-2,2-3:2
func SliceChunk ¶
func SliceChunk(slice []interface{}, size int) (chunkslice [][]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 SliceRandList ¶
func SliceRange ¶
func SliceReduce ¶
func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{})
func SliceRemove ¶
SliceRemove SliceRomove(a,4,5) //a[4]
func SliceRemoveCallback ¶
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 SliceUnique ¶
func SliceUnique(slice []interface{}) (uniqueslice []interface{})
func StatDir ¶
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 StrIsASCIIUpper ¶
func StrIsAlpha ¶
func StrIsAlphaNumeric ¶
func StrIsLetter ¶
func StrIsNumeric ¶
func StrIsUpperLetter ¶
func StrReplace ¶
StrReplace replace find all occurs to string
func StringSliceDiff ¶
func StripSlashes ¶
func ToASCIIUpper ¶
func ToUpperLetter ¶
func URLSafeBase64 ¶
URLSafeBase64 base64字符串编码为URL友好的字符串
func Uint64SliceDiff ¶
func UintSliceDiff ¶
func UnTarGz ¶
UnTarGz ungzips and untars .tar.gz file to 'destPath' and returns sub-directories. It returns error when fail to finish operation.
func UnmarshalStream ¶
UnmarshalStream .
func VersionCompare ¶
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 ¶
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 WithSuffix ¶
func WriteFile ¶
WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it and its upper level paths.
func WritePidFile ¶
WritePidFile writes the process ID to the file at PidFile. It does nothing if PidFile is not set.
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) Send ¶
func (c *CmdChanReader) Send(b []byte) *CmdChanReader
func (*CmdChanReader) SendString ¶
func (c *CmdChanReader) SendString(s string) *CmdChanReader
type CmdResultCapturer ¶
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 ¶
CanSet 同一时刻只有一个请求能获取执行权限,获得执行权限的线程接下来需要执行具体的业务逻辑,完成后调用release方法通知其他线程,操作完成,获取资源即可,其他请求接下来需要调用wait方法 reqTag 请求标识 用于标识同一个资源
type Durafmt ¶
type Durafmt struct {
// contains filtered or unexported fields
}
Durafmt holds the parsed duration and the original input duration.
func ParseDuration ¶
ParseDuration creates a new *Durafmt struct, returns error if input is invalid.
func ParseDurationString ¶
ParseDurationString creates a new *Durafmt struct from a string. returns an error if input is invalid.
type HTTPClientOptions ¶
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 RemoteError ¶
func (*RemoteError) Error ¶
func (e *RemoteError) Error() string
type SafeMap ¶
type SafeMap struct {
// contains filtered or unexported fields
}
func NewSafeMap ¶
func NewSafeMap() *SafeMap
type StrTo ¶
type StrTo string
StrTo Convert string to specify type.