utl

package
v0.0.0-...-185a503 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2017 License: Apache-2.0 Imports: 25 Imported by: 1

Documentation

Overview

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

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.

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

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

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

Index

Constants

View Source
const (
	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 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 Base64Encode

func Base64Encode(str string) string

base64 encode

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 ExecCmd

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

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

func ExecCmdBytes

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

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

func ExecCmdDir

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

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

func ExecCmdDirBytes

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

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

func Expand

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

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

func FetchFiles

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

FetchFiles fetches files specified by the rawURL field in parallel.

func FetchFilesCurl

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

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 GetAllSubDirs

func GetAllSubDirs(rootPath string) ([]string, error)

GetAllSubDirs returns all subdirectories of given root path. Slice does not include given path itself.

func GetCmdArg

func GetCmdArg(name string) string

取得命令行参数, 格式为 -name arg

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

func Int2HexStr(num int) (hex string)

Int2HexStr converts decimal number to hex format string.

func Int64SliceToStringSlice

func Int64SliceToStringSlice(sl []int64) []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 IsMobile

func IsMobile(number string) bool

validate string is a mobile phone number, if not return false

func IsSliceContainsInt

func IsSliceContainsInt(sl []int, i int) bool

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 MapToStruct

func MapToStruct(mapObj interface{}, structPtr interface{}, tagType string) error

将map根据指定的tag转为struct @param structPtr struct的实例指针 @param mapObj 为要存放数据的map @param tagType 为struct中要用的tag

func MustToInt

func MustToInt(value interface{}) int64

func Nl2br

func Nl2br(str string) string

change \n to <br/>

func Pipe

func Pipe(in io.Reader, out io.Writer) error

func PipeAndClose

func PipeAndClose(in io.ReadCloser, out io.WriteCloser) error

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 Reverse

func Reverse(s string) string

Reverse s string, support unicode

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 StringSliceToInt64Slice

func StringSliceToInt64Slice(sl []string) []int64

func StripTags

func StripTags(src string) string

strip tags in html string

func StructCopyByFields

func StructCopyByFields(src interface{}, dist interface{}, fields ...string)

将源struct的指定字段值拷贝到目标struct @param src 源 &struct{} @param dist 目标 &struct{} @param feilds 需要拷贝的字段名

func StructEmptyFields

func StructEmptyFields(dist interface{}, fields ...string)

将结构体的指定字段清空

func StructFieldMapByTag

func StructFieldMapByTag(structObj interface{}, tagType string, ignoreEmpty bool) map[string]string

将struct的字段和指定的tag对应起来 @param structObj struct的实例指针 @param tagType tag类型,如 `json:name`的tagType为json @param ignoreEmpty 是否忽略空tag,如果为false,当tag为空的时候会将字段的首字母小写来作为tag

func StructNewByFields

func StructNewByFields(src interface{}, fields ...string) interface{}

新实例化一个struct,并将源struct的指定字段值拷贝进去 @param src 源 &struct{} @param feilds 需要拷贝的字段名

func StructTagConvert

func StructTagConvert(obj map[string]interface{}, stp reflect.Type, srcTag, dstTag string) map[string]interface{}

将map中的key转为struct的另一个tag表示 @param obj map实例 @param stp truct类型 @param srcTag 原tag名,如json @param dstTag 目标tag名,如bson

func StructTagMapByField

func StructTagMapByField(structPtr interface{}, tagType string, ignoreEmpty bool) map[string]string

将struct的指定的tag和字段对应起来 @param structPtr struct的实例指针 @param tagType tag类型,如 `json:name`的tagType为json @param ignoreEmpty 是否忽略空tag,如果为false,当tag为空的时候会将字段的首字母小写来作为tag

func StructToMap

func StructToMap(structPtr interface{}, feilds interface{}, mapObj ...map[string]interface{}) map[string]interface{}

将struct的指定字段转到map中 @param structPtr struct的实例指针 @param feilds []string类型代表要取的字段,map[string]string类型代表字段映射 {"structFeild":"mapKey"}, 如果mapKey为空则使用structFeild做为key @param mapObj 要存放数据的map,如果传入的话会将数据放到这个map里

func StrutToMapByTag

func StrutToMapByTag(structPtr interface{}, v ...interface{}) map[string]interface{}

将struct转为map @param structPtr struct的实例指针 @param v 有四种情况: 1. 不传,将把struct的字段名首字母小写做为map的key 2. 包含string类型,将把struct字段中对应的tag做为map的key 3. 包含(map[string]interface{})类型, 将把数据存到这个map中 4. 包含bool类型,为true的话struct中字段值为空的字段不会加入map

func ToInt

func ToInt(value interface{}) (int64, error)

func ToStr

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

Convert any type to string.

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.

Types

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 Str

type Str string

Convert string to specify type.

func (Str) Exist

func (f Str) Exist() bool

func (Str) Float32

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

func (Str) Float64

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

func (Str) Int

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

func (Str) Int64

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

func (Str) MustFloat32

func (f Str) MustFloat32() float32

func (Str) MustFloat64

func (f Str) MustFloat64() float64

func (Str) MustInt

func (f Str) MustInt() int

func (Str) MustInt64

func (f Str) MustInt64() int64

func (Str) MustUint8

func (f Str) MustUint8() uint8

func (Str) String

func (f Str) String() string

func (Str) Uint8

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

Jump to

Keyboard shortcuts

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