util

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2021 License: Apache-2.0 Imports: 34 Imported by: 0

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.

View Source
const (
	Minute = 60
	Hour   = 60 * Minute
	Day    = 24 * Hour
	Week   = 7 * Day
	Month  = 30 * Day
	Year   = 12 * Month
)

Seconds-based time units

Variables

View Source
var Rander = rand.New(rand.NewSource(time.Now().UnixNano()))
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 added in v0.0.9

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

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

func AESGCMEncrypt added in v0.0.9

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

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

func AddDaysForCurrent

func AddDaysForCurrent(days int) time.Time

* 在当前的日期时间增加指定的天数,返回日期时间 *

func AddHoursForCurrent

func AddHoursForCurrent(hours int) time.Time

* 在当前的日期时间增加指定的小时数,返回日期时间 *

func AddMinutesForCurrent

func AddMinutesForCurrent(minutes int) time.Time

* 在当前的日期时间增加指定的分钟数,返回日期时间 *

func AorB

func AorB(condition bool, a, b string) string

func AppendStr added in v0.0.9

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

AppendStr appends string to slice with no duplicates.

Example
package main

import (
	"fmt"
	"github.com/qtoad/myxgo-plusplus/util"
)

func main() {
	s := []string{"a"}
	s = util.AppendStr(s, "a")
	s = util.AppendStr(s, "b")
	fmt.Println(s)
}
Output:

[a b]

func Base64Decode added in v0.0.9

func Base64Decode(str string) (string, error)

base64 decode

func Base64Encode added in v0.0.9

func Base64Encode(str string) string

base64 encode

func Br2String

func Br2String(source string) string

* 换行转br标签 *

func ColorLog added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

func main() {
	util.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 added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

func main() {
	coloredLog := util.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 Command

func Command(cmd string, args ...string) (string, error)

* 运行命令 *

func CompareSliceStr added in v0.0.9

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 added in v0.0.9

func CompareSliceStrU(s1, s2 []string) bool

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

func CompareVersion

func CompareVersion(src, toCompare string) bool

func CompressedHTML

func CompressedHTML(h *template.HTML)

func Copy added in v0.0.9

func Copy(src, dest string) error

Copy copies file from source to target path.

func CopyDir added in v0.0.9

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 CopyMap

func CopyMap(m map[string]string) map[string]string

func CurrentTimeToString

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

* 时间转字符串 *

func Date added in v0.0.9

func Date(ti int64, format string) string

Format unix time int64 to string

func DateParse added in v0.0.9

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

Parse Date use PHP time format.

func DateS added in v0.0.9

func DateS(ts string, format string) string

Format unix time string to string

func DateT added in v0.0.9

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 DateToIntSlice

func DateToIntSlice(date time.Time) []int

* 日期转成int切片 *

func DateToStringSlice

func DateToStringSlice(date time.Time) []string

* 日期转成日期字符串切片 *

func DateToUnixNanoTimestamp

func DateToUnixNanoTimestamp(date time.Time) int64

* 获取指定日期的Unix纳秒时间戳 *

func DateToUnixTimestamp

func DateToUnixTimestamp(date time.Time) int64

* 获取指定日期的Unix秒时间戳 *

func DatetimeAdd

func DatetimeAdd(firstDatetime time.Time, duration time.Duration) time.Time

* firstDatetime加上时间间隔duration,返回日期时间 *

func DatetimeAddDay

func DatetimeAddDay(firstDatetime time.Time, dayValue int) time.Time

* firstDatetime加上指定的天数,返回日期时间 *

func DatetimeAddHour

func DatetimeAddHour(firstDatetime time.Time, hourValue int) time.Time

* firstDatetime加上指定的小时数,返回日期时间 *

func DatetimeAddMinute

func DatetimeAddMinute(firstDatetime time.Time, minuteValue int) time.Time

* firstDatetime加上指定的分钟数,返回日期时间 *

func DatetimeAddSecond

func DatetimeAddSecond(firstDatetime time.Time, secondValue int) time.Time

* firstDatetime加上指定的秒数,返回日期时间 *

func DatetimeSub

func DatetimeSub(firstDatetime, secondDatetime time.Time) time.Duration

* firstDatetime减去secondDatetime,返回时间间隔 *

func EmailFilter

func EmailFilter(source string) string

* 电子邮件过滤 *

func ExecCmd added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

func main() {
	stdout, stderr, err := util.ExecCmd("go", "help", "get")
	fmt.Println(stdout, stderr, err)
}
Output:

func ExecCmdBytes added in v0.0.9

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 added in v0.0.9

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 added in v0.0.9

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 added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

func main() {
	match := map[string]string{
		"domain":    "gowalker.org",
		"subdomain": "github.com",
	}
	s := "http://{domain}/{subdomain}/{0}/{1}"
	fmt.Println(util.Expand(s, match, "unknwon", "gowalker"))
}
Output:

http://gowalker.org/github.com/unknwon/gowalker

func FetchFiles added in v0.0.9

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"
	"github.com/qtoad/myxgo-plusplus/util"
	"net/http"
)

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 := []util.RawFile{
		&rawFile{rawURL: "http://example.com"},
		&rawFile{rawURL: "http://example.com/foo"},
	}
	err := util.FetchFiles(&http.Client{}, files, nil)
	fmt.Println(err, len(files[0].Data()), len(files[1].Data()))
}
Output:

func FetchFilesCurl added in v0.0.9

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

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

Example
package main

import (
	"fmt"
	"github.com/qtoad/myxgo-plusplus/util"
)

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 := []util.RawFile{
		&rawFile{rawURL: "http://example.com"},
		&rawFile{rawURL: "http://example.com/foo"},
	}
	err := util.FetchFilesCurl(files)
	fmt.Println(err, len(files[0].Data()), len(files[1].Data()))
}
Output:

func FileMTime added in v0.0.9

func FileMTime(file string) (int64, error)

FileMTime returns file modified time and possible error.

func FileSize added in v0.0.9

func FileSize(file string) (int64, error)

FileSize returns file size in bytes and possible error.

func FilterHostProtocol

func FilterHostProtocol(path string) string

* 过滤主机协议 *

func FilterInt64Slice

func FilterInt64Slice(all, other []int64) []int64

* 过滤int64数组(从all中过滤所有other中的数据,返回未被过滤的数据集合) *

func FilterStringSlice

func FilterStringSlice(all, other []string) []string

* 过滤字符数组(从all中过滤所有other中的数据,返回未被过滤的数据集合) *

func FilterUint64Slice

func FilterUint64Slice(all, other []uint64) []uint64

* 过滤uint64数组(从all中过滤所有other中的数据,返回未被过滤的数据集合) *

func Float64ToString

func Float64ToString(value float64) string

* 浮点64转为字符串 *

func FromBase64

func FromBase64(data string, args ...bool) (string, error)

* Base64字符解码 *

func FromJson

func FromJson(jsonString string, object interface{}) error

* Json字符串转换成对象 *

func FromXml

func FromXml(xmlString string, object interface{}) error

* Xml字符串转换成对象 *

func GetAllSubDirs added in v0.0.9

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

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

func GetCurrentDay

func GetCurrentDay() int32

* 获取当前日 *

func GetCurrentDayCount

func GetCurrentDayCount(args ...time.Time) int

* 获取当前日期月份对应的天数 *

func GetCurrentHour

func GetCurrentHour() int32

* 获取当前小时 *

func GetCurrentMinute

func GetCurrentMinute() int32

* 获取当前分钟 *

func GetCurrentMonth

func GetCurrentMonth() int32

* 获取当前月份 *

func GetCurrentMonthMaxDate

func GetCurrentMonthMaxDate(args ...time.Time) time.Time

* 获取当月里最大日期时间(2016-01-02 23:59:59 999999999) *

func GetCurrentMonthMaxNanoTimestamp

func GetCurrentMonthMaxNanoTimestamp(args ...time.Time) int64

* 获取当月里最大日期时间戳(当月最后一天最大时间),单位纳秒 *

func GetCurrentMonthMaxTimestamp

func GetCurrentMonthMaxTimestamp(args ...time.Time) int64

* 获取当月里最大日期时间戳(当月最后一天最大时间),单位秒 *

func GetCurrentMonthMinDate

func GetCurrentMonthMinDate(args ...time.Time) time.Time

* 获取当月里最小日期时间(2016-01-01 0:0:0 0) *

func GetCurrentMonthMinNanoTimestamp

func GetCurrentMonthMinNanoTimestamp(args ...time.Time) int64

* 获取当月里最小日期时间戳(当月第一天最小时间),单位纳秒 *

func GetCurrentMonthMinTimestamp

func GetCurrentMonthMinTimestamp(args ...time.Time) int64

* 获取当月里最小日期时间戳(当月第一天最小时间),单位秒 *

func GetCurrentSecond

func GetCurrentSecond() int32

* 获取当前秒数 *

func GetCurrentTime

func GetCurrentTime() time.Time

func GetCurrentTimeStr

func GetCurrentTimeStr() string

func GetCurrentTimeUnix

func GetCurrentTimeUnix() int64

func GetCurrentWeek

func GetCurrentWeek() int

* 获取当前日期是周几(1:周一|2:周二|...|7:周日) *

func GetCurrentWeekDayRange

func GetCurrentWeekDayRange() (int, int)

* 获取当前周对应的月份里的日期范围(minDay in month, maxDay in month) *

func GetCurrentYear

func GetCurrentYear() int32

* 获取当前年份 *

func GetDateDay

func GetDateDay(datetime time.Time) int32

* 获取日期时间的日部分 *

func GetDateHour

func GetDateHour(datetime time.Time) int32

* 获取日期时间的小时部分 *

func GetDateMinute

func GetDateMinute(datetime time.Time) int32

* 获取日期时间的分钟部分 *

func GetDateMonth

func GetDateMonth(datetime time.Time) int32

* 获取日期时间的月份 *

func GetDateRangeForWeekInDateRange

func GetDateRangeForWeekInDateRange(startDate, endDate time.Time, week int) []time.Time

* 获取日期范围内的所属周几的日期集合 * week:从1开始,1表示周一,依次类推 *

func GetDateSecond

func GetDateSecond(datetime time.Time) int32

* 获取日期时间的秒部分 *

func GetDateYear

func GetDateYear(datetime time.Time) int32

* 获取日期时间的年份 *

func GetDateYearMonthDay

func GetDateYearMonthDay(args ...time.Time) int

* 获取当前年月日的整型数字值 *

func GetDatetimeForDateAndTimeString

func GetDatetimeForDateAndTimeString(date time.Time, timeString string) time.Time

* 日期时间的日期部分和时间字符串连接,返回日期时间 *

func GetDatetimeWeekString

func GetDatetimeWeekString(datetime time.Time) string

* 获取日期时间的日期和星期字符串 *

func GetDayCount

func GetDayCount(datetime time.Time) int

* 获取指定日期月份对应的天数 *

func GetField added in v0.0.8

func GetField(v reflect.Value, i int) reflect.Value

func GetFileListBySuffix added in v0.0.9

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 added in v0.0.9

func GetGOPATHs() []string

GetGOPATHs returns all paths in GOPATH variable.

Example
package main

import (
	"fmt"
	"github.com/qtoad/myxgo-plusplus/util"
)

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

func GetMaxDate

func GetMaxDate(dtTime time.Time) time.Time

* 返回日期的最大日期时间(2016-01-02 23:59:59 999999999) *

func GetMaxDateNanoTimestamp

func GetMaxDateNanoTimestamp(dtTime time.Time) int64

* 获取日期的最大日期时间戳,单位纳秒 *

func GetMaxDateTimestamp

func GetMaxDateTimestamp(dtTime time.Time) int64

* 获取日期的最大日期时间戳,单位秒 *

func GetMinDate

func GetMinDate(dtTime time.Time) time.Time

* 返回日期的最小日期时间(2016-01-02 00:00:00) *

func GetMinDateNanoTimestamp

func GetMinDateNanoTimestamp(dtTime time.Time) int64

* 获取日期的最小日期时间戳,单位纳秒 *

func GetMinDateTimestamp

func GetMinDateTimestamp(dtTime time.Time) int64

* 获取日期的最小日期时间戳,单位秒 *

func GetNow

func GetNow() time.Time

* 获取当前Local日期时间 *

func GetSrcPath added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

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

func GetStringCount

func GetStringCount(sourceString string) int

* 获取字符串个数(不是字节数) *

func GetSubString

func GetSubString(sourceString string, count int, args ...string) string

* 获取指定长度的字符串 *

func GetTimeIntervalStringSlice

func GetTimeIntervalStringSlice(startDate, endDate time.Time, minutes int64) []string

* 获取一段时间范围内指定间隔的时间段集合 *

func GetTokenString

func GetTokenString() string

* 获取当前唯一Token字符串 *

func GetUint64SliceRange

func GetUint64SliceRange(int64Slice []uint64, count int) []uint64

* 获取指定个数的uint64slice *

func GetUtcNow

func GetUtcNow() time.Time

* 获取当前Utc日期时间 *

func GetWeek

func GetWeek(datetime time.Time) int

* 获取指定的日期是周几(1:周一|2:周二|...|7:周日) *

func HasPrefix

func HasPrefix(content, target string) bool

* 判断内容字符串头是否包含指定的字符串 *

func HasPrefixSuffix

func HasPrefixSuffix(content, target string) bool

* 判断内容字符串头尾是否包含指定的字符串 *

func HasSuffix

func HasSuffix(content, target string) bool

* 判断内容字符串尾是否包含指定的字符串 *

func HexStr2int added in v0.0.9

func HexStr2int(hexStr string) (int, error)

HexStr2int converts hex format string to decimal number.

func HomeDir added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

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

func Html2JS added in v0.0.9

func Html2JS(data []byte) []byte

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

Example
package main

import (
	"fmt"
	"github.com/qtoad/myxgo-plusplus/util"
)

func main() {
	htm := "<div id=\"button\" class=\"btn\">Click me</div>\n\r"
	js := string(util.Html2JS([]byte(htm)))
	fmt.Println(js)
}
Output:

<div id=\"button\" class=\"btn\">Click me</div>\n

func HtmlDecode added in v0.0.9

func HtmlDecode(str string) string

HtmlDecode decodes string to html chars

func HtmlEncode added in v0.0.9

func HtmlEncode(str string) string

encode html chars to string

func HtmlToPureText

func HtmlToPureText(html string) string

func HttpCall added in v0.0.9

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

HttpCall makes HTTP method call.

func HttpGet added in v0.0.9

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 added in v0.0.9

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 added in v0.0.9

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 added in v0.0.9

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 added in v0.0.9

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 added in v0.0.9

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 added in v0.0.9

func HumaneFileSize(s uint64) string

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

func IdCardNumFilter

func IdCardNumFilter(source string) string

* 身份证号过滤 *

func InArray

func InArray(arr []string, str string) bool

func Int2HexStr added in v0.0.9

func Int2HexStr(num int) (hex string)

Int2HexStr converts decimal number to hex format string.

func Int64Diff

func Int64Diff(one, two []int64) []int64

* int64差集合 *

func Int64Inter

func Int64Inter(one, two []int64) []int64

* int64交集合 *

func Int64SliceToString

func Int64SliceToString(intSlice []int64, args ...string) string

* 用指定的字符串把int64切片链接为字符串 *

func Int64SliceToStringSlice

func Int64SliceToStringSlice(values []int64) []string

* 整型64切片转为字符串切片 *

func Int64ToString

func Int64ToString(value int64) string

* 整型64转为字符串 *

func Int64Union

func Int64Union(one, two []int64) []int64

* int64并集合 *

func IntSliceToDate

func IntSliceToDate(intSlice []int) (time.Time, error)

* int切片转成日期 *

func IsAlpha

func IsAlpha(sourceString string, args ...interface{}) bool

* 是否英文单词 *

func IsAlphaOrNumber

func IsAlphaOrNumber(sourceString string) bool

* 是否英文单词或数字 *

func IsChinese

func IsChinese(sourceString string, args ...interface{}) bool

* 是否中文 *

func IsDateGreaterThan

func IsDateGreaterThan(firstDatetime, secondDatetime time.Time) bool

* 判断firstDatetime是否在secondDatetime的后面,即firstDatetime比secondDatetime日期大 *

func IsDateLessThan

func IsDateLessThan(firstDatetime, secondDatetime time.Time) bool

* 判断firstDatetime是否在secondDatetime的前面,即firstDatetime比secondDatetime日期小 *

func IsDecimals

func IsDecimals(str ...string) bool

纯小数

func IsDir added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

func main() {
	if util.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

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

Example
package main

import (
	"fmt"
	"github.com/qtoad/myxgo-plusplus/util"
)

func main() {
	fmt.Println(util.IsEmail("test@example.com"))
	fmt.Println(util.IsEmail("@example.com"))
}
Output:

true
false

func IsEmail2 added in v0.0.9

func IsEmail2(sourceString string, args ...interface{}) bool

* 是否电子邮件 *

func IsEmailRFC added in v0.0.9

func IsEmailRFC(email string) bool

IsEmailRFC validates string is an email address, if not return false this validation omits RFC 2822

func IsEngishLowCase

func IsEngishLowCase(str ...string) bool

************************ 英文类型 ************************ 仅小写

func IsEnglish

func IsEnglish(str ...string) bool

大小写混合

func IsEnglishCap

func IsEnglishCap(str ...string) bool

仅大写

func IsExist added in v0.0.9

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/qtoad/myxgo-plusplus/util"
)

func main() {
	if util.IsExist("file.go") {
		fmt.Println("file.go exists")
		return
	}
	fmt.Println("file.go does not exist")
}
Output:

func IsFile added in v0.0.8

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/qtoad/myxgo-plusplus/util"
)

func main() {
	if util.IsFile("file.go") {
		fmt.Println("file.go exists")
		return
	}
	fmt.Println("file.go is not a file or does not exist")
}
Output:

func IsID

func IsID(str ...string) bool

************************ 自定义类型 *********************** 数字+字母 不限制大小写 6~30位

func IsIdCardNum

func IsIdCardNum(sourceString string) bool

* 是否身份证号码 *

func IsInteger

func IsInteger(str ...string) bool

************************ 数字类型 *********************** 纯整数

func IsJSON

func IsJSON(str string) bool

func IsLetter added in v0.0.9

func IsLetter(l uint8) bool

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

Example
package main

import (
	"fmt"
	"github.com/qtoad/myxgo-plusplus/util"
)

func main() {
	fmt.Println(util.IsLetter('1'))
	fmt.Println(util.IsLetter('['))
	fmt.Println(util.IsLetter('a'))
	fmt.Println(util.IsLetter('Z'))
}
Output:

false
false
true
true

func IsMatchStringSliceCount

func IsMatchStringSliceCount(srcSlice []string, maxCount, stringItemCount int) bool

* 判断字符串切片及单个项的字符数是否匹配指定大小, *

func IsMobile

func IsMobile(sourceString string) bool

* 是否手机号码 *

func IsNumber

func IsNumber(sourceString string, args ...interface{}) bool

* 是否数字 *

func IsPwd

func IsPwd(str ...string) bool

数字+字母+符号 6~30位

func IsRegexpMatch

func IsRegexpMatch(sourceString string, pattern string) bool

* 正则是否匹配 *

func IsSliceContainsInt64 added in v0.0.9

func IsSliceContainsInt64(sl []int64, i int64) bool

IsSliceContainsInt64 returns true if the int64 exists in given slice.

func IsSliceContainsStr added in v0.0.9

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

IsSliceContainsStr returns true if the string exists in given slice, ignore case.

func IsSql

func IsSql(source string) bool

* 判断是否sql *

func IsTelphone

func IsTelphone(sourceString string) bool

* 是否电话号码 *

func IsUrl added in v0.0.9

func IsUrl(url string) bool

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

Example
package main

import (
	"fmt"
	"github.com/qtoad/myxgo-plusplus/util"
)

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

true
false

func IsUsername

func IsUsername(sourceString string, args ...interface{}) bool

* 是否用户名(以英文字母开头,后面跟英文字母和数据以及下划线) *

func JSON

func JSON(a interface{}) string

func JoinMapToString

func JoinMapToString(params map[string]string, filterKeys []string, isEscape bool) string

* 字典参数升序排序,组成键=值集合,然后把集合用&拼接成字符串 *

func JsonToStruct

func JsonToStruct(data string, value interface{}) error

func LgetAllSubDirs added in v0.0.9

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

LgetAllSubDirs returns all subdirectories of given root path, including following symbolic links, if any. Slice does not include given path itself.

func LstatDir added in v0.0.9

func LstatDir(rootPath string, includeDir ...bool) ([]string, error)

LstatDir gathers information of given directory by depth-first. It returns slice of file list, follows symbolic links 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 MapDataSign

func MapDataSign(params map[string]string, secret string) (string, bool)

* 签名算法 * params里的每个Value都需要进行url编码 * fmt.Sprintf("%s=%s", key, url.QueryEscape(value)) *

func Match

func Match(p string, s string) bool

func Min

func Min(x, y int) int

func MinutesToTimeString

func MinutesToTimeString(minutes int64) string

* 分钟数转时间字符串(HH:mm:ss) *

func MobileFilter

func MobileFilter(source string) string

* 手机号过滤 *

func ModFloat64

func ModFloat64(value float64, length int) float64

* 保留浮点数指定长度的小数位数 *

func MonthsToSeasons

func MonthsToSeasons(months []int32) []string

* 月份数值集合转换成季节名集合 *

func Nl2br added in v0.0.9

func Nl2br(str string) string

change \n to <br/>

func Nonzero added in v0.0.8

func Nonzero(v reflect.Value) bool

func PackageName

func PackageName(v interface{}) string

func ParseBool

func ParseBool(s string) bool

func ParseFloat32

func ParseFloat32(f string) float32

func ParseHTML

func ParseHTML(name, tmpl string, param interface{}) template.HTML

func ParseText

func ParseText(name, tmpl string, param interface{}) string

func ParseTime

func ParseTime(stringTime string) time.Time

func PowInt added in v0.0.9

func PowInt(x int, y int) int

PowInt is int type of math.Pow function.

func ProcessID added in v0.0.9

func ProcessID(processName string) (int, error)

* 根据进程名称找到对应的pid *

func ProcessStart added in v0.0.9

func ProcessStart(processName string) (string, error)

* 运行指定的进程 *

func ProcessStop added in v0.0.9

func ProcessStop(processName string) (string, error)

* 杀死指定pid进程 *

func RandNum

func RandNum(min, max int) int

包含min, max

func RandNumStr

func RandNumStr(n int) string

func RandOrd

func RandOrd(n int) string

func RandStr

func RandStr(n int, letter string) string

随机生成字符串

func RandString

func RandString(n int) string

func Random

func Random(strings []string) ([]string, error)

func RandomCreateBytes added in v0.0.9

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

RandomCreateBytes generate random []byte by specify chars.

func ReplaceAll

func ReplaceAll(s string, oldnew ...string) string

func ReplaceNth

func ReplaceNth(s, old, new string, n int) string

func Reverse added in v0.0.9

func Reverse(s string) string

Reverse s string, support unicode

func ReverseString

func ReverseString(sourceString string) string

* 翻转字符串 *

func ReverseUint64Slice

func ReverseUint64Slice(int64Slice []uint64)

* 翻转uint64 Slice *

func SetDefault

func SetDefault(value, condition, def string) string

func Split

func Split(str, sep string) []string

golang 切割空字符串依然会得到包含一个空元素的数组 => [""]

func SqlFilter

func SqlFilter(source string) string

* sql过滤 *

func StatDir added in v0.0.9

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 String2Br

func String2Br(source string) string

* 换行转br标签 *

func StringDiff

func StringDiff(one, two []string) []string

* 字符集合的差集合 *

func StringInter

func StringInter(one, two []string) []string

* 字符集合的交集合 *

func StringReplace

func StringReplace(sourceString string, args ...string) string

* 字符串替换 * sourceString: 原始字符串 * args[0...n-2]: 被替换字符串集合 * args[n-1]: 替换字符串 *

func StringSliceLatest

func StringSliceLatest(srcSlice []string, maxCount int) []string

* 保留指定长度字符串切片,前面的数据移除 *

func StringSliceToDate

func StringSliceToDate(dateStringSlice []string) (time.Time, error)

* 日期字符串切片转成日期 *

func StringSliceToInt64Slice

func StringSliceToInt64Slice(values []string) []int64

* 字符串切片转为整型64切片 *

func StringSliceToString

func StringSliceToString(stringSlice []string, args ...string) string

* 用指定的字符串链接字符串切片 *

func StringSliceToUint64Slice

func StringSliceToUint64Slice(values []string) []uint64

* 字符串切片转为无符号整型64切片 *

func StringToBool

func StringToBool(stringValue string) bool

* 字符串转换为bool *

func StringToFloat64

func StringToFloat64(stringValue string) float64

* 字符串转换为float64 *

func StringToInt

func StringToInt(e string) (int, error)

func StringToInt32

func StringToInt32(stringValue string) int32

* 字符串转换为int32 *

func StringToInt64

func StringToInt64(stringValue string) int64

* 字符串转换为int64 *

func StringToInt64Slice

func StringToInt64Slice(sourceString string, args ...string) []int64

* 用指定的字符串把源字符串分隔为int64切片 *

func StringToIntSlice

func StringToIntSlice(sourceString string, args ...string) []int

* 用指定的字符串把源字符串分隔为int切片 *

func StringToStringSlice

func StringToStringSlice(sourceString string, args ...string) []string

* 用指定的字符串分隔源字符串为字符串切片 *

func StringToTime

func StringToTime(datetimeString string, args ...interface{}) (time.Time, error)

* 字符串转时间 * isUtc参数决定传入的日期字符串是否是utc日期 * isUtc:bool | format:string * 返回UTC日期 *

func StringToUint32

func StringToUint32(stringValue string) uint32

* 字符串转换为uint32 *

func StringToUint64

func StringToUint64(stringValue string) uint64

* 字符串转换为uint64 *

func StringToUint64Slice

func StringToUint64Slice(sourceString string, args ...string) []uint64

* 用指定的字符串把源字符串分隔为uint64切片 *

func StringUnion

func StringUnion(one, two []string) []string

* 字符集合的并集合 *

func StripTags added in v0.0.9

func StripTags(src string) string

strip tags in html string

func StructToJson

func StructToJson(value interface{}) (res string, err error)

func SubString

func SubString(src string, start, end int) string

截取文本 支持中文

func Substr

func Substr(s string, pos, length int) string

func TimeSincePro

func TimeSincePro(then time.Time, m map[string]string) string

TimeSincePro calculates the time interval and generate full user-friendly string.

func TimeStringAddMinutes

func TimeStringAddMinutes(timeString string, minutes int) string

* 时间字符串加指定的分钟数,返回时间字符串 *

func TimeToFriendString

func TimeToFriendString(datetime time.Time, args ...interface{}) string

* 日期时间转换成友好的显示字符串 * isUtc:bool | format:string *

func TimeToString

func TimeToString(datetime time.Time, args ...interface{}) string

* 时间转字符串 *

func TimeToUnix

func TimeToUnix(e time.Time) int64

时间转时间戳

func ToBase64

func ToBase64(data string, args ...bool) string

* Base64字符编码 *

func ToJson

func ToJson(object interface{}) (string, error)

* 对象转换成Json字符串 *

func ToLowerUnderlinedNamer

func ToLowerUnderlinedNamer(name string) string

ToLowerUnderlinedNamer 转换为小写下划线命名

func ToSnakeCase added in v0.0.9

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 added in v0.0.9

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

Convert any type to string.

func ToXml

func ToXml(object interface{}) (string, error)

* 对象转换成Xml字符串 *

func TrimSpaceLine

func TrimSpaceLine(source string) string

* 去除连续的换行符 *

func Uint64Diff

func Uint64Diff(one, two []uint64) []uint64

* uint64差集合 *

func Uint64Inter

func Uint64Inter(one, two []uint64) []uint64

* uint64交集合 *

func Uint64SliceToString

func Uint64SliceToString(uintSlice []uint64, args ...string) string

* 用指定的字符串把uint64切片链接为字符串 *

func Uint64SliceToStringSlice

func Uint64SliceToStringSlice(values []uint64) []string

* 无符号整型64切片转为字符串切片 *

func Uint64ToString

func Uint64ToString(value uint64) string

* 无符号整型64转为字符串 *

func Uint64Union

func Uint64Union(one, two []uint64) []uint64

* uint64并集合 *

func UnixDate

func UnixDate() time.Time

* Golang零时间日期(0001-01-01 00:00:00) * -62135596800 *

func UnixNanoTimestamp

func UnixNanoTimestamp() int64

* 获取当前Unix纳秒时间戳 * 当前日期距离197011000的纳秒数 *

func UnixNanoTimestampToDate

func UnixNanoTimestampToDate(unixNanoTimestamp int64) time.Time

* 根据Unix纳秒时间戳返回日期 *

func UnixTimestamp

func UnixTimestamp() int64

* 获取当前Unix时间戳 * 当前日期距离197011000的秒数 *

func UnixTimestampDate

func UnixTimestampDate() time.Time

* Unix时间戳日期(1970-01-01 00:00:00) *

func UnixTimestampToDate

func UnixTimestampToDate(unixTimestamp int64) time.Time

* 根据Unix时间戳返回日期 *

func UnixToTime

func UnixToTime(e string) (datatime time.Time, err error)

时间戳转时间

func UrlDecode added in v0.0.9

func UrlDecode(str string) (string, error)

url decode string

func UrlEncode added in v0.0.9

func UrlEncode(str string) string

url encode string, is + not %20

func WeekDay

func WeekDay(t time.Time) string

WeekDay 获取当前日的周名称

func WrapURL

func WrapURL(u string) string

func WriteFile added in v0.0.9

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 Mailer

type Mailer struct {
	// contains filtered or unexported fields
}

func (*Mailer) SendMail

func (m *Mailer) SendMail(to []string, subject, body string) bool

type NotFoundError added in v0.0.9

type NotFoundError struct {
	Message string
}

func (NotFoundError) Error added in v0.0.9

func (e NotFoundError) Error() string

type RawFile added in v0.0.9

type RawFile interface {
	Name() string
	RawUrl() string
	Data() []byte
	SetData([]byte)
}

A RawFile describes a file that can be downloaded.

type RemoteError added in v0.0.9

type RemoteError struct {
	Host string
	Err  error
}

func (*RemoteError) Error added in v0.0.9

func (e *RemoteError) Error() string

type StrTo added in v0.0.9

type StrTo string

Convert string to specify type.

func (StrTo) Exist added in v0.0.9

func (f StrTo) Exist() bool

func (StrTo) Float64 added in v0.0.9

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

func (StrTo) Int added in v0.0.9

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

func (StrTo) Int64 added in v0.0.9

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

func (StrTo) MustFloat64 added in v0.0.9

func (f StrTo) MustFloat64() float64

func (StrTo) MustInt added in v0.0.9

func (f StrTo) MustInt() int

func (StrTo) MustInt64 added in v0.0.9

func (f StrTo) MustInt64() int64

func (StrTo) MustUint8 added in v0.0.9

func (f StrTo) MustUint8() uint8

func (StrTo) String added in v0.0.9

func (f StrTo) String() string

func (StrTo) Uint8 added in v0.0.9

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

type StringSet added in v0.0.8

type StringSet struct {
	// contains filtered or unexported fields
}

StringSet is string sets val

func NewStringSet added in v0.0.8

func NewStringSet() *StringSet

NewStringSet is new set

func (*StringSet) Add added in v0.0.8

func (set *StringSet) Add(i string) bool

Add is

func (*StringSet) Contains added in v0.0.8

func (set *StringSet) Contains(i string) bool

Contains is

func (*StringSet) Index added in v0.0.8

func (set *StringSet) Index(c string) int

Index is

func (*StringSet) ItemByIndex added in v0.0.8

func (set *StringSet) ItemByIndex(idx int) string

ItemByIndex is

func (*StringSet) Len added in v0.0.8

func (set *StringSet) Len() int

Len is

func (*StringSet) Remove added in v0.0.8

func (set *StringSet) Remove(i string)

Remove is

func (*StringSet) Sort added in v0.0.8

func (set *StringSet) Sort()

Sort is

func (*StringSet) String added in v0.0.8

func (set *StringSet) String() string

String is

Jump to

Keyboard shortcuts

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