tools

package
v0.0.0-...-49ccde3 Latest Latest
Warning

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

Go to latest
Published: Mar 26, 2020 License: Apache-2.0 Imports: 29 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
var (
	// MaxRetries is the maximum number of retries before bailing.
	MaxRetries = 10
)
View Source
var PathSeparator = string(os.PathSeparator)

PathSeparator is the string of os.PathSeparator

Functions

func AESDecryptData

func AESDecryptData(cipherText []byte, aesKey []byte, iv []byte) (rawData []byte, err error)

func AESDecryptMsg

func AESDecryptMsg(ciphertext []byte, aesKey []byte) (random, rawXMLMsg, appId []byte, err error)

ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]

func AESEncryptMsg

func AESEncryptMsg(random, rawXMLMsg []byte, appId string, aesKey []byte) (ciphertext []byte)

ciphertext = AES_Encrypt[random(16B) + msg_len(4B) + rawXMLMsg + appId]

func Addslashes

func Addslashes(str string) string

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 AddslashesPlus(str string) string

func Boolean

func Boolean(value interface{}) bool

// 123(true), 0(false),"-123"(true), "on"(true), "off"(false), "true"(true), "false"(false)

func BytesToString

func BytesToString(b []byte) string

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 CheckError(err error, exit bool)

func CheckInIntSlice

func CheckInIntSlice(key int, intSlice []int) bool

func CheckInStrSlice

func CheckInStrSlice(key string, strSlice []string) bool

func Command

func Command(command string, args ...string) (output string, err error)

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 DateTimeToDate

func DateTimeToDate(dateTime string) string

2006-01-02 15:04:05 to 2006-01-02

func DecodeJson

func DecodeJson(jsonStr string) interface{}

json to map

func DeleteSliceItem

func DeleteSliceItem(slice []interface{}, index int) []interface{}

delete a item from slice.

func Deserialize

func Deserialize(str string, m interface{}) error

func DeserializeBytes

func DeserializeBytes(b []byte, m interface{}) error

DeserializeBytes converts the bytes to an object using gob decoder

func Do

func Do(fn Func) error

Do keeps trying the function until the second argument returns false, or no error is returned.

func FindLower

func FindLower(a, b int) int

func Float32

func Float32(value interface{}) float32

func Float64

func Float64(value interface{}) float64

func FormatMapToXML

func FormatMapToXML(xmlWriter io.Writer, m map[string]string) (err error)

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 GenId

func GenId() uint64

获取id |version:4bit|timestamp:39bit|shardId:13bit|squence:8bit

func GenIdInt64

func GenIdInt64() int64

func GetDate

func GetDate() string

func GetIP

func GetIP() (string, error)

GetIP returns the ip address of a client.

func GetSequence

func GetSequence(id uint64) uint64

获取id当前的序列号

func GetShardId

func GetShardId(id uint64) int

获取id的分区id(组件唯一标识)

func GetSliceMapValueByKey

func GetSliceMapValueByKey(params []map[string]interface{}, key string) string

func GetSliceValueString

func GetSliceValueString(slice []string, index int, defaultValue string) string

根据给定的index获取slice对应的值

func GetStrBetweenStr

func GetStrBetweenStr(str, strA, strB string) []string

获取两个字符串中间的字符串。此方法待完善。 例如:[aaaaa]bbbbbbb[aaaaaa]nnnnn[aaa], 获取中括号中的字符串

func GetTime

func GetTime(id uint64) time.Time

获取id生成时间Time

func GetTimeUnixMill

func GetTimeUnixMill(id int64) int64

获取id的UinxMill时间戳

func GetTimeUnixNano

func GetTimeUnixNano(id uint64) int64

获取id的UinxNano时间戳

func GetVersion

func GetVersion(id uint64) int

获取id的版本信息

func HtmlEscape

func HtmlEscape(s string) string

func Int

func Int(value interface{}) int

func Int32

func Int32(value interface{}) int32

func Int64

func Int64(value interface{}) int64

func IsEmpty

func IsEmpty(value interface{}) bool

Determine whether a variable is empty

func IsMaxRetries

func IsMaxRetries(err error) bool

IsMaxRetries checks whether the error is due to hitting the maximum number of retries or not.

func IsNumeric

func IsNumeric(val interface{}) bool

func MapToTree

func MapToTree(list interface{}, parentID string, childFieldName string) []map[string]interface{}

func Md5hash

func Md5hash(str string) string

md5

func MsgSign

func MsgSign(token, timestamp, nonce, encryptedMsg string) (signature string)

MsgSign 微信公众号/企业号 消息体签名.

func MustCommand

func MustCommand(command string, args ...string) (output string)

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

func ParseXMLToMap(xmlReader io.Reader) (m map[string]string, err error)

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 PostString

func PostString(url, paramStr string) ([]byte, error)

发送POST请求, 返回Body

func RandInt64

func RandInt64(min, max int64) int64

生成随机数 [min, max)

func Random

func Random(n int) []byte

func RandomString

func RandomString(n int) string

RandomString accepts a number(10 for example) and returns a random string using simple but fairly safe random algorithm

func Request

func Request(httpURL, method string, params map[string]string) (string, error)

发送GET和POST请求

func Round

func Round(num float64, precision int64) float64

浮点数四舍五入

func Serialize

func Serialize(m interface{}) (string, error)

func SerializeBytes

func SerializeBytes(m interface{}) ([]byte, error)

SerializeBytes serializa bytes using gob encoder and returns them

func SetShardId

func SetShardId(id int) error

设置分区id

func SetVersion

func SetVersion(v int) error

设置id版本

func Sign

func Sign(token, timestamp, nonce string) (signature string)

Sign 微信公众号 url 签名.

func String

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

args: value, precision(only for float)

func StringSliceToInForSQL

func StringSliceToInForSQL(slice []string) string

func StringToBoolean

func StringToBoolean(str string) bool

func StringToBytes

func StringToBytes(s string) []byte

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 StringToSlice(str, sep string) []string

func Strtotime

func Strtotime(date string) int64

Format date string to unix time,like the function of PHP with strtotime

func Substr

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

func Ticket

func Ticket(key, Account string) string

Ticket generates a ticket for user.

func Timetostr

func Timetostr(unixTime int64) string

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 ToJSON

func ToJSON(param interface{}) string

func TrimMapValue

func TrimMapValue(data map[string]string) map[string]string

func UniqueSlice

func UniqueSlice(slice *[]string)

func Wrap

func Wrap(str, wraper string) string

Types

type AES

type AES struct {
	Key     string
	Origin  string
	Crypted string
}

func (*AES) CryptedToString

func (this *AES) CryptedToString() string

func (*AES) Decrypt

func (this *AES) Decrypt() error

func (*AES) Encrypt

func (this *AES) Encrypt() error

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

type Cmd struct {
	*exec.Cmd
}

Cmd is a custom struch which 'implements' the *exec.Cmd

func CommandBuilder

func CommandBuilder(command string, args ...string) *Cmd

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

func (this *Cmd) AppendArguments(args ...string) *Cmd

AppendArguments appends the arguments to the exists.

func (*Cmd) Arguments

func (this *Cmd) Arguments(args ...string) *Cmd

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

func (this *Cmd) Directory(workingDirectory string) *Cmd

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

func (this *Cmd) ResetArguments() *Cmd

ResetArguments resets the arguments.

type Func

type Func func(attempt int) (retry bool, err error)

Func represents functions that can be retried.

type HMap

type HMap struct {
	SMap map[string]interface{}
	// contains filtered or unexported fields
}

HMap is a map with lock

func NewMap

func NewMap(smap ...map[string]interface{}) *HMap

NewMap returns a new safe map.

func (*HMap) Check

func (this *HMap) Check(key string) bool

Checker returns true is key is exist in the map, otherwise returns false.

func (*HMap) Count

func (this *HMap) Count() int

Count returns the number of items within the map

func (*HMap) Delete

func (this *HMap) Delete(key string)

func (*HMap) Get

func (this *HMap) Get(key string) interface{}

func (*HMap) GetMap

func (this *HMap) GetMap() map[string]interface{}

GetMap returns all item in the safe map.

func (*HMap) GetToFloat32

func (this *HMap) GetToFloat32(key string) float32

func (*HMap) GetToFloat64

func (this *HMap) GetToFloat64(key string) float64

func (*HMap) GetToInt

func (this *HMap) GetToInt(key string) int

func (*HMap) GetToInt32

func (this *HMap) GetToInt32(key string) int32

func (*HMap) GetToInt64

func (this *HMap) GetToInt64(key string) int64

func (*HMap) GetToMap

func (this *HMap) GetToMap(key string) map[string]interface{}

func (*HMap) GetToString

func (this *HMap) GetToString(key string) string

func (*HMap) IToS

func (this *HMap) IToS(value interface{}) string

func (*HMap) Remove

func (this *HMap) Remove(key string, defaultValue interface{}) interface{}

func (*HMap) Set

func (this *HMap) Set(key string, value interface{}) bool

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 NewTicker

func NewTicker() *Ticker

NewTicker returns a new Ticker

func (*Ticker) OnTick

func (c *Ticker) OnTick(h func())

OnTick add event handlers/ callbacks which are called on each timer's tick

func (*Ticker) Start

func (c *Ticker) Start(duration time.Duration)

Start starts the timer and execute all listener's when tick

func (*Ticker) Stop

func (c *Ticker) Stop()

Stop stops the ticker

type TreeMap

type TreeMap struct {
	PrimaryKey     string // 主键字段名
	ParentFieldKey string // 父级ID字段名
	ChildrenKey    string // 子叶Key名称

	NewTreeForData []map[string]interface{}
}

func (*TreeMap) FormatTree

func (this *TreeMap) FormatTree(list []map[string]interface{}, parentField,
	parentID, space string) []map[string]interface{}

func (*TreeMap) MapToTree

func (this *TreeMap) MapToTree(originMap []map[string]interface{}, parentID string) []map[string]interface{}

Jump to

Keyboard shortcuts

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