Documentation ¶
Overview ¶
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.
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. 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. 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 AppendStr(strs []string, str string) []string
- func Base64Decode(str string) (string, error)
- func Base64Encode(str string) string
- func ByteMd5(b []byte) string
- func CheckPassword(rawPassword string, hashedPassword string, salt string) bool
- func ClearHtmlAttr(src string) string
- func ColorLog(format string, a ...interface{})
- func ColorLogS(format string, a ...interface{}) string
- 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 Date(ti int64, format string) string
- func DateFormat(format string, timestamp interface{}) (t string)
- func DateFormatShort(timestamp interface{}, args ...string) 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{}) error
- func Dump(m interface{}) string
- func ElapsedMemory() (ret string)
- func Encode(data interface{}) ([]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 Float32(i interface{}) float32
- func Float64(i interface{}) float64
- func FormatByte(args ...interface{}) string
- func FormatPastTime(timestamp interface{}, args ...string) string
- func FriendlyTime(d time.Duration, args ...string) (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{})
- func GetSrcPath(importPath string) (appPath string, err error)
- func GobDecode(data []byte, to interface{}) error
- func GobEncode(data interface{}) ([]byte, error)
- func GrepFile(patten string, filename string) (lines []string, err error)
- func Hash(str string) string
- func HexStr2int(hexStr string) (int, error)
- func HomeDir() (home string, err error)
- func Html2JS(data []byte) []byte
- func HtmlDecode(str string) string
- func HtmlEncode(str string) string
- 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 HumaneFileSize(s uint64) string
- func InSlice(v string, sl []string) bool
- func InSliceIface(v interface{}, sl []interface{}) bool
- func Int(i interface{}) int
- func Int2HexStr(num int) (hex string)
- func Int32(i interface{}) int32
- func Int64(i interface{}) int64
- 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 IsSliceContainsInt64(sl []int64, i int64) bool
- func IsSliceContainsStr(sl []string, str string) bool
- func IsUrl(url string) bool
- func JsonDecode(data []byte, to interface{}) error
- func JsonEncode(data interface{}) ([]byte, error)
- func Ltrim(str string) string
- func MakePassword(password string, salt string) string
- func Md5(str string) string
- func Monitor(rootDir string, callback MonitorEventFunc, filter func(string) bool) error
- func NewCookie(name string, value string, args ...interface{}) *http.Cookie
- func Nl2br(str string) string
- func ParseFuncName(funcString string) (pkgName string, objName string, funcName string)
- func PowInt(x int, y int) int
- func PregIsMatch(expr string, src []byte) (hasMatched bool)
- func PregIsMatchString(expr string, src string) (hasMatched bool)
- func PregMatch(expr string, src string) string
- func PregMatchAll(expr string, src string, n int) [][]string
- func PregMatchAll2(expr string, src string, n int) []string
- func PregReplace(expr string, repl string, src string) string
- func PregReplaceByte(expr string, repl []byte, src []byte) []byte
- func PregReplaceByteCallback(expr string, repl func([]byte) []byte, src []byte) []byte
- func PregReplaceCallback(expr string, repl func(string) string, src string) string
- func PregSplit(expr string, src string, n int) []string
- func RandFloat32() float32
- func RandFloat64() float64
- func RandInt(max int) int
- func RandPerm(max int) []int
- func RandStr(count int) (r string)
- func RandomAlphaOrNumeric(count uint, letters, numbers bool) string
- func RandomAlphabetic(count uint) string
- func RandomAlphanumeric(count uint) string
- func RandomAscii(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 ReadFile(filePath string) ([]byte, error)
- func ReadFileS(filePath string) (string, error)
- func ReadJson(path string, s interface{})
- func Reverse(s string) string
- func Rtrim(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 SelfDir() string
- func SelfPath() string
- func SetJson(s interface{}) string
- 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 SliceShuffle(slice []interface{}) []interface{}
- func SliceSum(intslice []int64) (sum int64)
- func SliceUnique(slice []interface{}) (uniqueslice []interface{})
- func StatDir(rootPath string, includeDir ...bool) ([]string, error)
- func Str(v interface{}) string
- func StrRepeat(str string, times int) string
- func StrReplace(str string, find string, to string) string
- func StrToTime(str string) (unixtime int)
- func StripTags(src string) string
- func Substr(s string, dot string, lengthAndStart ...int) string
- func TarGz(srcDirPath string, destFilePath string) error
- func ToStr(value interface{}, args ...int) (s string)
- func Token(key string, val []byte, args ...string) string
- func TotalRunTime() string
- func Trim(str string) string
- func UnTarGz(srcFilePath string, destDirPath string) ([]string, error)
- func Unlink(file string) bool
- func Unzip(srcPath, destPath string) ([]string, error)
- func UrlDecode(str string) (string, error)
- func UrlEncode(str string) string
- func WriteFile(filename string, data []byte) error
- func WriteJson(path string, dat *string)
- type MonitorEventFunc
- type NotFoundError
- type RawFile
- type RemoteError
- type SafeMap
- type StrTo
Examples ¶
Constants ¶
const ( Gray = uint8(iota + 90) Red Green Yellow Blue Magenta //NRed = uint8(31) // Normal EndColor = "\033[0m" )
Color number constants.
const ( Byte = 1 KByte = Byte * 1024 MByte = KByte * 1024 GByte = MByte * 1024 TByte = GByte * 1024 PByte = TByte * 1024 EByte = PByte * 1024 )
Storage unit constants.
Variables ¶
var DateFormatReplacer = strings.NewReplacer(datePatterns...)
var StartTime time.Time = time.Now()
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 AppendStr ¶
AppendStr appends string to slice with no duplicates.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { s := []string{"a"} s = com.AppendStr(s, "a") s = com.AppendStr(s, "b") fmt.Println(s) }
Output: [a b]
func CheckPassword ¶
检查密码(密码原文,数据库中保存的哈希过后的密码,数据库中保存的盐值)
func ColorLog ¶
func ColorLog(format string, a ...interface{})
ColorLog prints colored log to stdout. See color rules in function 'ColorLogS'.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { com.ColorLog(fmt.Sprintf( "[WARN] This is a tesing log that should be colored, path( %s ),"+ " highlight # %s #, error [ %s ].", "path to somewhere", "highlighted content", "tesing error")) }
Output:
func ColorLogS ¶
ColorLogS colors log and return colored content. Log format: <level> <content [highlight][path]> [ error ]. Level: TRAC -> blue; ERRO -> red; WARN -> Magenta; SUCC -> green; others -> default. Content: default; path: yellow; error -> red. Level has to be surrounded by "[" and "]". Highlights have to be surrounded by "# " and " #"(space), "#" will be deleted. Paths have to be surrounded by "( " and " )"(space). Errors have to be surrounded by "[ " and " ]"(space). Note: it hasn't support windows yet, contribute is welcome.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { coloredLog := com.ColorLogS(fmt.Sprintf( "[WARN] This is a tesing log that should be colored, path( %s ),"+ " highlight # %s #, error [ %s ].", "path to somewhere", "highlighted content", "tesing error")) fmt.Println(coloredLog) }
Output:
func CompareSliceStr ¶
CompareSliceStr compares two 'string' type slices. It returns true if elements and order are both the same.
func CompareSliceStrU ¶
CompareSliceStr compares two 'string' type slices. It returns true if elements are the same, and ignores the order.
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 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.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { stdout, stderr, err := com.ExecCmd("go", "help", "get") fmt.Println(stdout, stderr, err) }
Output:
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 Expand ¶
Expand replaces {k} in template with match[k] or subs[atoi(k)] if k is not in match.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { match := map[string]string{ "domain": "gowalker.org", "subdomain": "github.com", } s := "http://{domain}/{subdomain}/{0}/{1}" fmt.Println(com.Expand(s, match, "Unknwon", "gowalker")) }
Output: http://gowalker.org/github.com/Unknwon/gowalker
func FetchFiles ¶
FetchFiles fetches files specified by the rawURL field in parallel.
Example ¶
package main import ( "fmt" "net/http" "github.com/Unknwon/com" ) type rawFile struct { name string rawURL string data []byte } func (rf *rawFile) Name() string { return rf.name } func (rf *rawFile) RawUrl() string { return rf.rawURL } func (rf *rawFile) Data() []byte { return rf.data } func (rf *rawFile) SetData(p []byte) { rf.data = p } func main() { // Code that should be outside of your function body. // type rawFile struct { // name string // rawURL string // data []byte // } // func (rf *rawFile) Name() string { // return rf.name // } // func (rf *rawFile) RawUrl() string { // return rf.rawURL // } // func (rf *rawFile) Data() []byte { // return rf.data // } // func (rf *rawFile) SetData(p []byte) { // rf.data = p // } files := []com.RawFile{ &rawFile{rawURL: "http://example.com"}, &rawFile{rawURL: "http://example.com/foo"}, } err := com.FetchFiles(&http.Client{}, files, nil) fmt.Println(err, len(files[0].Data()), len(files[1].Data())) }
Output:
func FetchFilesCurl ¶
FetchFiles uses command `curl` to fetch files specified by the rawURL field in parallel.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) type rawFile struct { name string rawURL string data []byte } func (rf *rawFile) Name() string { return rf.name } func (rf *rawFile) RawUrl() string { return rf.rawURL } func (rf *rawFile) Data() []byte { return rf.data } func (rf *rawFile) SetData(p []byte) { rf.data = p } func main() { // Code that should be outside of your function body. // type rawFile struct { // name string // rawURL string // data []byte // } // func (rf *rawFile) Name() string { // return rf.name // } // func (rf *rawFile) RawUrl() string { // return rf.rawURL // } // func (rf *rawFile) Data() []byte { // return rf.data // } // func (rf *rawFile) SetData(p []byte) { // rf.data = p // } files := []com.RawFile{ &rawFile{rawURL: "http://example.com"}, &rawFile{rawURL: "http://example.com/foo"}, } err := com.FetchFilesCurl(files) fmt.Println(err, len(files[0].Data()), len(files[1].Data())) }
Output:
func FileExists ¶
FileExists reports whether the named file or directory exists.
func FixDirSeparator ¶
func FuncFullPath ¶
返回完整路径包名、实例名和函数名
func GetAllSubDirs ¶
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.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { gps := com.GetGOPATHs() fmt.Println(gps) }
Output:
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.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { srcPath, err := com.GetSrcPath("github.com/Unknwon/com") if err != nil { fmt.Println(err) return } fmt.Println(srcPath) }
Output:
func GrepFile ¶
like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read
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.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { hd, err := com.HomeDir() fmt.Println(hd, err) }
Output:
func Html2JS ¶
Html2JS converts []byte type of HTML content into JS format.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { htm := "<div id=\"button\" class=\"btn\">Click me</div>\n\r" js := string(com.Html2JS([]byte(htm))) fmt.Println(js) }
Output: <div id=\"button\" class=\"btn\">Click me</div>\n
func HttpGet ¶
HttpGet gets the specified resource. ErrNotFound is returned if the server responds with status 404.
Example ¶
package main import ( "io/ioutil" "net/http" "github.com/Unknwon/com" ) func main() ([]byte, error) { rc, err := com.HttpGet(&http.Client{}, "http://gowalker.org", nil) if err != nil { return nil, err } p, err := ioutil.ReadAll(rc) rc.Close() return p, err }
Output:
func HttpGetBytes ¶
HttpGetBytes gets the specified resource. ErrNotFound is returned if the server responds with status 404.
Example ¶
package main import ( "net/http" "github.com/Unknwon/com" ) func main() ([]byte, error) { p, err := com.HttpGetBytes(&http.Client{}, "http://gowalker.org", nil) return p, err }
Output:
func HttpGetJSON ¶
HttpGetJSON gets the specified resource and mapping to struct. ErrNotFound is returned if the server responds with status 404.
Example ¶
package main import ( "net/http" "github.com/Unknwon/com" ) func main() interface{} { j := com.HttpGetJSON(&http.Client{}, "http://gowalker.org", nil) return j }
Output:
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)
==============================
func HttpPostBytes ¶
func HttpPostJSON ¶
func HumaneFileSize ¶
HumaneFileSize calculates the file size and generate user-friendly string.
func InSliceIface ¶
func InSliceIface(v interface{}, sl []interface{}) bool
func Int2HexStr ¶
Int2HexStr converts decimal number to hex format string.
func IsDir ¶
IsDir returns true if given path is a directory, or returns false when it's a file or does not exist.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { if com.IsDir("files") { fmt.Println("directory 'files' exists") return } fmt.Println("'files' is not a directory or does not exist") }
Output:
func IsEmail ¶
validate string is an email address, if not return false basically validation can match 99% cases
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { fmt.Println(com.IsEmail("test@example.com")) fmt.Println(com.IsEmail("@example.com")) }
Output: true false
func 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.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { if com.IsExist("file.go") { fmt.Println("file.go exists") return } fmt.Println("file.go does not exist") }
Output:
func IsFile ¶
IsFile returns true if given path is a file, or returns false when it's a directory or does not exist.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { if com.IsFile("file.go") { fmt.Println("file.go exists") return } fmt.Println("file.go is not a file or does not exist") }
Output:
func IsLetter ¶
IsLetter returns true if the 'l' is an English letter.
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { fmt.Println(com.IsLetter('1')) fmt.Println(com.IsLetter('[')) fmt.Println(com.IsLetter('a')) fmt.Println(com.IsLetter('Z')) }
Output: false false true true
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 ¶
validate string is a url link, if not return false simple validation can match 99% cases
Example ¶
package main import ( "fmt" "github.com/Unknwon/com" ) func main() { fmt.Println(com.IsUrl("http://example.com")) fmt.Println(com.IsUrl("http//example.com")) }
Output: true false
func JsonDecode ¶
func JsonEncode ¶
func Monitor ¶
func Monitor(rootDir string, callback MonitorEventFunc, filter func(string) bool) error
文件监测
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 ParseFuncName ¶
func PregIsMatch ¶
func PregIsMatchString ¶
func PregReplaceByteCallback ¶
func PregReplaceCallback ¶
func 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 ¶
Creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alphabetic characters.
func 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 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 RandomCreateBytes ¶
RandomCreateBytes generate random []byte by specify chars.
func 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
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 ¶
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 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 ¶
search a file in paths. this is offen used in search config file in /etc ~/
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 ¶
SliceRomove(a,4,5) //a[4]
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 StrReplace ¶
replace find all occurs to string
func UnTarGz ¶
UnTarGz ungzips and untars .tar.gz file to 'destPath' and returns sub-directories. It returns error when fail to finish operation.
func Unzip ¶
Unzip unzips .zip file to 'destPath' and returns sub-directories. It returns error when fail to finish operation.
Types ¶
type MonitorEventFunc ¶
type MonitorEventFunc struct { Create func(string) //创建 Delete func(string) //删除 Modify func(string) //修改 Rename func(string) //重命名 Timer func() bool //定时操作 }
监控事件函数
type NotFoundError ¶
type NotFoundError struct {
Message string
}
func (NotFoundError) Error ¶
func (e NotFoundError) Error() string
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