utils

package
v3.15.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2018 License: Apache-2.0, Apache-2.0 Imports: 13 Imported by: 76

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

Examples

Constants

View Source
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

View Source
var (
	TrimStringMapper = TypedFuncToMapper(func(v string) string {
		return strings.TrimSpace(v)
	})

	EmptyStringFilter = TypedFuncToFilter(func(v string) bool {
		return v != ""
	})
)
View Source
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

func AreArrayOfStringsSame(leftArray []string, rightArray []string) bool

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 Checksum

func Checksum(endpoint string, metric string, tags map[string]string) string

func ChecksumOfUUID

func ChecksumOfUUID(endpoint, metric string, tags map[string]string, dstype string, step int64) string

func CompareAny

func CompareAny(left interface{}, right interface{}, direction byte) int

Compares any value. supporting:

String Interger Unsigned Integer Float

net.IP

This funcation would be slower than typed function

func CompareFloat

func CompareFloat(left float64, right float64, direction byte) int

func CompareInt

func CompareInt(left int64, right int64, direction byte) int

func CompareIpAddress

func CompareIpAddress(leftIp net.IP, rightIp net.IP, direction byte) int

Compares IP address from left-most byte(numeric-sensitive)

func CompareNil

func CompareNil(left interface{}, right interface{}, direction byte) (r int, hasNil bool)

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 CompareString

func CompareString(left string, right string, direction byte) int

func CompareUint

func CompareUint(left uint64, right uint64, direction byte) int

func ConvertTo

func ConvertTo(value interface{}, targetType reflect.Type) interface{}

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

See https://golang.org/ref/spec#Conversions

func ConvertToByReflect

func ConvertToByReflect(sourceValue reflect.Value, targetType reflect.Type) reflect.Value

func ConvertToTargetType

func ConvertToTargetType(value interface{}, targetValue interface{}) interface{}

func Counter

func Counter(metric string, tags map[string]string) string

func DeferCatchPanicWithCaller

func DeferCatchPanicWithCaller() func()

func DictedTagstring

func DictedTagstring(s string) map[string]string

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 IntTo16

func IntTo16(source []int64) []int16

Converts 64 bits integer to 16 bits one

func IntTo32

func IntTo32(source []int64) []int32

Converts 64 bits integer to 32 bits one

func IntTo8

func IntTo8(source []int64) []int8

Converts 64 bits integer to 8 bits one

func IsViable

func IsViable(v interface{}) bool

func KeysOfMap

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

TODO 以下的部分, 考虑放到公共组件库

func Md5

func Md5(raw string) string

func PK

func PK(endpoint, metric string, tags map[string]string) string

func PK2

func PK2(endpoint, counter string) string

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

func PointerOfCloneString(source string) *string

If the value of source is empty(""), gets nil pointer

func ReadableFloat

func ReadableFloat(raw float64) string

func ReverseIfDescending

func ReverseIfDescending(result int, direction byte) int

func ShortenStringToSize

func ShortenStringToSize(s string, more string, maxSize int) string

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

func SortAndUniqueInt64(source []int64) []int64

Sorts the value of int64 with unique processing

func SortAndUniqueUint64

func SortAndUniqueUint64(source []uint64) []uint64

Sorts the value of int64 with unique processing

func SortedTags

func SortedTags(tags map[string]string) string

func SplitTagsString

func SplitTagsString(s string) (err error, tags map[string]string)

func UUID

func UUID(endpoint, metric string, tags map[string]string, dstype string, step int) string

func UintTo16

func UintTo16(source []uint64) []uint16

Converts 64 bits integer(unsigned) to 16 bits one

func UintTo32

func UintTo32(source []uint64) []uint32

Converts 64 bits integer(unsigned) to 32 bits one

func UintTo8

func UintTo8(source []uint64) []uint8

Converts 64 bits integer(unsigned) to 8 bits one

func UniqueArrayOfStrings

func UniqueArrayOfStrings(arrayOfStrings []string) []string

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

func UnixTsFormat(ts int64) string

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 KeyGetter

type KeyGetter interface {
	GetKey() interface{}
}

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 PanicHandler

type PanicHandler func(interface{})

Defines the handler of panic

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)

type ValueExt

type ValueExt reflect.Value

Alias of reflect.Value, provides some convenient functions for programming on reflection.

func (ValueExt) IsArray

func (v ValueExt) IsArray() bool

Returns true value if the value is array or slice

func (ValueExt) IsPointer

func (v ValueExt) IsPointer() bool

Returns true value if the value is reflect.Ptr, reflect.Uintptr, or reflect.UnsafePointer

func (ValueExt) IsViable

func (v ValueExt) IsViable() bool

Checks if a value is viable

For array, slice, map, chan: the value.Len() must be > 0

For pointer, interface, or function: the value.IsNil() must not be true

Othewise: use reflect.Value.IsValid()

Jump to

Keyboard shortcuts

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