com

package module
v0.0.0-...-7f23218 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2018 License: Apache-2.0 Imports: 27 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 and got PASS .

Documentation

Overview

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

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

func AESGCMDecrypt(key, ciphertext []byte) ([]byte, error)

AESGCMDecrypt decrypts ciphertext with the given key using AES in GCM mode.

func AESGCMEncrypt

func AESGCMEncrypt(key, plaintext []byte) ([]byte, error)

AESGCMEncrypt encrypts plaintext with the given key using AES in GCM mode.

func AppendStr

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

AppendStr appends string to slice with no duplicates.

Example
package main

import (
	"fmt"

	"github.com/bruinxs/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 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/bruinxs/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/bruinxs/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 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.

Example
package main

import (
	"fmt"

	"github.com/bruinxs/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/bruinxs/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/bruinxs/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/bruinxs/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 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 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.

Example
package main

import (
	"fmt"

	"github.com/bruinxs/com"
)

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

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/bruinxs/com"
)

func main() {
	srcPath, err := com.GetSrcPath("github.com/Unknwon/com")
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(srcPath)
}
Output:

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/bruinxs/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/bruinxs/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 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.

Example
package main

import (
	"io/ioutil"
	"net/http"

	"github.com/bruinxs/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/bruinxs/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/bruinxs/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, 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 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/bruinxs/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/bruinxs/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/bruinxs/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/bruinxs/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/bruinxs/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, 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

Example
package main

import (
	"fmt"

	"github.com/bruinxs/com"
)

func main() {
	fmt.Println(com.IsUrl("http://example.com"))
	fmt.Println(com.IsUrl("http//example.com"))
}
Output:

true
false

func ItoFloat64

func ItoFloat64(i interface{}) (float64, error)

ItoFloat64 convert interface to float64.

func ItoFloat64Must

func ItoFloat64Must(i interface{}) float64

ItoFloat64Must must convert interface to float64.

func ItoFloat64Slice

func ItoFloat64Slice(i interface{}) ([]float64, error)

ItoFloat64Slice convert interface to float64 slice.

func ItoFloat64SliceMust

func ItoFloat64SliceMust(i interface{}) []float64

ItoFloat64SliceMust convert interface to float64 slice.

func ItoInt

func ItoInt(i interface{}) (int, error)

ItoInt convert interface to int.

func ItoInt64

func ItoInt64(i interface{}) (int64, error)

ItoInt64 convert interface to int64.

func ItoInt64Must

func ItoInt64Must(i interface{}) int64

ItoInt64Must must convert interface to int64.

func ItoInt64Slice

func ItoInt64Slice(i interface{}) ([]int64, error)

ItoInt64Slice convert interface to int64 slice.

func ItoInt64SliceMust

func ItoInt64SliceMust(i interface{}) []int64

ItoInt64SliceMust convert interface to int64 slice.

func ItoIntMust

func ItoIntMust(i interface{}) int

ItoIntMust must convert interface to int.

func ItoIntSlice

func ItoIntSlice(i interface{}) ([]int, error)

ItoIntSlice convert interface to int slice.

func ItoIntSliceMust

func ItoIntSliceMust(i interface{}) []int

ItoIntSliceMust must convert interface to int slice.

func ItoSlice

func ItoSlice(i interface{}) []interface{}

ItoSlice convert interface to interface slice.

func ItoString

func ItoString(i interface{}) string

ItoString convert interface to string.

func ItoStringSlice

func ItoStringSlice(i interface{}) []string

ItoStringSlice convert interface to string slice.

func ItoUint64

func ItoUint64(i interface{}) (uint64, error)

ItoUint64 convert interface to uint64.

func ItoUint64Must

func ItoUint64Must(i interface{}) uint64

ItoUint64Must must convert interface to uint64.

func Json

func Json(v interface{}) string

Json must convert value to json string

func Nl2br

func Nl2br(str string) string

change \n to <br/>

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 Round

func Round(val float64, decimals int) float64

Round specify precision and rounding

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 StripTags

func StripTags(src string) string

strip tags in html string

func ToSnakeCase

func ToSnakeCase(str string) string

ToSnakeCase can convert all upper case characters in a string to underscore format.

Some samples.

"FirstName"  => "first_name"
"HTTPServer" => "http_server"
"NoHTTPS"    => "no_https"
"GO_PATH"    => "go_path"
"GO PATH"    => "go_path"      // space is converted to underscore.
"GO-PATH"    => "go_path"      // hyphen is converted to underscore.

From https://github.com/huandu/xstrings

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 Map

type Map map[string]interface{}

Map like a object

func ItoMap

func ItoMap(i interface{}) (Map, error)

ItoMap convert interface to Map.

func ItoMapMust

func ItoMapMust(i interface{}) Map

ItoMapMust must convert interface to Map.

func ItoMapSlice

func ItoMapSlice(i interface{}) ([]Map, error)

ItoMapSlice convert interface to Map slice.

func ItoMapSliceMust

func ItoMapSliceMust(i interface{}) []Map

ItoMapSliceMust must convert interface to Map slice.

func (Map) Exist

func (m Map) Exist(key string) bool

Exist check if exist the key

func (Map) Float64

func (m Map) Float64(key string) float64

Float64 get float64 value by key

func (Map) Float64Slice

func (m Map) Float64Slice(key string) []float64

Float64Slice get float64 slice by key

func (Map) Int

func (m Map) Int(key string) int

Int get int value by key

func (Map) Int64

func (m Map) Int64(key string) int64

Int64 get int64 value by key

func (Map) Int64Slice

func (m Map) Int64Slice(key string) []int64

Int64Slice get int64 slice by key

func (Map) IntSlice

func (m Map) IntSlice(key string) []int

IntSlice get int slice by key

func (Map) Map

func (m Map) Map(key string) Map

Map get map value by key

func (Map) MapSlice

func (m Map) MapSlice(key string) []Map

MapSlice get Map slice by key

func (Map) Set

func (m Map) Set(key string, value interface{}) Map

Set set value on key, if value is nil then remove it

func (Map) String

func (m Map) String(key string) string

String get string value by key

func (Map) StringSlice

func (m Map) StringSlice(key string) []string

StringSlice get string slice by key

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 StrTo

type StrTo string

Convert string to specify type.

func (StrTo) Exist

func (f StrTo) Exist() bool

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

func (f StrTo) MustFloat64() float64

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