Documentation ¶
Overview ¶
aes
convert
数据类型之间的转换
var s := "168000" i, _ := toolbox.Int(s) i32, _ := toolbox.Int32(s) i64, _ := toolbox.Int64(s) f32, _ := toolbox.Float32(s) f64, _ := toolbox.Float64(s)
exec
html
idgenerator
json
map
md5
slice
string
ticker
time
tools
try
Usage ¶
Just call try.Do with the function you want to retry in the event of an error:
Call try.Do that returns a bool indicating whether to retry or not, and an error The attempt argument will start at 1 and count up try.Do blocks until you return false, or a nil error try.Do returns the last error or nil if it was successful var value string
err := try.Do(func(attempt int) (bool, error) { var err error value, err = SomeFunction() return attempt < 5, err // try 5 times })
if err != nil { log.Fatalln("error:", err) }
In the above example the function will be called repeatedly until error is nil, while attempt < 5 (i.e. try 5 times)
Retrying panics ¶
Try supports retrying in the event of a panic.
Use named return parameters Set retry first Defer the recovery code, and set err manually in the case of a panic Use empty return statement at the end var value string
err := try.Do(func(attempt int) (retry bool, err error) { retry = attempt < 5 // try 5 times defer func() { if r := recover(); r != nil { err = errors.New(fmt.Sprintf("panic: %v", r)) } }() value, err = SomeFunction() return })
if err != nil { log.Fatalln("error:", err) }
Delay between retries
To introduce a delay between retries, just make a time.Sleep call before you return from the function if you are returning an error.
var value string
err := try.Do(func(attempt int) (bool, error) { var err error value, err = SomeFunction() if err != nil { time.Sleep(1 * time.Minute) // wait a minute } return attempt < 5, err })
if err != nil { log.Fatalln("error:", err) }
Maximum retry limit
To avoid infinite loops, Try will ensure it only makes try.MaxRetries attempts. By default, this value is 10, but you can change it:
try.MaxRetries = 20 To see if a Do operation failed due to reaching the limit, you can check the error with try.IsMaxRetries(err).
Index ¶
- Variables
- func AESDecryptData(cipherText []byte, aesKey []byte, iv []byte) (rawData []byte, err error)
- func AESDecryptMsg(ciphertext []byte, aesKey []byte) (random, rawXMLMsg, appId []byte, err error)
- func AESEncryptMsg(random, rawXMLMsg []byte, appId string, aesKey []byte) (ciphertext []byte)
- func Addslashes(str string) string
- func AddslashesPlus(str string) string
- func Boolean(value interface{}) bool
- func BytesToString(b []byte) string
- func CheckError(err error, exit bool)
- func CheckInIntSlice(key int, intSlice []int) bool
- func CheckInStrSlice(key string, strSlice []string) bool
- func Command(command string, args ...string) (output string, err error)
- func ConvertToMap(model interface{}) map[string]interface{}
- func DateTimeToDate(dateTime string) string
- func DecodeJson(jsonStr string) interface{}
- func DeleteSliceItem(slice []interface{}, index int) []interface{}
- func Deserialize(str string, m interface{}) error
- func DeserializeBytes(b []byte, m interface{}) error
- func Do(fn Func) error
- func FindLower(a, b int) int
- func Float32(value interface{}) float32
- func Float64(value interface{}) float64
- func FormatMapToXML(xmlWriter io.Writer, m map[string]string) (err error)
- func GenId() uint64
- func GenIdInt64() int64
- func GetDate() string
- func GetIP() (string, error)
- func GetSequence(id uint64) uint64
- func GetShardId(id uint64) int
- func GetSliceMapValueByKey(params []map[string]interface{}, key string) string
- func GetSliceValueString(slice []string, index int, defaultValue string) string
- func GetStrBetweenStr(str, strA, strB string) []string
- func GetTime(id uint64) time.Time
- func GetTimeUnixMill(id int64) int64
- func GetTimeUnixNano(id uint64) int64
- func GetVersion(id uint64) int
- func HtmlEscape(s string) string
- func Int(value interface{}) int
- func Int32(value interface{}) int32
- func Int64(value interface{}) int64
- func IsEmpty(value interface{}) bool
- func IsMaxRetries(err error) bool
- func IsNumeric(val interface{}) bool
- func MapToTree(list interface{}, parentID string, childFieldName string) []map[string]interface{}
- func Md5hash(str string) string
- func MsgSign(token, timestamp, nonce, encryptedMsg string) (signature string)
- func MustCommand(command string, args ...string) (output string)
- func Now() int64
- func ParseXMLToMap(xmlReader io.Reader) (m map[string]string, err error)
- func PostString(url, paramStr string) ([]byte, error)
- func RandInt64(min, max int64) int64
- func Random(n int) []byte
- func RandomString(n int) string
- func Request(httpURL, method string, params map[string]string) (string, error)
- func Round(num float64, precision int64) float64
- func Serialize(m interface{}) (string, error)
- func SerializeBytes(m interface{}) ([]byte, error)
- func SetShardId(id int) error
- func SetVersion(v int) error
- func Sign(token, timestamp, nonce string) (signature string)
- func String(args ...interface{}) string
- func StringSliceToInForSQL(slice []string) string
- func StringToBoolean(str string) bool
- func StringToBytes(s string) []byte
- func StringToSlice(str, sep string) []string
- func Strtotime(date string) int64
- func Substr(str string, start, length int) string
- func Ticket(key, Account string) string
- func Timetostr(unixTime int64) string
- func ToJSON(param interface{}) string
- func TrimMapValue(data map[string]string) map[string]string
- func UniqueSlice(slice *[]string)
- func Wrap(str, wraper string) string
- type AES
- type BufferPool
- type Cmd
- type Func
- type HMap
- func (this *HMap) Check(key string) bool
- func (this *HMap) Count() int
- func (this *HMap) Delete(key string)
- func (this *HMap) Get(key string) interface{}
- func (this *HMap) GetMap() map[string]interface{}
- func (this *HMap) GetToFloat32(key string) float32
- func (this *HMap) GetToFloat64(key string) float64
- func (this *HMap) GetToInt(key string) int
- func (this *HMap) GetToInt32(key string) int32
- func (this *HMap) GetToInt64(key string) int64
- func (this *HMap) GetToMap(key string) map[string]interface{}
- func (this *HMap) GetToString(key string) string
- func (this *HMap) IToS(value interface{}) string
- func (this *HMap) Remove(key string, defaultValue interface{}) interface{}
- func (this *HMap) Set(key string, value interface{}) bool
- type ITick
- type Ticker
- type TreeMap
Constants ¶
This section is empty.
Variables ¶
var (
// MaxRetries is the maximum number of retries before bailing.
MaxRetries = 10
)
var PathSeparator = string(os.PathSeparator)
PathSeparator is the string of os.PathSeparator
Functions ¶
func AESDecryptData ¶
func AESDecryptMsg ¶
ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
func AESEncryptMsg ¶
ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]
func Addslashes ¶
Quote string with slashes Returns a string with backslashes before characters that need to be escaped. These characters are single quote ('), double quote (") and backslash (\)
func AddslashesPlus ¶
func Boolean ¶
func Boolean(value interface{}) bool
// 123(true), 0(false),"-123"(true), "on"(true), "off"(false), "true"(true), "false"(false)
func BytesToString ¶
BytesToString accepts bytes and returns their string presentation instead of string() this method doesn't generate memory allocations, BUT it is not safe to use anywhere because it points this helps on 0 memory allocations
func CheckError ¶
func CheckInIntSlice ¶
func CheckInStrSlice ¶
func Command ¶
the below is just for exec.Command Command executes a command in shell and returns it's ouput, it's block versioin.
func ConvertToMap ¶
func ConvertToMap(model interface{}) map[string]interface{}
parses struct to map
func DeleteSliceItem ¶
func DeleteSliceItem(slice []interface{}, index int) []interface{}
delete a item from slice.
func Deserialize ¶
func DeserializeBytes ¶
DeserializeBytes converts the bytes to an object using gob decoder
func Do ¶
Do keeps trying the function until the second argument returns false, or no error is returned.
func FormatMapToXML ¶
FormatMapToXML marshal map[string]string to xmlWriter with xml format, the root node name is xml.
NOTE: This function assumes the key of m map[string]string are legitimate xml name string that does not contain the required escape character!
func GenIdInt64 ¶
func GenIdInt64() int64
func GetSliceMapValueByKey ¶
func GetSliceValueString ¶
根据给定的index获取slice对应的值
func GetStrBetweenStr ¶
获取两个字符串中间的字符串。此方法待完善。 例如:[aaaaa]bbbbbbb[aaaaaa]nnnnn[aaa], 获取中括号中的字符串
func HtmlEscape ¶
func IsMaxRetries ¶
IsMaxRetries checks whether the error is due to hitting the maximum number of retries or not.
func MustCommand ¶
MustCommand executes a command in shell and returns it's output, it's block version. It panics on an error
func Now ¶
func Now() int64
月份 1,01,Jan,January 日 2,02,_2 时 3,03,15,PM,pm,AM,am 分 4,04 秒 5,05 年 06,2006 周几 Mon,Monday 时区时差表示 -07,-0700,Z0700,Z07:00,-07:00,MST 时区字母缩写 MST
This function returns the local Time corresponding to the Unix time
func ParseXMLToMap ¶
ParseXMLToMap parses xml reading from xmlReader and returns the first-level sub-node key-value set, if the first-level sub-node contains child nodes, skip it.
func RandomString ¶
RandomString accepts a number(10 for example) and returns a random string using simple but fairly safe random algorithm
func SerializeBytes ¶
SerializeBytes serializa bytes using gob encoder and returns them
func StringSliceToInForSQL ¶
func StringToBoolean ¶
func StringToBytes ¶
StringToBytes accepts string and returns their []byte presentation instead of byte() this method doesn't generate memory allocations, BUT it is not safe to use anywhere because it points this helps on 0 memory allocations
func StringToSlice ¶
func Timetostr ¶
This function returns the unix time corresponding to date string. like 2006-01-02 15:04:05 if the unixTime equals 0 then the unixTime equals local time.
func UniqueSlice ¶
func UniqueSlice(slice *[]string)
Types ¶
type AES ¶
func (*AES) CryptedToString ¶
type BufferPool ¶
type BufferPool struct {
// contains filtered or unexported fields
}
BufferPool implements a pool of bytes.Buffers in the form of a bounded channel. Pulled from the github.com/oxtoacart/bpool package (Apache licensed).
func NewBufferPool ¶
func NewBufferPool(size int) (bp *BufferPool)
NewBufferPool creates a new BufferPool bounded to the given size.
func (*BufferPool) Get ¶
func (bp *BufferPool) Get() (b *bytes.Buffer)
Get gets a Buffer from the BufferPool, or creates a new one if none are available in the pool.
func (*BufferPool) Put ¶
func (bp *BufferPool) Put(b *bytes.Buffer)
Put returns the given Buffer to the BufferPool.
type Cmd ¶
Cmd is a custom struch which 'implements' the *exec.Cmd
func CommandBuilder ¶
CommandBuilder creates a Cmd object and returns it accepts 2 parameters, one is optionally first parameter is the command (string) second variatic parameter is the argument(s) (slice of string)
the difference from the normal Command function is that you can re-use this Cmd, it doesn't execute until you call its Command function
func (*Cmd) AppendArguments ¶
AppendArguments appends the arguments to the exists.
func (*Cmd) Arguments ¶
Arguments sets the command line arguments, including the command as Args[0] If the args parameter is empty or nil, Run uses {Path}. In typical use, both Path and args are set by calling Command.
func (*Cmd) Directory ¶
Directory sets the working directory of the command. If workingDirectory is the empty string, Run runs the command in the calling process's current directory.
func (*Cmd) ResetArguments ¶
ResetArguments resets the arguments.
type HMap ¶
type HMap struct { SMap map[string]interface{} // contains filtered or unexported fields }
HMap is a map with lock
func (*HMap) GetToFloat32 ¶
func (*HMap) GetToFloat64 ¶
func (*HMap) GetToInt32 ¶
func (*HMap) GetToInt64 ¶
func (*HMap) GetToString ¶
type ITick ¶
type ITick interface {
OnTick()
}
ITick is the interface which all ticker's listeners must implement
type Ticker ¶
type Ticker struct {
// contains filtered or unexported fields
}
Ticker is the timer which is used in cache
func (*Ticker) OnTick ¶
func (c *Ticker) OnTick(h func())
OnTick add event handlers/ callbacks which are called on each timer's tick
type TreeMap ¶
type TreeMap struct { PrimaryKey string // 主键字段名 ParentFieldKey string // 父级ID字段名 ChildrenKey string // 子叶Key名称 NewTreeForData []map[string]interface{} }