utils

package module
v0.0.0-...-105c82a Latest Latest
Warning

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

Go to latest
Published: May 13, 2020 License: BSD-2-Clause Imports: 45 Imported by: 0

README

utils

Install

cd $GOPATH
go get

Documentation

  • aes.go : aes
  • all.go : all applys a function
  • any.go : any applys a function
  • apply.go : apply applys a function
  • caller.go : GetFuncName get function name
  • compose.go :
  • compress.go : gzip / ungzip
  • debug.go :
  • err.go :
  • file.go :
  • filter.go : Filter apply a function
  • goerr.go : 错误生成
  • heap.go : heap队列
  • helper.go : helper
  • ini.go : 读取ini配置文件
  • mail.go : mail
  • option.go :
  • os.go : 执行系统命令
  • partial.go :
  • queue.go :
  • random.go : 常用的随机数工具方法
  • randutil.go : 产生随机字符串工具方法
  • reduce.go : Reduce applys a function
  • safemap.go :
  • slice.go :
  • sorting.go : 常用排序算法
  • string.go : 常用的字符串工具方法
  • structandmap.go :
  • timer_queue.go :
  • to.go : go数据类型到字符数组的转换
  • utils.go : 常用的工具方法,如:验证是否为邮箱等
  • xxtea.go : 字符串加密,解密
  • times.go : 常用的时间工具方法

example

参照php的date()函数和strtotime()函数

t := utils.StrToTime("2012-11-12 23:32:01")

字符串转换为time.Time类型

t := utils.StrToLocalTime("2012-11-12 23:32:01")
t := utils.StrToLocalTime("2012-11-12")

原生Go实现字符串转换为time.Time类型

t := time.Date(2012, 11, 12, 23, 32, 01, 0, time.Local)
t := time.Date(2012, 11, 12, 0, 0, 0, 0, time.Local)

time.Time类型格式化为字符串

now := time.Now()
strTime := utils.Format("Y-m-d H:i:s", now)

原生Go实现time.Time类型格式化为字符串

strTime := time.Now().Format("2006-01-02 15:04:05")


TODO

License

  • LICENSE

Reference

  • github.com/choleraehyq/gofunctools/functools
  • github.com/polaris1119/times
  • github.com/polaris1119/goutils
  • github.com/jmcvetta/randutil
  • github.com/astaxie/beego
  • test result

Documentation

Overview

Package functools is a simple Golang library including some commonly used functional programming tools. There is no generic in golang, so most of the functions will return interface{}, be sure to type assert it to the type you want before you use it.

*********************************************************

  • Author :
  • Email :
  • Last modified : 2016-01-23 10:24
  • Filename : goerr.go
  • Description : 错误生成
  • ******************************************************

This example demonstrates a priority queue built using the heap interface.

*********************************************************

  • Author :
  • Email :
  • Last modified : 2016-09-15 17:29:51
  • Filename : random.go
  • Description : 常用的随机数工具方法
  • ******************************************************

Package randutil provides various convenience functions for dealing with random numbers and strings.

*********************************************************

  • Author :
  • Email :
  • Last modified : 2016-09-15 16:22:18
  • Filename : string.go
  • Description : 常用的字符串工具方法
  • ******************************************************

*********************************************************

  • Author :
  • Email :
  • Last modified : 2016-09-15 16:22:18
  • Filename : times.go
  • Description : 常用的时间工具方法
  • ******************************************************

*********************************************************

  • Author :
  • Email :
  • Last modified : 2016-07-07 23:42
  • Filename : to.go
  • Description : go数据类型到字符数组的转换
  • ******************************************************

Index

Constants

View Source
const (
	// Set of characters to use for generating random strings
	Alphabet       = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	Numerals       = "1234567890"
	Alphanumeric   = Alphabet + Numerals
	Ascii          = Alphanumeric + "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:`"
	DefaultCharset = Alphanumeric + "!%@#"
)
View Source
const (
	KindTime reflect.Kind = iota + 1000000000
	KindDuration
)
View Source
const (
	XForwardedFor = "X-Forwarded-For"
	XRealIP       = "X-Real-IP"
)
View Source
const FORMAT string = "2006-01-02 15:04:05"
View Source
const FORMATDATA string = "2006-01-02 "
View Source
const FORMATSTR string = "2006/01/02/15"

Variables

View Source
var (
	FormatString = "%v\nthe trace error is\n%s"
)
View Source
var IllegalNameRune [13]rune
View Source
var MinMaxError = errors.New("Min cannot be greater than max.")
View Source
var RandInt32Chan chan int32

*

  • Chan中存放随机数
View Source
var RandUint32Chan chan uint32

Functions

func AalidataPwd

func AalidataPwd(name string) (b bool)

*

  • 验证只能由数字字母下划线组成的5-17位密码字符串
  • @param name string
  • @return bool

func AccountRegexp

func AccountRegexp(account string) bool

*

  • 验证账号是否合法
  • @param account string
  • @return bool

func AddDateTime

func AddDateTime(year, month, day int) (int, time.Month, int)

*

  • 获取相对年,月,日
  • @return int, time.Month, int)
  • Some examples: AddDateTime(0, -1, 0) 上月今天时间

func After

func After() bool

*

  • 是否当前时间之后
  • @return bool

func All

func All(function, slice interface{}) (ret bool, err error)

All applys a function(the first parameter) returning a boolean value to each element of a slice(second parameter), if all elements make that function return true then All will return true, otherwise false. Notice that All return a boolean value NOT an interface{}

func AlphaString

func AlphaString(n int) (string, error)

AlphaString returns a random alphanumeric string n characters long.

func AlphaStringRange

func AlphaStringRange(min, max int) (string, error)

AlphaRange returns a random alphanumeric string at least min and no more than max characters long.

func Any

func Any(function, slice interface{}) (ret bool, err error)

Any applys a function(the first parameter) returning a boolean value to each element of a slice(second parameter), if there exist at least one element make that function return true then Any will return true, otherwise false. Notice that Any return a boolean value NOT an interface{}

func Apply

func Apply(function, slice interface{}) (ret interface{}, err error)

Apply applys a function(the first parameter) to each element of a slice(second parameter). Just like Map in other language.

func Atoi

func Atoi(s string) (int, error)

func Base62decode

func Base62decode(base62 string) uint64

*

  • 翻转切片字符串
  • @param base62 string
  • @return uint64

func Base62encode

func Base62encode(num uint64) string

*

  • 翻转切片字符串
  • @param num uint64
  • @return string

func Base64Decode

func Base64Decode(data string) string

func Base64Encode

func Base64Encode(data string) string

func Before

func Before() bool

*

  • 是否当前时间之前
  • @return bool

func Bool

func Bool(value interface{}) bool

Tries to convert the argument into a bool. Returns false if any error occurs.

func BsonNow

func BsonNow() time.Time

Now returns the current time with millisecond precision. MongoDB stores timestamps with the same precision, so a Time returned from this method will not change after a roundtrip to the database. That's the only reason why this function exists. Using the time.Now function also works fine otherwise.

func BubbleSort

func BubbleSort(r []int)

冒泡排序 稳定

func Bytes

func Bytes(val interface{}) []byte

Tries to convert the argument into a []byte array. Returns []byte{} if any error occurs.

func Bytes2String

func Bytes2String(b []byte) (s string)

*

  • Bytes2String force casts a []byte to a string.
  • @param b []byte
  • @return (s string)

func BytesToInt

func BytesToInt(b []byte) int

*

  • 字节转换成整形
  • @param b []byte
  • @return int

func BytesToInt64

func BytesToInt64(b []byte) int64

*

  • 字节转换成int64整形
  • @param b []byte
  • @return int64

func CamelName

func CamelName(name string) string

下划线写法转为驼峰写法

func ChoiceInt

func ChoiceInt(choices []int) (int, error)

ChoiceInt returns a random selection from an array of integers.

func ChoiceString

func ChoiceString(choices []string) (string, error)

ChoiceString returns a random selection from an array of strings.

func Clone

func Clone(dst, src interface{}) error

*

  • 对象深度拷贝
  • @param dst interface{}
  • @param src interface{}
  • @return error

func Compose

func Compose(functions ...interface{}) (ret func(...interface{}) interface{}, err error)

Compose will compose the received functions, there is no limit on the number of functions. Notice that the return value of the composed function is interface{}.

func Convert

func Convert(value interface{}, t reflect.Kind) (interface{}, error)

Tries to convert the argument into a reflect.Kind element.

func ConvertString

func ConvertString(inter interface{}, precs ...int) string

func Date

func Date(year, month, day, hour, min, sec, nsec int) time.Time

*

  • Date returns the current time
  • @return time.Time struct{}

func DateLocal

func DateLocal(year int, month time.Month, day, hour, min, sec, nsec int) time.Time

*

  • DateLocal returns the current local time
  • @return time.Time struct{}

func DateStr

func DateStr() string

*

  • str格式当前日期
  • @return string

func DateTime

func DateTime() (int, time.Month, int)

*

  • 获取当前年,月,日
  • @return (int, time.Month, int)

func Day

func Day() int

*

  • 获取当前天
  • @return int

func DayDate

func DayDate() int

*

  • 获取本地当天时间20170402
  • @return int

func Decode

func Decode(data []byte, to interface{}) error

*

  • 用gob进行数据解码
  • @param data []byte
  • @param to interface{}
  • @return error

func Decrypt

func Decrypt(data []byte, key []byte) []byte

Decrypt the data with key. data is the bytes to be decrypted. key is the decrypted key. It is the same as the encrypt key.

func Diff

func Diff() time.Duration

*

  • 两个时间点的时间间隔
  • @return time.Duration

func Display

func Display(data ...interface{})

Display print the data in console

func Dump

func Dump(v interface{})

Print to standard out the value that is passed as the argument with indentation. Pointers are dereferenced.

func Duration

func Duration(val interface{}) time.Duration

Tries to convert the argument into a time.Duration value. Returns time.Duration(0) if any error occurs.

func EmailRegexp

func EmailRegexp(mail string) bool

*

  • 验证是否邮箱
  • @param mail string
  • @return bool

func Encode

func Encode(data interface{}) ([]byte, error)

*

  • 用gob进行数据编码
  • @param data interface{}
  • @return ([]byte, error)

func Encrypt

func Encrypt(data []byte, key []byte) []byte

Encrypt the data with key. data is the bytes to be encrypted. key is the encrypt key. It is the same as the decrypt key.

func Equal

func Equal() bool

*

  • 是否等于当前时间
  • @return bool

func FileExists

func FileExists(name string) bool

FileExists reports whether the named file or directory exists.

func Filter

func Filter(function, slice interface{}) (ret interface{}, err error)

Filter apply a function(the first parameter) to each element of a slice(second parameter), and filter out ones which make the function return true.

func Float64

func Float64(val interface{}) float64

Tries to convert the argument into a float64. Returns float64(0.0) if any error occurs.

func Format

func Format(format string, ts ...time.Time) string

Format 跟 PHP 中 date 类似的使用方式,如果 ts 没传递,则使用当前时间

func GCSummary

func GCSummary() string

func GenSign

func GenSign(args url.Values, secretKey string) string

GenSign 根据输入参数进行签名

func GetAuth

func GetAuth() []rune

*

  • Get Auth
  • @return []rune

func GetDisplayString

func GetDisplayString(data ...interface{}) string

GetDisplayString return data print string

func GetExternalIP

func GetExternalIP() (exip string, err error)

func GetFuncName

func GetFuncName(i interface{}) string

GetFuncName get function name

func GetGuid

func GetGuid() string

*

  • 生成Guid字符串
  • @return string

func GetInternalIP

func GetInternalIP() (inip string, err error)

func GetInternalIP2

func GetInternalIP2() (inip string, err error)

func GetMd5String

func GetMd5String(s string) string

*

  • 生成32位md5字符串
  • @param s string
  • @return string

func GetPhoto

func GetPhoto(str string) string

func GetRandInt32

func GetRandInt32() int32

*

  • 从RandInt32Chan中获取int32类型随机数
  • @return int32

func GetRandUint32

func GetRandUint32() uint32

*

  • 从RandUint32Chan中获取uint32类型随机数
  • @return uint32

func GetSalt

func GetSalt() string

*

  • Generated Salt
  • @return string

func GrepFile

func GrepFile(patten string, filename string) (lines []string, err error)

GrepFile like command grep -E for example: GrepFile(`^hello`, "hello.txt") \n is striped while read

func Gunzip

func Gunzip(r io.Reader) ([]byte, error)

func Gzip

func Gzip(b []byte, w io.Writer) (int, error)

func Hour

func Hour() int

*

  • 获取当前时间小时
  • @return int

func InSlice

func InSlice(v string, sl []string) bool

InSlice checks given string in string slice or not.

func InSliceIface

func InSliceIface(v interface{}, sl []interface{}) bool

InSliceIface checks given interface in interface slice.

func InetToaton

func InetToaton(ipnr string) uint32

*

  • 点分结构的IP地址转成数值类型
  • @param ipnr string
  • @return uint32
  • @eg t.Log((InetToaton("192.168.1.190")))

func InetTobton

func InetTobton(ipnr net.IP) uint32

*

  • 字节类型的IP地址转成数值类型
  • @param ipnr string
  • @return uint32
  • @eg: t.Log((InetTobton(net.IPv4(192,168,1,190))))

func InetTontoa

func InetTontoa(ipnr uint32) net.IP

*

  • 数值类型转成点分结构的IP地址
  • @param ipnr string
  • @return uint32
  • @eg: t.Log((InetTontoa(3232235966).String()))

func Init

func Init()

func InitIllegalNameRune

func InitIllegalNameRune()

func InsertSort

func InsertSort(r []int)

没有监视哨

func InsertionSort

func InsertionSort(r []int)

直接插入排序 稳定 额外空间 1 1.设置监视哨 r[i] = tmp 2.从r[1]开始比较 3.r[i] 和 r[i-1] 比较; r[i-1] >= tmp r[i]=tmp 即r[i-1]后移; r[i-1] < tmp r[i] = tmp

func Int2Str

func Int2Str(i int) string

*

  • 整形转换成字符串
  • @param i int
  • @return s string

func Int64

func Int64(val interface{}) int64

Tries to convert the argument into an int64. Returns int64(0) if any error occurs.

func Int64ToBytes

func Int64ToBytes(n int64) []byte

*

  • int64整形转换成字节
  • @param n int64
  • @return []byte

func IntRange

func IntRange(min, max int) (int, error)

IntRange returns a random integer in the range from min to max.

func IntToBytes

func IntToBytes(n int) []byte

*

  • 整形转换成字节
  • @param n int
  • @return []byte

func Ip2Long

func Ip2Long(ip_address string) float64

*

  • 将一个IPV4的字符串互联网协议转换成数字格式
  • @param ip_address string
  • @return float64

func Ip2long

func Ip2long(ipstr string) uint32

Ip2long 将 IPv4 字符串形式转为 uint32

func Itoa

func Itoa(i int) string

func Kickers

func Kickers(per, second int, f func())

*

  • 指定second时间内每隔per执行一次
  • @param per int
  • @param second int
  • @param f func()

func LastWeek

func LastWeek() (start, end time.Time)

*

  • 获取上周
  • @return start, end time.Time

func LegalName

func LegalName(name string, maxcount int) bool

*

  • 验证名字
  • @param name string
  • @param maxcount int
  • @return bool

func LocalTime

func LocalTime() time.Time

*

  • Now returns the current local time
  • @return time.Time struct{}

func Long2Ip

func Long2Ip(long float64) string

*

  • 将一个数字格式转换成IPV4的字符串
  • @param long float64
  • @return ip string

func Md5

func Md5(text string) string

*

  • Md5加密
  • @param text string
  • @return string

func Md5Buf

func Md5Buf(buf []byte) string

func Md5Copy

func Md5Copy(text string) string

*

  • Md5加密
  • @param text string
  • @return string

func Md5File

func Md5File(reader io.Reader) string

func MergeSort

func MergeSort(r []int) []int

归并排序 稳定

func Minute

func Minute() int

*

  • 获取当前时间分钟
  • @return int

func Month

func Month() time.Month

*

  • 获取当前月
  • @return time.Month

func MonthDate

func MonthDate() int

*

  • 获取本地当月时间201704
  • @return int

func MonthDays

func MonthDays(year int, month int) (days int)

*

  • 获取指定年月的天数
  • @param year int
  • @param month int
  • @return days int

func MustBool

func MustBool(s string, defaultVal ...bool) bool

func MustFloat

func MustFloat(inter interface{}, defaultVals ...float64) float64

func MustInt

func MustInt(s string, defaultVal ...int) int

MustInt 字符串转int

func MustInt64

func MustInt64(s string, defaultVal ...int64) int64

MustInt64 字符串转int64

func Nanosecond

func Nanosecond() int

*

  • 获取当前时间纳秒
  • @return int

func New

func New(format string, p ...interface{}) error

返回一个错误

func NewError

func NewError(err error, format string, p ...interface{}) error

按格式返回一个错误 同时携带原始的错误信息

func NewTicker

func NewTicker(second int) *time.Ticker

*

  • 时钟
  • @param second int
  • @return *time.Ticker

func NewTickerMilli

func NewTickerMilli(millisecond int) *time.Ticker

*

  • 时钟
  • @param millisecond int
  • @return *time.Ticker

func Partial

func Partial(function interface{}, params ...interface{}) (ret func(...interface{}) interface{}, err error)

Partial will make a partial function. The first argument is the function being partialed, the rest arguments is the parameters sending to that function.

func PhoneRegexp

func PhoneRegexp(phone string) bool

*

  • 验证是否手机
  • @param phone string
  • @return bool

func PhoneValidate

func PhoneValidate(phone string) bool

*

  • 验证是否手机
  • @param phone string
  • @return bool

func PrintPointerInfo

func PrintPointerInfo(buf *bytes.Buffer, headlen int, pointers *pointerInfo)

PrintPointerInfo dump pointer value

func Qsort

func Qsort(arr []byte)

对牌值从小到大排序,采用快速排序算法

func QuSort

func QuSort(arr []byte, start, end int)

对牌值从小到大排序,采用快速排序算法

func QuickSort

func QuickSort(r []int)

快速排序 不稳定 选定r[0]

func RadixSort

func RadixSort(sz []int)

基数排序 稳定 MSD法:从优先级最高的关键字开始 LSD法:从优先级最低的关键字开始,速度快,但对数据有类型要求 时间复杂度:O(d n) n为关键字数量

func RandFloat32

func RandFloat32() (r float32)

*

  • 获取float32类型随机数
  • @return r float32

func RandFloat64

func RandFloat64() (r float64)

*

  • 获取float64类型随机数
  • @return r float64

func RandInt

func RandInt() (r int)

*

  • 获取int类型随机数
  • @return r int

func RandInt32

func RandInt32() (r int32)

*

  • 获取int32类型随机数
  • @return r int32

func RandInt32N

func RandInt32N(n int32) (r int32)

*

  • 获取int32类型随机数
  • @param n int32
  • @return r int32

func RandInt64

func RandInt64() (r int64)

*

  • 获取int64类型随机数
  • @return r int64

func RandInt64N

func RandInt64N(n int64) (r int64)

*

  • 获取int64类型随机数
  • @param n int64
  • @return r int64

func RandIntN

func RandIntN(n int) (r int)

*

  • 获取[0,n)int类型随机数
  • @param n int
  • @return r int

func RandStr

func RandStr(i int) (s string)

*

  • 随机长度数值字符串
  • @param i int
  • @return s string

func RandString

func RandString(n int, defaultCharsets ...string) string

RandString 产生随机字符串,可用于密码等

func RandUint32

func RandUint32() (r uint32)

*

  • 获取uint32类型随机数
  • @return r uint32

func RandomCreateBytes

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

*

  • RandomCreateBytes generate random []byte by specify chars.
  • @param n int
  • @param alphabets []byte
  • @return []byte

func RandomCreateBytes2

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

RandomCreateBytes generate random []byte by specify chars.

func Reduce

func Reduce(function, slice, initial interface{}) (ret interface{}, err error)

Reduce applys a function(the first parameter) of two arguments cumulatively to each element of a slice(second parameter), and the initial value is the third parameter.

func RemoteIp

func RemoteIp(req *http.Request) string

RemoteIp 返回远程客户端的 IP,如 192.168.1.1

func Reverse

func Reverse(s string) string

*

  • 反转字符串
  • @param s string
  • @return string

func ReverseRune

func ReverseRune(runes []rune) []rune

*

  • 反转rune
  • @param s string
  • @return string

func Run

func Run(cmd string, args ...string) []byte

func RunError

func RunError(cmd string, args ...string) ([]byte, error)

func RunPrint

func RunPrint(cmd string, args ...string)

func Sdump

func Sdump(v interface{}) string

Return the value that is passed as the argument with indentation. Pointers are dereferenced.

func SearchFile

func SearchFile(filename string, paths ...string) (fullpath string, err error)

SearchFile Search a file in paths. this is often used in search config file in /etc ~/

func SearchString

func SearchString(slice []string, s string) int

搜索字符串出现的位置

func Second

func Second() int

*

  • 获取当前时间秒
  • @return int

func Seed

func Seed()

*

  • Rand Send
  • @return

func SelectionSort

func SelectionSort(r []int)

选择排序 不稳定

func SelfDir

func SelfDir() string

SelfDir gets compiled executable file directory

func SelfPath

func SelfPath() string

SelfPath gets compiled executable file absolute path

func ShellSort

func ShellSort(r []int)

希尔排序 不稳定

func Sleep

func Sleep(second int)

*

  • 延迟second
  • @param second int

func Sleep64

func Sleep64(second int64)

*

  • 延迟second
  • @param second int64

func SleepRand

func SleepRand(second int)

*

  • 延迟1~second
  • @param second int

func SleepRand64

func SleepRand64(second int64)

*

  • 延迟1~second
  • @param second int64

func SliceChunk

func SliceChunk(slice []interface{}, size int) (chunkslice [][]interface{})

SliceChunk separates one slice to some sized slice.

func SliceDiff

func SliceDiff(slice1, slice2 []interface{}) (diffslice []interface{})

SliceDiff returns diff slice of slice1 - slice2.

func SliceFilter

func SliceFilter(slice []interface{}, a filtertype) (ftslice []interface{})

SliceFilter generates a new slice after filter function.

func SliceIndexOf

func SliceIndexOf(arr []string, str string) int

*

  • 切片中字符串第一个位置
  • @param arr []string
  • @param str string
  • @return int

func SliceIntersect

func SliceIntersect(slice1, slice2 []interface{}) (diffslice []interface{})

SliceIntersect returns slice that are present in all the slice1 and slice2.

func SliceLastIndexOf

func SliceLastIndexOf(arr []string, str string) int

*

  • 切片中字符串最后一个位置
  • @param arr []string
  • @param str string
  • @return int

func SliceMerge

func SliceMerge(slice1, slice2 []interface{}) (c []interface{})

SliceMerge merges interface slices to one slice.

func SlicePad

func SlicePad(slice []interface{}, size int, val interface{}) []interface{}

SlicePad prepends size number of val into slice.

func SliceRand

func SliceRand(a []interface{}) (b interface{})

SliceRand returns random one from slice.

func SliceRandList

func SliceRandList(min, max int) []int

SliceRandList generate an int slice from min to max.

func SliceRange

func SliceRange(start, end, step int64) (intslice []int64)

SliceRange generates a new slice from begin to end with step duration of int64 number.

func SliceReduce

func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{})

SliceReduce generates a new slice after parsing every value by reduce function

func SliceRemoveFormSlice

func SliceRemoveFormSlice(oriArr []string, removeArr []string) []string

*

  • 从字符串切片中移除指定切片字符串
  • @param oriArr []string
  • @param removeArr []string
  • @return []string

func SliceShuffle

func SliceShuffle(slice []interface{}) []interface{}

SliceShuffle shuffles a slice.

func SliceSum

func SliceSum(intslice []int64) (sum int64)

SliceSum sums all values in int64 slice.

func SliceUnique

func SliceUnique(slice []interface{}) (uniqueslice []interface{})

SliceUnique cleans repeated values in slice.

func Split

func Split(s, sep string) []string

*

  • 分离字符串为一个slices
  • @param s string
  • @param sep string
  • @return []string

func Stack

func Stack(skip int, indent string) []byte

Stack get stack bytes

func Stamp2Time

func Stamp2Time(t int64) time.Time

*

  • 时间截转换为Time时间
  • @return time.Time

func Str2Int

func Str2Int(s string) (int, error)

*

  • 字符串转换成整形
  • @param s string
  • @return (int, error)

func Str2Local

func Str2Local(t string) (int64, error)

*

  • str格式化时间转本地时间戳
  • @param t string
  • @return (int64, error)

func Str2Time

func Str2Time(t string) time.Time

*

  • str格式化时间转时间戳
  • @param t string
  • @return time.Time

func Str2Unix

func Str2Unix(t string) (int64, error)

*

  • str格式化时间转时间戳
  • @param t string
  • @return (int64, error)

func StrToLocalTime

func StrToLocalTime(value string) time.Time

StrToLocalTime 字符串转换成本地Time时间表示

func StrToTime

func StrToTime(value string) time.Time

StrToTime 字符串转换成Time时间表示

func String

func String(val interface{}) string

Tries to convert the argument into a string. Returns "" if any error occurs.

func String2Bytes

func String2Bytes(s string) (b []byte)

*

  • String2Bytes force casts a string to a []byte
  • @param s string
  • @return (b []byte)

func StringAdd

func StringAdd(numStr string) string

*

  • 字符串加法
  • @param numStr string
  • @return string

func StringAdd2

func StringAdd2(numStr1, numStr2 string) string

*

  • 字符串加法
  • @param numStr1 string
  • @param numStr2 string
  • @return string

func StringRand

func StringRand(n int, charset string) (string, error)

StringRand returns a random string n characters long, composed of entities from charset.

func StringRange

func StringRange(min, max int, charset string) (string, error)

StringRange returns a random string at least min and no more than max characters long, composed of entitites from charset.

func Struct2Map

func Struct2Map(obj interface{}) map[string]interface{}

func SubStr

func SubStr(str string, begin, length int) (substr string)

*

  • 截取字符串
  • @param string str
  • @param begin int
  • @param length int
  • @return int 长度

func ThisWeek

func ThisWeek() (start, end time.Time)

*

  • 获取本周
  • @return start, end time.Time

func Time

func Time(val interface{}) time.Time

Converts a date string into a time.Time value, several date formats are tried.

func Time2DayDate

func Time2DayDate(now time.Time) int

*

  • 获取本地当天时间20170402
  • @return int

func Time2LocalStr

func Time2LocalStr(t time.Time) string

*

  • 返回字符串格式化本地时间
  • @return string

func Time2MonthDate

func Time2MonthDate(now time.Time) int

*

  • 获取本地当月时间201704
  • @return int

func Time2Stamp

func Time2Stamp(t time.Time) int64

*

  • 返回时间截数值
  • @return int64

func Time2Str

func Time2Str(t time.Time) string

*

  • 返回字符串格式化时间
  • @return string

func TimeToHeadphpoto

func TimeToHeadphpoto(t int64, userid int, headname int64) (string, string)

*

  • 把时间戳转换成头像存储目录
  • @param t int64
  • @param userid int
  • @param headname int64
  • @return (string, string)

func TimeToPhpotoPath

func TimeToPhpotoPath(t int64, userid int) string

*

  • 把时间戳转换成头像存储目录
  • @param t int64
  • @param userid int
  • @return string

func TimerRun

func TimerRun(second int, f func()) *time.Timer

*

  • 定时器
  • @param second int
  • @param f func()
  • @return *time.Timer

func TimerStop

func TimerStop(timer *time.Timer) bool

*

  • 取消定时器
  • @param *time.Timer
  • @return bool

func Timestamp

func Timestamp() int64

*

  • 获取当前时间截
  • @return int64

func TimestampNano

func TimestampNano() int64

*

  • 获取当前纳秒时间截
  • @return int64

func TimestampToday

func TimestampToday() int64

*

  • 获取本地当天零点时间截
  • @return int64

func TimestampTodayTime

func TimestampTodayTime() time.Time

*

  • 获取本地当天零点时间截
  • @return time.Time

func TimestampTomorrow

func TimestampTomorrow() int64

*

  • 获取本地明天零点时间截
  • @return int64

func TimestampYesterday

func TimestampYesterday() int64

*

  • 获取本地昨天零点时间截
  • @return int64

func Uint64

func Uint64(val interface{}) uint64

Tries to convert the argument into an uint64. Returns uint64(0) if any error occurs.

func UnderscoreName

func UnderscoreName(name string) string

驼峰式写法转为下划线写法

func Unix2Day

func Unix2Day(t int64) int

*

  • 获取指定时间截的天
  • @param t int64
  • @return int

func Unix2Fstr

func Unix2Fstr(t int64) string

*

  • 时间戳转str格式化时间
  • @param t int64
  • @return string

func Unix2Month

func Unix2Month(t int64) time.Month

*

  • 获取指定时间截的月
  • @param t int64
  • @return time.Month

func Unix2Str

func Unix2Str(t int64) string

*

  • 时间戳转str格式化时间
  • @param t int64
  • @return string

func Unix2Year

func Unix2Year(t int64) int

*

  • 获取指定时间截的年
  • @param t int64
  • @return int

func UseridCovToInvate

func UseridCovToInvate(userid string) uint32

*

  • 利用用户id生成数值类型唯一激活码
  • @param userid string
  • @return uint32

TODO:bug

func Weekday

func Weekday() time.Weekday

*

  • 获取当前周
  • @return time.Weekday

func Year

func Year() int

*

  • 获取当前年
  • @return int

Types

type AesEncrypt

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

func (*AesEncrypt) Decrypt

func (this *AesEncrypt) Decrypt(src []byte) (strDesc []byte, err error)

解密字符串

func (*AesEncrypt) Encrypt

func (this *AesEncrypt) Encrypt(strMesg []byte) ([]byte, error)

加密字符串

func (*AesEncrypt) SetKey

func (this *AesEncrypt) SetKey(key []byte)

type Array

type Array interface {
	//Push 向链表尾部添加一个或者多个元素
	Push(values ...interface{})

	// Pop 从列表尾部移除并返回一个元素
	Pop() interface{}

	//PushFront 向链表头部添加一个元素
	PushFront(values ...interface{})

	// PopFront从链表头部移除并返回一个元素
	PopFront() interface{}

	// Len 返回集链表元素的长度
	Len() int

	// Values 返回链表所有元素组成的 Slice
	Values() []interface{}

	// Iter 遍历链表的所有元素
	Iter() <-chan interface{}

	// Clear  清空链表
	Clear()
}

func NewArray

func NewArray(block bool, values ...interface{}) Array

NewArray 创建一个链表,block == true :线程安全,block == false:非线程安全

type Attachment

type Attachment struct {
	Filename string
	Header   textproto.MIMEHeader
	Content  []byte
}

Attachment is a struct representing an email attachment. Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question

type BeeMap

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

BeeMap is a map with lock

func NewBeeMap

func NewBeeMap() *BeeMap

NewBeeMap return new safemap

func (*BeeMap) Check

func (m *BeeMap) Check(k interface{}) bool

Check Returns true if k is exist in the map.

func (*BeeMap) Delete

func (m *BeeMap) Delete(k interface{})

Delete the given key and value.

func (*BeeMap) Get

func (m *BeeMap) Get(k interface{}) interface{}

Get from maps return the k's value

func (*BeeMap) Items

func (m *BeeMap) Items() map[interface{}]interface{}

Items returns all items in safemap.

func (*BeeMap) Set

func (m *BeeMap) Set(k interface{}, v interface{}) bool

Set Maps the given key and value. Returns false if the key is already in the map and changes nothing.

type Buffer

type Buffer struct {
	*bytes.Buffer
}

内嵌bytes.Buffer,支持连写

func NewBuffer

func NewBuffer() *Buffer

func (*Buffer) Append

func (b *Buffer) Append(i interface{}) *Buffer

type Choice

type Choice struct {
	Weight int
	Item   interface{}
}

A Choice contains a generic item and a weight controlling the frequency with which it will be selected.

func WeightedChoice

func WeightedChoice(choices []Choice) (Choice, error)

WeightedChoice used weighted random selection to return one of the supplied choices. Weights of 0 are never selected. All other weight values are relative. E.g. if you have two choices both weighted 3, they will be returned equally often; and each will be returned 3 times as often as a choice weighted 1.

type Config

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

func SetConfig

func SetConfig(filepath string) *Config

Create an empty configuration file

func (*Config) DeleteValue

func (c *Config) DeleteValue(section, name string) bool

Delete the corresponding key values

func (*Config) GetValue

func (c *Config) GetValue(section, name string) string

To obtain corresponding value of the key values

func (*Config) ReadList

func (c *Config) ReadList() []map[string]map[string]string

List all the configuration file

func (*Config) SetValue

func (c *Config) SetValue(section, key, value string) bool

Set the corresponding value of the key value, if not add, if there is a key change

type Email

type Email struct {
	Auth        smtp.Auth
	Identity    string `json:"identity"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	Host        string `json:"host"`
	Port        int    `json:"port"`
	From        string `json:"from"`
	To          []string
	Bcc         []string
	Cc          []string
	Subject     string
	Text        string // Plaintext message (optional)
	HTML        string // Html message (optional)
	Headers     textproto.MIMEHeader
	Attachments []*Attachment
	ReadReceipt []string
}

Email is the type used for email messages

func NewEMail

func NewEMail(config string) *Email

NewEMail create new Email struct with config json. config json is followed from Email struct fields.

func (*Email) Attach

func (e *Email) Attach(r io.Reader, filename string, args ...string) (a *Attachment, err error)

Attach is used to attach content from an io.Reader to the email. Parameters include an io.Reader, the desired filename for the attachment, and the Content-Type.

func (*Email) AttachFile

func (e *Email) AttachFile(args ...string) (a *Attachment, err error)

AttachFile Add attach file to the send mail

func (*Email) Bytes

func (e *Email) Bytes() ([]byte, error)

Bytes Make all send information to byte

func (*Email) Send

func (e *Email) Send() error

Send will send out the mail

type IPTaoBao

type IPTaoBao struct {
	Code int          `json:"code"`
	Data IPTaoBaoData `json:"data"`
}

通过淘宝API获取ip物理地址

func GetIPAddrByTaoBao

func GetIPAddrByTaoBao(ip string) (res *IPTaoBao, err error)

type IPTaoBaoData

type IPTaoBaoData struct {
	Country    string `json:country`
	Country_id string `json:country_id`
	Area       string `json:area`
	Area_id    string `json:area_id`
	Region     string `json:region`
	Region_id  string `json:region_id`
	City       string `json:city`
	City_id    string `json:city_id`
	County     string `json:county`
	County_id  string `json:county_id`
	Isp        string `json:isp`
	Isp_id     string `json:isp_id`
	Ip         string `json:ip`
}

type Item

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

An Item is something we manage in a priority queue.

type Option

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

Type Option represents an optional value: every Option is either Some and contains a value, or None, and contains a nil. They have a number of uses. For example, if a function call maybe failed, it can return an Option that None is returned on error.

var None Option = Option{nil}

None is a special Option containing a nil.

func Some

func Some(i interface{}) Option

Some will return a Option containing the given value. Some cannot use to generate a None. If the given value is nil, it will panic.

func (*Option) And

func (this *Option) And(other Option) Option

And returns None if this option is None, otherwise returns the option received.

func (*Option) And_then

func (this *Option) And_then(function interface{}) Option

And_then returns None if this option is None, otherwise calls the received function with the wrapped value and returns the result Option.

func (*Option) Bind

func (this *Option) Bind(function interface{}) Option

Bind will apply a given function to the wrapped value of this Option and return a new Option. If this Option is None, then it will return None.

func (*Option) Is_none

func (this *Option) Is_none() bool

Is_none judge whether this Option is None.

func (*Option) Is_some

func (this *Option) Is_some() bool

Is_some judge whether this Option is Some.

func (*Option) Unwrap

func (this *Option) Unwrap() interface{}

Unwrap return the wrapped value of a Option. If the Option is None, it will panic.

type PriorityQueue

type PriorityQueue []*Item

A PriorityQueue implements heap.Interface and holds Items.

func (PriorityQueue) Len

func (pq PriorityQueue) Len() int

func (PriorityQueue) Less

func (pq PriorityQueue) Less(i, j int) bool

func (*PriorityQueue) Pop

func (pq *PriorityQueue) Pop() interface{}

func (*PriorityQueue) Push

func (pq *PriorityQueue) Push(x interface{})

func (PriorityQueue) Swap

func (pq PriorityQueue) Swap(i, j int)

func (*PriorityQueue) Update

func (pq *PriorityQueue) Update(item *Item, value string, priority int)

update modifies the priority and value of an Item in the queue.

type Queue

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

func (*Queue) Len

func (q *Queue) Len() int

func (*Queue) Pop

func (q *Queue) Pop() (elem interface{})

func (*Queue) Push

func (q *Queue) Push(elem interface{})

type RPCConfig

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

func (*RPCConfig) FillStruct

func (s *RPCConfig) FillStruct(m map[string]string) error

type TimeOuter

type TimeOuter interface {
	TimeOut(int64)
}

type Timer

type Timer struct {
	TimeOuter
	// contains filtered or unexported fields
}

type TimerManager

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

func NewTimerManager

func NewTimerManager(size int) *TimerManager

func (*TimerManager) AddTimer

func (this *TimerManager) AddTimer(i TimeOuter, e int64, iv int64) uint32

func (*TimerManager) RemoveTimer

func (this *TimerManager) RemoveTimer(id uint32)

func (*TimerManager) Run

func (this *TimerManager) Run(now int64, limit int)

type TimerQueue

type TimerQueue []*Timer

func (TimerQueue) Len

func (this TimerQueue) Len() int

func (TimerQueue) Less

func (this TimerQueue) Less(i, j int) bool

func (*TimerQueue) Pop

func (this *TimerQueue) Pop() interface{}

func (*TimerQueue) Push

func (this *TimerQueue) Push(x interface{})

func (TimerQueue) Swap

func (this TimerQueue) Swap(i, j int)

Jump to

Keyboard shortcuts

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