utility

package module
v0.0.0-...-b9fdee4 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2018 License: Apache-2.0 Imports: 29 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

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

Index

Constants

View Source
const (
	B = 1 << (10 * iota)
	KB
	MB
	GB
	TB
	PB
	EB
)
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.

View Source
const (
	Uppercase    string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	Lowercase           = "abcdefghijklmnopqrstuvwxyz"
	Alphabetic          = Uppercase + Lowercase
	Numeric             = "0123456789"
	Alphanumeric        = Alphabetic + Numeric
	Symbols             = "`" + `~!@#$%^&*()-_+={}[]|\;:"<>,./?`
	Hex                 = Numeric + "abcdef"
)

Charsets

View Source
const (
	LAYOUT_FORMAT19 = "2006-01-02 15:04:05"
	LAYOUT_FORMAT14 = "20060102150405"
	LAYOUT_FORMAT10 = "2006-01-02"
	LAYOUT_FORMAT8  = "20060102"
	LAYOUT_FORMAT17 = "20060102 15:04:05"
)
View Source
const (
	ACCURACY = 0.00001 //精度
)
View Source
const (
	UNDERLINE = "_"
)

Variables

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 AESDecrypt

func AESDecrypt(key, text []byte) ([]byte, error)

AESDecrypt decrypts text and given key with AES.

func AESEncrypt

func AESEncrypt(key, text []byte) ([]byte, error)

AESEncrypt encrypts text and given key with AES.

func AppendStr

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

AppendStr appends string to slice with no duplicates.

func Base64Decode

func Base64Decode(str string) (string, error)

base64 decode

func Base64Decode_

func Base64Decode_(str string) ([]byte, error)

base64 decode

func Base64Encode

func Base64Encode(str string) string

base64 encode

func Base64Encode_

func Base64Encode_(str []byte) string

base64 encode

func BeBig

func BeBig(source, compare float64) bool

BeBig 比大

func BeBigOrEqual

func BeBigOrEqual(source, compare float64) bool

BeBigOrEqual 大于等于

func BeEqual

func BeEqual(source, compare float64) bool

相等

func BeSmall

func BeSmall(source, compare float64) bool

BeSmall 比小

func BeSmallOrEqual

func BeSmallOrEqual(source, compare float64) bool

BeSmallOrEqual 小于等于

func BytesFormat

func BytesFormat(b int64) string

Format wraps global Bytes's Format function.

func BytesParse

func BytesParse(val string) (int64, error)

Parse wraps global Bytes's Parse function.

func Camel2Underline

func Camel2Underline(s string) string

camel2Underline:snake string, XxYy to xx_yy , XxYY to xx_yy

func ColorLog

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

ColorLog prints colored log to stdout. See color rules in function 'ColorLogS'.

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.

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

func Decrypt3(key, src []byte) ([]byte, error)

func DesDecrypt

func DesDecrypt(src, key []byte) ([]byte, error)

func DesDecryptIv

func DesDecryptIv(crypted, key, iv []byte) ([]byte, error)

func DesEncrypt

func DesEncrypt(src, key []byte) (string, error)

func DesEncryptIv

func DesEncryptIv(origData, key, iv []byte) (string, error)

func Encrypt3

func Encrypt3(key1 string, src []byte) (string, error)

func EncryptDesECB

func EncryptDesECB(ori, key []byte) ([]byte, error)

3des ecb PKCS7

func ExecCmd

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

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

func ExecCmdBytes

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

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

func ExecCmdDir

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

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

func ExecCmdDirBytes

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

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

func ExecPath

func ExecPath() (string, error)

func Expand

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

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

func FetchFiles

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

FetchFiles fetches files specified by the rawURL field in parallel.

func FetchFilesCurl

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

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

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 Format10

func Format10(time time.Time) string

Format10 format date YYYY-MM-DD

func Format10ToTimestamp

func Format10ToTimestamp(formatTime string) (int, error)

Format10ToTimestamp 格式化的时间(YYYY-MM-DD)转时间戳

func Format14

func Format14(time time.Time) string

Format14 format date YYYYMMDDHHmmss

func Format14ToTimestamp

func Format14ToTimestamp(formatTime string) (int, error)

Format14ToTimestamp 格式化的时间(YYYYMMDDHHmmss)转时间戳

func Format17

func Format17(time time.Time) string

Format17 format date YYYYMMDD HH:mm:ss

func Format17ToTimestamp

func Format17ToTimestamp(formatTime string) (int, error)

Format17ToTimestamp 格式化的时间(YYYYMMDD HH:mm:ss)转时间戳

func Format19

func Format19(time time.Time) string

Format19 format date YYYY-MM-DD HH:mm:ss

func Format19ToTimestamp

func Format19ToTimestamp(formatTime string) (int, error)

Format19ToTimestamp 格式化的时间(YYYY-MM-DD HH:mm:ss)转时间戳

func Format8

func Format8(time time.Time) string

Format8 format date YYYYMMDD

func Format8ToTimestamp

func Format8ToTimestamp(formatTime string) (int, error)

Format8ToTimestamp 格式化的时间(YYYYMMDD)转时间戳

func Generate

func Generate() 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 GetFileListBySuffix

func GetFileListBySuffix(dirPath, suffix string) ([]string, error)

GetFileListBySuffix returns an ordered list of file paths. It recognize if given path is a file, and don't do recursive find.

func GetGOPATHs

func GetGOPATHs() []string

GetGOPATHs returns all paths in GOPATH variable.

func GetNightTimestamp

func GetNightTimestamp(day int) int

GetNightTimestamp 获取前一天的时间戳:day = -1 , 获取今天晚上的时间戳:0 ,获取明天的凌晨时间戳:1

func GetNowTime

func GetNowTime() time.Time

GetNowTime get current time

func GetNowTimestamp

func GetNowTimestamp() int

GetNowTimestamp get current timestamp

func GetSrcPath

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

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

func GetTimeIntervalDay

func GetTimeIntervalDay(day int) int

GetTimeIntervalDay 与当前时间的时间间隔 单位天 如 GetTimeIntervalDay(1) 为延后一天

func HexStr2int

func HexStr2int(hexStr string) (int, error)

HexStr2int converts hex format string to decimal number.

func HomeDir

func HomeDir() (home string, err error)

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

func Html2JS

func Html2JS(data []byte) []byte

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

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 HttpCall

func HttpCall(client *http.Client, method, url string, header http.Header, body io.Reader) (io.ReadCloser, error)

HttpCall makes HTTP method call.

func HttpGet

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

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

func HttpGetBytes

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

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

func HttpGetJSON

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

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

func HttpGetToFile

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

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

func HttpPost

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

HttpPost posts the specified resource. ErrNotFound is returned if the server responds with status 404.

func HttpPostJSON

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

HttpPostJSON posts the specified resource with struct values, and maps results to struct. ErrNotFound is returned if the server responds with status 404.

func HumaneFileSize

func HumaneFileSize(s uint64) string

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

func If

func If(condition bool, trueVal, falseVal interface{}) interface{}

If 三元表达式

func Int2HexStr

func Int2HexStr(num int) (hex string)

Int2HexStr converts decimal number to hex format string.

func IntSliceDeduplication

func IntSliceDeduplication(ints []int) []int

IntSliceDeduplication int的切片去重复

func Ints2Strings

func Ints2Strings(src []int) []string

Ints2Strings []int转[]string

func IsDir

func IsDir(dir string) bool

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

func IsEmail

func IsEmail(email string) bool

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

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.

func IsFile

func IsFile(filePath string) bool

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

func IsLetter

func IsLetter(l uint8) bool

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

func 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, ignore case.

func IsUrl

func IsUrl(url string) bool

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

func Md5

func Md5(str string) string

func Md5_16

func Md5_16(str string) []byte

func MysqlFilter

func MysqlFilter(key string) string

func NewECBEncrypter

func NewECBEncrypter(b cipher.Block) cipher.BlockMode

返回ECB方式的加密器

func Nl2br

func Nl2br(str string) string

change \n to <br/>

func PKCS5Padding

func PKCS5Padding(ciphertext []byte, blockSize int) []byte

func PKCS5UnPadding

func PKCS5UnPadding(origData []byte) []byte

func PKCS7Padding

func PKCS7Padding(src []byte) []byte

PKCS7Padding pads as prescribed by the PKCS7 standard

func PKCS7UnPadding

func PKCS7UnPadding(src []byte) ([]byte, error)

PKCS7UnPadding unpads as prescribed by the PKCS7 standard

func ParseInLocation

func ParseInLocation(layout string, value string) (time.Time, error)

ParseInLocation 根据格式解析格式化为字符串的的时间

func PasswordEncrypt

func PasswordEncrypt(account, password string) string

PasswordEncrypt

func PowInt

func PowInt(x int, y int) int

PowInt is int type of math.Pow function.

func RandomCreateBytes

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

RandomCreateBytes generate random []byte by specify chars.

func RandomString

func RandomString(length uint8, charsets ...string) string

func Reverse

func Reverse(s string) string

Reverse s string, support unicode

func Round

func Round(f float64, n int) float64

Round 浮点型精准问题矫正

func Sha256

func Sha256(str string) string

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 Strings2Ints

func Strings2Ints(src []string) (dst []int, err error)

[]string 转 []int

func Strings2IntsAsc

func Strings2IntsAsc(src []string) (dst []int, err error)

[]string 转 []int 排序从小到大

func StripTags

func StripTags(src string) string

strip tags in html string

func SubString

func SubString(str string, begin, length int) string

func SubstrByByte

func SubstrByByte(str string, length int) string

按字节截取字符串 utf-8不乱码

func TimeIntervalDay

func TimeIntervalDay(t1, t2 time.Time) int

TimeIntervalDay 计算两个时间相隔多少天

func TimeIntervalSecond

func TimeIntervalSecond(time1 time.Time, time2 time.Time) int

TimeIntervalSecond 两个时间相隔秒数

func TimeSub

func TimeSub(t1, t2 time.Time) int

计算两个时间相隔多少天

func ToFixed

func ToFixed(l float64, n float64) float64

ToFixed 自定义小数位精度.

func ToFixed10K

func ToFixed10K(l float64) float64

ToFixed10K 4位小数精度

func ToStr

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

Convert any type to string.

func Underline2Camel

func Underline2Camel(s string) string

underline2Camel camel string, xx_yy to XxYy 大驼峰

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, perm os.FileMode) 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 ZeroPadding

func ZeroPadding(ciphertext []byte, blockSize int) []byte

func ZeroUnPadding

func ZeroUnPadding(origData []byte) []byte

Types

type Bytes

type Bytes struct {
}

func New

func New() *Bytes

New creates a Bytes instance.

func (*Bytes) Format

func (*Bytes) Format(b int64) string

Format formats bytes integer to human readable string. For example, 31323 bytes will return 30.59KB.

func (*Bytes) Parse

func (*Bytes) Parse(value string) (i int64, err error)

Parse parses human readable bytes string to bytes integer. For example, 6GB (6G is also valid) will return 6442450944.

type NotFoundError

type NotFoundError struct {
	Message string
}

func (NotFoundError) Error

func (e NotFoundError) Error() string

type Random

type Random struct {
}

func RandomNew

func RandomNew() *Random

func (*Random) String

func (r *Random) String(length uint8, charsets ...string) 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 StrTo

type StrTo string

Convert string to specify type.

func (StrTo) Exist

func (f StrTo) Exist() bool

func (StrTo) Float32

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

func (StrTo) Float64

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

func (StrTo) Int

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

func (StrTo) Int64

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

func (StrTo) 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