Documentation ¶
Overview ¶
This package provides misc utilities.
Array process ¶
MakeAbstractArray() wraps an array object to *AbstractArray.
Error Handler ¶
PanicToError() could be used to transfer a panic code to customized error object ¶
PanicToSimpleError() could be used to transfer a panic code to simple error object
func your_func() (err error) { defer PanicToSimpleError(&err)() // Code may cause panic... }
You can wrap a function to a function with error returned:
func your_func(int) { /**/ } errFunc := PanicToSimpleErrorWrapper( func() { your_func(var_1) }, ) err := errFunc()
Capture panic to special handler ¶
If a go routine gets panic, the process would be terminated by default, you could use "BuildPanicCapture" to prevent the behavior.
panicFreeFunc := utils.BuildPanicCapture( func() { /* Your code... */ }, func(panicObject interface{}) { /* Gets executed if there is non-nil panic while executing your code */ }, ) go panicFreeFunc()
Alternatively, there is a "BuildPanicToError" to set error object into "error pointer" if something gets panic.
Stack error ¶
If you are writing IoC framework, the code position in framework may be too complex while output panic message, you could use "StackError" to record caller's position:
func yourLibrary() error { err := someFunc() if err != nil { return BuildErrorWithCaller(err) } return nil }
For lambda-style programming, you could use "common/runtime.GetCallerInfo()" to keep the position of caller:
func yourIoc(clientCode func()) { callerInfo := runtime.GetCallerInfo() defer func() { p := recover() if p != nil { panic(BuildErrorWithCallerInfo(SimpleErrorConverter(p), callerInfo)) } } clinetCode() }
Index ¶
- Constants
- Variables
- func AppendToAny(arrayOfAny []interface{}, any interface{}) []interface{}
- func AreArrayOfStringsSame(leftArray []string, rightArray []string) bool
- func BuildPanicCapture(targetFunc func(), panicHandler func(interface{})) func()
- func BuildPanicToError(targetFunc func(), errHolder *error) func()
- func CartesianProduct(listOfSets ...interface{}) [][]interface{}
- func Checksum(endpoint string, metric string, tags map[string]string) string
- func ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string
- func CompareAny(left interface{}, right interface{}, direction byte) int
- func CompareFloat(left float64, right float64, direction byte) int
- func CompareInt(left int64, right int64, direction byte) int
- func CompareIpAddress(leftIp net.IP, rightIp net.IP, direction byte) int
- func CompareNil(left interface{}, right interface{}, direction byte) (r int, hasNil bool)
- func CompareString(left string, right string, direction byte) int
- func CompareUint(left uint64, right uint64, direction byte) int
- func ConvertTo(value interface{}, targetType reflect.Type) interface{}
- func ConvertToByReflect(sourceValue reflect.Value, targetType reflect.Type) reflect.Value
- func ConvertToTargetType(value interface{}, targetValue interface{}) interface{}
- func Counter(metric string, tags map[string]string) string
- func DeferCatchPanicWithCaller() func()
- func DictedTagstring(s string) map[string]string
- func FlattenToSlice(source interface{}, convertFunc func(v interface{}) []interface{}) []interface{}
- func IdentityMapper(v interface{}) interface{}
- func IntTo16(source []int64) []int16
- func IntTo32(source []int64) []int32
- func IntTo8(source []int64) []int8
- func IsViable(v interface{}) bool
- func KeysOfMap(m map[string]string) []string
- func Md5(raw string) string
- func PK(endpoint, metric string, tags map[string]string) string
- func PK2(endpoint, counter string) string
- func PanicToError(err *error, errConverter ErrorConverter) func()
- func PanicToErrorWrapper(mainFunc func(), errConverter ErrorConverter) func() error
- func PanicToSimpleError(err *error) func()
- func PanicToSimpleErrorWrapper(mainFunc func()) func() error
- func PointerOfCloneString(source string) *string
- func ReadableFloat(raw float64) string
- func ReverseIfDescending(result int, direction byte) int
- func ShortenStringToSize(s string, more string, maxSize int) string
- func SimpleErrorConverter(p interface{}) error
- func SortAndUniqueInt64(source []int64) []int64
- func SortAndUniqueUint64(source []uint64) []uint64
- func SortedTags(tags map[string]string) string
- func SplitTagsString(s string) (err error, tags map[string]string)
- func UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string
- func UintTo16(source []uint64) []uint16
- func UintTo32(source []uint64) []uint32
- func UintTo8(source []uint64) []uint8
- func UniqueArrayOfStrings(arrayOfStrings []string) []string
- func UniqueElements(arrayOrSlice interface{}) interface{}
- func UnixTsFormat(ts int64) string
- type AbstractArray
- func (a *AbstractArray) BatchProcess(batchSize int, batchProcessor func(batch interface{}), ...)
- func (a *AbstractArray) FilterWith(filter FilterFunc) *AbstractArray
- func (a *AbstractArray) GetArray() interface{}
- func (a *AbstractArray) GetArrayAsTargetType(targetValue interface{}) interface{}
- func (a *AbstractArray) GetArrayAsType(elemTypeOfTarget reflect.Type) interface{}
- func (a *AbstractArray) GetArrayOfAny() []interface{}
- func (a *AbstractArray) MapTo(mapper MapperFunc, eleType reflect.Type) *AbstractArray
- type AbstractMap
- type ErrorConverter
- type FilterFunc
- type GroupingProcessor
- type Int64Slice
- type KeyGetter
- type MapperFunc
- type PanicHandler
- type StackError
- type Uint64Slice
- type ValueExt
Examples ¶
Constants ¶
const ( DefaultDirection byte = 0 // Sorting by ascending Ascending byte = 1 // Sorting by descending Descending byte = 2 // The sequence should be higher SeqHigher = 1 // The sequence is equal SeqEqual = 0 // The sequence should be lower SeqLower = -1 )
Variables ¶
var ( TrimStringMapper = TypedFuncToMapper(func(v string) string { return strings.TrimSpace(v) }) EmptyStringFilter = TypedFuncToFilter(func(v string) bool { return v != "" }) )
var ( TypeOfInt = ot.TypeOfInt TypeOfInt64 = ot.TypeOfInt64 TypeOfInt32 = ot.TypeOfInt32 TypeOfInt16 = ot.TypeOfInt16 TypeOfInt8 = ot.TypeOfInt8 TypeOfUint = ot.TypeOfUint TypeOfUint64 = ot.TypeOfUint64 TypeOfUint32 = ot.TypeOfUint32 TypeOfUint16 = ot.TypeOfUint16 TypeOfUint8 = ot.TypeOfUint8 TypeOfFloat32 = ot.TypeOfFloat32 TypeOfFloat64 = ot.TypeOfFloat64 TypeOfComplex64 = ot.TypeOfComplex64 TypeOfComplex128 = ot.TypeOfComplex128 TypeOfByte = ot.TypeOfByte TypeOfBool = ot.TypeOfBool TypeOfString = ot.TypeOfString ATypeOfInt = ot.STypeOfInt ATypeOfInt64 = ot.STypeOfInt64 ATypeOfInt32 = ot.STypeOfInt32 ATypeOfInt16 = ot.STypeOfInt16 ATypeOfInt8 = ot.STypeOfInt8 ATypeOfUint = ot.STypeOfUint ATypeOfUint64 = ot.STypeOfUint64 ATypeOfUint32 = ot.STypeOfUint32 ATypeOfUint16 = ot.STypeOfUint16 ATypeOfUint8 = ot.STypeOfUint8 ATypeOfFloat32 = ot.STypeOfFloat32 ATypeOfFloat64 = ot.STypeOfFloat64 ATypeOfComplex64 = ot.STypeOfComplex64 ATypeOfComplex128 = ot.STypeOfComplex128 ATypeOfByte = ot.STypeOfByte ATypeOfBool = ot.STypeOfBool ATypeOfString = ot.STypeOfString TrueValue = ot.TrueValue FalseValue = ot.FalseValue )
Functions ¶
func AppendToAny ¶
func AppendToAny(arrayOfAny []interface{}, any interface{}) []interface{}
func AreArrayOfStringsSame ¶
Checks the two array of strings are same
This function would sort there two strings first, then check their equality.
The array of nil and array of empty are seen the same one.
func BuildPanicCapture ¶
func BuildPanicCapture(targetFunc func(), panicHandler func(interface{})) func()
Builds simple function, which executes target function with panic handler(panic-free)
func BuildPanicToError ¶
func BuildPanicToError(targetFunc func(), errHolder *error) func()
Builds sample function, which captures panic object and convert it to error object
func CartesianProduct ¶
func CartesianProduct(listOfSets ...interface{}) [][]interface{}
Performs Cartesian product and gives list of product results
Every element should be slice or array.
func ChecksumOfUUID ¶
func CompareAny ¶
Compares any value. supporting:
String Interger Unsigned Integer Float
net.IP
This funcation would be slower than typed function
func CompareIpAddress ¶
Compares IP address from left-most byte(numeric-sensitive)
func CompareNil ¶
For ascending:
Nil / Not Nil: SeqHigher Nil / Nil: SeqEqual Not Nil / Nil: SeqLower
descending is the Reverse of ascending
Returns:
if the second value is true, means at least one of their value is nil
func ConvertTo ¶
Super conversion by reflect
1. Nil pointer would be to nil pointer of target type 2. Othewise, uses the reflect.Value.Convert() function to perform conversion
func ConvertToByReflect ¶
func ConvertToTargetType ¶
func ConvertToTargetType(value interface{}, targetValue interface{}) interface{}
func DeferCatchPanicWithCaller ¶
func DeferCatchPanicWithCaller() func()
func DictedTagstring ¶
func FlattenToSlice ¶
func FlattenToSlice(source interface{}, convertFunc func(v interface{}) []interface{}) []interface{}
Flatten a array or slice object by customized function.
This function combines the flatten ones to a slice of []interface{}
func IdentityMapper ¶
func IdentityMapper(v interface{}) interface{}
func PanicToError ¶
func PanicToError(err *error, errConverter ErrorConverter) func()
Converts the panic content to error object
err - The holder of error object errConverter - The builder function for converting non-error object to error object
Example ¶
sampleFunc := func() (err error) { defer PanicToError( &err, func(p interface{}) error { return fmt.Errorf("Customized: %v", p) }, )() panic("Good Error!!") } err := sampleFunc() fmt.Println(err)
Output: Customized: Good Error!!
func PanicToErrorWrapper ¶
func PanicToErrorWrapper(mainFunc func(), errConverter ErrorConverter) func() error
Convert a lambda function to function with error returned
func PanicToSimpleError ¶
func PanicToSimpleError(err *error) func()
Converts the panic content to error object by SimpleErrorConverter()
Example ¶
sampleFunc := func() (err error) { defer PanicToSimpleError(&err)() panic("Novel Error!!") } err := sampleFunc() fmt.Println(err)
Output: Novel Error!!
func PanicToSimpleErrorWrapper ¶
func PanicToSimpleErrorWrapper(mainFunc func()) func() error
Convert a lambda function to function with error returned(by SimpleErrorConverter)
Example ¶
sampleFunc := func(n int) { panic(fmt.Sprintf("Value: %d", n)) } testedFunc := PanicToSimpleErrorWrapper( func() { sampleFunc(918) }, ) fmt.Println(testedFunc())
Output:
func PointerOfCloneString ¶
If the value of source is empty(""), gets nil pointer
func ReadableFloat ¶
func ReverseIfDescending ¶
func ShortenStringToSize ¶
Shorten string to "<heading chars> <more> <tailing chars>(total size)" if the length of input is greater than "maxSize".
For example of 4 characters of maximum size(more is "..."):
"abcd" -> "abcd" "abcde" -> "ab ...(4) de" "This is hello world!" -> "Th ...(4) d!"
If "more" is empty, the result string would be "<heading chars> <tailing chars>"
func SimpleErrorConverter ¶
func SimpleErrorConverter(p interface{}) error
Simple converter for converting non-error object to error object by:
fmt.Errorf("%v", object)
func SortAndUniqueInt64 ¶
Sorts the value of int64 with unique processing
func SortAndUniqueUint64 ¶
Sorts the value of int64 with unique processing
func SortedTags ¶
func UniqueArrayOfStrings ¶
Makes the array of strings unique, which is stable(the sequence of output is same as input)
func UniqueElements ¶
func UniqueElements(arrayOrSlice interface{}) interface{}
Uses reflect.* to make unique element of input array
func UnixTsFormat ¶
Types ¶
type AbstractArray ¶
type AbstractArray struct {
// contains filtered or unexported fields
}
Abstract array to provide various function for processing array
func MakeAbstractArray ¶
func MakeAbstractArray(sourceSlice interface{}) *AbstractArray
Constructs an array of abstract
func (*AbstractArray) BatchProcess ¶
func (a *AbstractArray) BatchProcess( batchSize int, batchProcessor func(batch interface{}), restProcessor func(rest interface{}), )
Splits the array to batch and feeds every batch to "batchProcessor", the rest of data would be feed to restProcessor
func (*AbstractArray) FilterWith ¶
func (a *AbstractArray) FilterWith(filter FilterFunc) *AbstractArray
Filters elements in the array
func (*AbstractArray) GetArray ¶
func (a *AbstractArray) GetArray() interface{}
Gets the result array
func (*AbstractArray) GetArrayAsTargetType ¶
func (a *AbstractArray) GetArrayAsTargetType(targetValue interface{}) interface{}
func (*AbstractArray) GetArrayAsType ¶
func (a *AbstractArray) GetArrayAsType(elemTypeOfTarget reflect.Type) interface{}
Gets the result array as desired type(element)
func (*AbstractArray) GetArrayOfAny ¶
func (a *AbstractArray) GetArrayOfAny() []interface{}
func (*AbstractArray) MapTo ¶
func (a *AbstractArray) MapTo(mapper MapperFunc, eleType reflect.Type) *AbstractArray
Maps the elements in array(with target type of result array)
type AbstractMap ¶
type AbstractMap struct {
// contains filtered or unexported fields
}
func MakeAbstractMap ¶
func MakeAbstractMap(sourceMap interface{}) *AbstractMap
func (*AbstractMap) ToType ¶
func (m *AbstractMap) ToType(keyType reflect.Type, elemType reflect.Type) interface{}
Gets map of desired type
func (*AbstractMap) ToTypeOfTarget ¶
func (m *AbstractMap) ToTypeOfTarget(keyOfTarget interface{}, elemOfTarget interface{}) interface{}
type ErrorConverter ¶
type ErrorConverter func(p interface{}) error
Defines the converter from converting any value to error object
type FilterFunc ¶
type FilterFunc func(interface{}) bool
This function is used to get bool value to decide
func NewDomainFilter ¶
func NewDomainFilter(mapOfDomain interface{}) FilterFunc
Constructs a filter, which uses domain(map[<type]bool) of golang as filtering
The element must be shown in domain.
func NewUniqueFilter ¶
func NewUniqueFilter(targetType reflect.Type) FilterFunc
Constructs a filter, which uses map of golang.
**WARNING** The generated filter cannot be reused
targetType - Could be array, slice, or element type
func TypedFuncToFilter ¶
func TypedFuncToFilter(anyFunc interface{}) FilterFunc
Converts typed function(for filter) to FilterFunc
type GroupingProcessor ¶
type GroupingProcessor struct {
// contains filtered or unexported fields
}
func NewGroupingProcessor ¶
func NewGroupingProcessor(typeOfElem reflect.Type) *GroupingProcessor
func NewGroupingProcessorOfTargetType ¶
func NewGroupingProcessorOfTargetType(target interface{}) *GroupingProcessor
func (*GroupingProcessor) Children ¶
func (g *GroupingProcessor) Children(keyObject KeyGetter) interface{}
func (*GroupingProcessor) KeyObject ¶
func (g *GroupingProcessor) KeyObject(keyObject KeyGetter) interface{}
func (*GroupingProcessor) Keys ¶
func (g *GroupingProcessor) Keys() []KeyGetter
func (*GroupingProcessor) Put ¶
func (g *GroupingProcessor) Put(keyObject KeyGetter, child interface{})
type Int64Slice ¶
type Int64Slice []int64
func (Int64Slice) Len ¶
func (s Int64Slice) Len() int
func (Int64Slice) Less ¶
func (s Int64Slice) Less(i, j int) bool
func (Int64Slice) Swap ¶
func (s Int64Slice) Swap(i, j int)
type MapperFunc ¶
type MapperFunc func(interface{}) interface{}
This function is used to transfer element
func TypedFuncToMapper ¶
func TypedFuncToMapper(anyFunc interface{}) MapperFunc
Converts typed function(for filter) to MapperFunc
type StackError ¶
type StackError struct {
// contains filtered or unexported fields
}
func BuildErrorWithCaller ¶
func BuildErrorWithCaller(err error) *StackError
func BuildErrorWithCallerDepth ¶
func BuildErrorWithCallerDepth(err error, depth int) *StackError
func BuildErrorWithCallerInfo ¶
func BuildErrorWithCallerInfo(err error, callerInfo *gr.CallerInfo) *StackError
Builds the error object with caller info, if the error object is type of *StackError, replaces the caller info with the new one
func (*StackError) Error ¶
func (e *StackError) Error() string
type Uint64Slice ¶
type Uint64Slice []uint64
func (Uint64Slice) Len ¶
func (s Uint64Slice) Len() int
func (Uint64Slice) Less ¶
func (s Uint64Slice) Less(i, j int) bool
func (Uint64Slice) Swap ¶
func (s Uint64Slice) Swap(i, j int)