com

package
v0.0.0-...-800783e Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2016 License: Apache-2.0, Apache-2.0 Imports: 38 Imported by: 0

README

Common functions

Build Status Go Walker

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

This package need >= go 1.2

Code Convention: based on Go Code Convention.

Contribute

Your contribute is welcome, but you have to check following steps after you added some functions and commit them:

  1. Make sure you wrote user-friendly comments for all functions .
  2. Make sure you wrote test cases with any possible condition for all functions in file *_test.go.
  3. Make sure you wrote benchmarks for all functions in file *_test.go.
  4. Make sure you wrote useful examples for all functions in file example_test.go.
  5. Make sure you ran go test -bench="." and got PASS .

Performance

See results on drone.io by go test -bench=".".

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

Examples

Constants

View Source
const (
	Gray = uint8(iota + 90)
	Red
	Green
	Yellow
	Blue
	Magenta
	//NRed      = uint8(31) // Normal
	EndColor = "\033[0m"
)

Color number constants.

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.

Variables

View Source
var DateFormatReplacer = strings.NewReplacer(datePatterns...)
View Source
var StartTime time.Time = time.Now()
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 AppendStr

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

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 Base64Decode

func Base64Decode(str string) (string, error)

base64 decode

func Base64Encode

func Base64Encode(str string) string

base64 encode

func ByteMd5

func ByteMd5(b []byte) string

func CheckPassword

func CheckPassword(rawPassword string, hashedPassword string, salt string) bool

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

func ClearHtmlAttr

func ClearHtmlAttr(src string) string

clear all attributes

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

func ColorLogS(format string, a ...interface{}) string

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

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

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

func ConvDateFormat

func ConvDateFormat(format string) string

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 Date

func Date(ti int64, format string) string

Format unix time int64 to string

func DateFormat

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

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

func DateFormatShort

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

格式化耗时

func DateParse

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

Parse Date use PHP time format.

func DateS

func DateS(ts string, format string) string

Format unix time string to string

func DateT

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

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

func Dump

func Dump(m interface{}) string

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

func ElapsedMemory

func ElapsedMemory() (ret string)

内存占用

func Encode

func Encode(data interface{}) ([]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.

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

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.

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

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

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

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

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

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 Float32

func Float32(i interface{}) float32

func Float64

func Float64(i interface{}) float64

func FormatByte

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

格式化字节。 FormatByte(字节整数,保留小数位数)

func FormatPastTime

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

格式化耗时

func FriendlyTime

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

对人类友好的经历时间格式

func FuncFullPath

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

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

func FuncName

func FuncName(i interface{}) string

func FuncPath

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

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

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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	gps := com.GetGOPATHs()
	fmt.Println(gps)
}
Output:

func GetJson

func GetJson(dat *string, s interface{})

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.

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 GobDecode

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

func GobEncode

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

func GrepFile

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

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

func Hash

func Hash(str string) string

生成哈希值

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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	hd, err := com.HomeDir()
	fmt.Println(hd, err)
}
Output:

func Html2JS

func Html2JS(data []byte) []byte

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 HtmlDecode

func HtmlDecode(str string) string

decode string to html chars

func HtmlEncode

func HtmlEncode(str string) string

encode html chars to string

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.

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

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.

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

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.

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

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)

==============================

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 HumaneFileSize

func HumaneFileSize(s uint64) string

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

func InSlice

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

func InSliceIface

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

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

func IsEmail(email string) bool

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

func IsEmailRFC(email string) bool

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.

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

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.

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

func IsLetter(l uint8) bool

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

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

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 JsonDecode(data []byte, to interface{}) error

func JsonEncode

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

func Ltrim

func Ltrim(str string) string

trim space on left

func MakePassword

func MakePassword(password string, salt string) string

创建密码

func Md5

func Md5(str string) string

md5 hash string

func Monitor

func Monitor(rootDir string, callback MonitorEventFunc, filter func(string) bool) error

文件监测

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

change \n to <br/>

func ParseFuncName

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

func PowInt

func PowInt(x int, y int) int

PowInt is int type of math.Pow function.

func PregIsMatch

func PregIsMatch(expr string, src []byte) (hasMatched bool)

func PregIsMatchString

func PregIsMatchString(expr string, src string) (hasMatched bool)

func PregMatch

func PregMatch(expr string, src string) string

func PregMatchAll

func PregMatchAll(expr string, src string, n int) [][]string

func PregMatchAll2

func PregMatchAll2(expr string, src string, n int) []string

func PregReplace

func PregReplace(expr string, repl string, src string) string

func PregReplaceByte

func PregReplaceByte(expr string, repl []byte, src []byte) []byte

func PregReplaceByteCallback

func PregReplaceByteCallback(expr string, repl func([]byte) []byte, src []byte) []byte

func PregReplaceCallback

func PregReplaceCallback(expr string, repl func(string) string, src string) string

func PregSplit

func PregSplit(expr string, src string, n int) []string

func RandFloat32

func RandFloat32() float32

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

func RandFloat64

func RandFloat64() float64

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

func RandInt

func RandInt(max int) int

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

func RandPerm

func RandPerm(max int) []int

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

func RandStr

func RandStr(count int) (r string)

func RandomAlphaOrNumeric

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

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

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

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

func RandomAscii(count uint) string

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

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

RandomCreateBytes generate random []byte by specify chars.

func RandomNumeric

func RandomNumeric(count uint) string

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

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

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 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{})

Json data read from the specified file

func Reverse

func Reverse(s string) string

Reverse s string, support unicode

func Rtrim

func Rtrim(str string) string

trim space on right

func Salt

func Salt() string

盐值加密

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)

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

func SelfDir

func SelfDir() string

func SelfPath

func SelfPath() string

func SetJson

func SetJson(s interface{}) string

Struct s will be converted to json format

func Sha1

func Sha1(str string) string

sha1 hash string

func Sha256

func Sha256(str string) string

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{}

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

func SliceShuffle

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

func SliceSum

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

func SliceUnique

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

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(v interface{}) string

func StrRepeat

func StrRepeat(str string, times int) string

repeat string times

func StrReplace

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

replace find all occurs to string

func StrToTime

func StrToTime(str string) (unixtime int)

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

func StripTags

func StripTags(src string) string

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 ToStr

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

Convert any type to string.

func Token

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

func TotalRunTime

func TotalRunTime() string

总运行时长

func Trim

func Trim(str string) string

trim space in all string length

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 Unzip

func Unzip(srcPath, destPath string) ([]string, error)

Unzip unzips .zip file to 'destPath' and returns sub-directories. It returns error when fail to finish operation.

func UrlDecode

func UrlDecode(str string) (string, error)

url decode string

func UrlEncode

func UrlEncode(str string) string

url encode string, is + not %20

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)

The json data is written to the specified file

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

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

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

type StrTo

type StrTo string

Convert string to specify type.

func (StrTo) Exist

func (f StrTo) Exist() bool

func (StrTo) Int

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

func (StrTo) Int64

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

func (StrTo) MustInt

func (f StrTo) MustInt() int

func (StrTo) MustInt64

func (f StrTo) MustInt64() int64

func (StrTo) MustUint8

func (f StrTo) MustUint8() uint8

func (StrTo) String

func (f StrTo) String() string

func (StrTo) Uint8

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

Jump to

Keyboard shortcuts

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