com

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

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

Go to latest
Published: Apr 22, 2014 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.1

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

Examples

Constants

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

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

func Basename(file string) string

get filepath base name

func ColorLog

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

ColorLog colors log and print 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 Copy

func Copy(srcPath, destPath string) error

Copy copies file from source to target path. It returns false and error when error occurs in underlying functions.

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

func Dirname(file string) string

get filepath dir name

func ExecCmd

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

ExecCmd executes system command and returns output, stderr(both string type) and 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)

func ExecCmdDir

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

ExecCmd executes system command and returns output, stderr(both string type) and error in given work directory.

func ExecCmdDirBytes

func ExecCmdDirBytes(dir, cmdName string, args ...string) ([]byte, []byte, 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 Explode

func Explode(str string, sep string) []string

explode string with proper chars

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 FileMTime

func FileMTime(file string) (int64, error)

get file modified time

func FileSize

func FileSize(file string) (int64, error)

get file size as how many bytes

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

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

func IsDir(dir string) bool

IsDir checks whether the path is a directory. It 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 checks whether the path is a file, it 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 IsSliceContainsStr

func IsSliceContainsStr(sl []string, str string) bool

IsSliceContainsStr returns true if a 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 Join

func Join(str []string, sep string) string

join string array to string with connection chars

func Ltrim

func Ltrim(str string) string

trim space on left

func Md5

func Md5(str string) string

md5 hash string

func Nl2br

func Nl2br(str string) string

change \n to <br/>

func Now

func Now() int64

Get unix stamp int64 of now

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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	b, err := com.ReadFile("SaveFile.txt")
	fmt.Println(string(b), err)
}
Output:

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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	s, err := com.ReadFileS("SaveFileS.txt")
	fmt.Println(s, err)
}
Output:

func RealPath

func RealPath(file string) (string, error)

get absolute filepath, based on built executable 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 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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	s := "ExampleSaveFile"
	n, err := com.SaveFile("SaveFile.txt", []byte(s))
	fmt.Println(n, err)
}
Output:

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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	s := "ExampleSaveFileS"
	n, err := com.SaveFileS("SaveFileS.txt", s)
	fmt.Println(n, err)
}
Output:

func Sha1

func Sha1(str string) string

sha1 hash string

func Sha256

func Sha256(str string) string

sha256 hash string

func StatDir

func StatDir(dirPath 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 StrPos

func StrPos(str string, find string) int

find the first occur position, if not found return -1

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 StrToLower

func StrToLower(str string) string

convert to lower

func StrToUpper

func StrToUpper(str string) string

convert to upper

func StripTags

func StripTags(src string) string

strip tags in html string

func SubStr

func SubStr(str string, start, length int) string

substring from start position and belong length

func Trim

func Trim(str string) string

trim space in all string length

func UcFirst

func UcFirst(str string) string

convert first letter to upper

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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	dirs, err := com.UnTarGz("src/file/path", "dest/file/path")
	fmt.Println(dirs, err)
}
Output:

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.

Example
package main

import (
	"fmt"

	"github.com/Unknwon/com"
)

func main() {
	dirs, err := com.Unzip("src/file/path", "dest/file/path")
	fmt.Println(dirs, err)
}
Output:

func UrlDecode

func UrlDecode(str string) (string, error)

url decode string

func UrlEncode

func UrlEncode(str string) string

url encode string, is + not %20

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

Jump to

Keyboard shortcuts

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