Documentation
¶
Index ¶
- Constants
- Variables
- func CopyMap[K comparable, V any](m map[K]V) map[K]V
- func DefaultStringIfEmpty(s, dv string) stringdeprecated
- func Download(url string, dest string) (err error)
- func FileSize[T constraints.Integer](s T) string
- func Filter[T any](slice []T, fn func(T) bool) []T
- func FilterInPlace[T any](slice *[]T, fn func(T) bool)
- func FilterLegacy(slice, fn interface{}) interface{}
- func FormatMsgAndArgs(msgAndArgs ...any) string
- func GetCaller() string
- func HandleCrash(additionalHandlers ...func(interface{}))
- func HandleError(err error)
- func HumanReadableDuration(diffSeconds int64) string
- func IgnoreErr[R any](fn func() (R, error)) func() R
- func IgnoreErr1[P any, R any](fn func(P) (R, error)) func(P) R
- func IgnoreErr2[P1 any, P2 any, R any](fn func(P1, P2) (R, error)) func(P1, P2) R
- func Indent(s, prefix string) string
- func IndentBytes(b, prefix []byte) []byte
- func Index(s, substr string) int
- func IsDir(path string) bool
- func IsExist(path string) bool
- func IsFile(path string) bool
- func IsIPv4(s string) bool
- func LeftPad(s string, padStr string, length int) string
- func ListAllEnvs() map[string]string
- func MakeRange(min, max int) []int
- func Map[From any, To any](src []From, fn func(obj From) To) []To
- func MapInPlace[T any](src []T, fn func(obj T) T)
- func MarshalAndWriteFile(v any, file string) error
- func MergeMap[K comparable, V any](base map[K]V, overrides ...map[K]V) map[K]V
- func MergeStrIFaceMaps(to, from map[string]any) map[string]any
- func Must(err error)
- func PartialSwap[P1 any, P2 any, R any](fn func(P1, P2) R) func(P2, P1) R
- func ReadFileAndUnmarshal(file string, v any) error
- func ReadFileInt(file string) (val int, err error)
- func RecoverFromPanic(err *error)
- func Reduce[T any, R any](slice []T, fn func(T, R) R, zeroValue R) R
- func RightPad(s string, padStr string, length int) string
- func Round(val float64, precision int) float64
- func SafeExec(cmd *exec.Cmd, timeout time.Duration, fn func(*exec.Cmd) error) (killed bool, err error)
- func SafeExecWithCombinedOutput(cmd *exec.Cmd, timeout time.Duration) (output []byte, killed bool, err error)
- func Trim(str string) string
- func TrimLeft(str string) string
- func TrimRight(str string) string
- func UUID() string
- func UnsafeBytesToString(b []byte) string
- func UnsafeStringToBytes(s string) (b []byte)
- func WildcardMatch(pattern, name string) (matched bool)
- func WildcardMatchSimple(pattern, name string) bool
- func ZeroFill(s string, length int) string
- type Counter
- type RingBuffer
- type SysStatus
Constants ¶
const EmptyStr = ""
EmptyStr is the empty string const
const RegIPv4 = "(([2][5][0-5]|[2][0-4][0-9]|[1][0-9]{2}|[1-9][0-9]|[0-9])[.]){3}([2][5][0-5]|[2][0-4][0-9]|[1][0-9]{2}|[1-9][0-9]|[0-9])"
RegIPv4 is the IPv4 Regexp
Variables ¶
var ErrorHandlers = []func(error){ logError, (&rudimentaryErrorBackoff{ lastErrorTime: time.Now(), minPeriod: time.Millisecond, }).OnError, }
ErrorHandlers is a list of functions which will be invoked when a nonreturnable error occurs. TODO(lavalamp): for testability, this and the below HandleError function should be packaged up into a testable and reusable object.
var PanicHandlers = []func(interface{}){logPanic}
PanicHandlers is a list of functions which will be invoked when a panic happens.
var ( // ReallyCrash controls the behavior of HandleCrash and defaults to // true. It's exposed so components can optionally set to false // to restore prior behavior. This flag is mostly used for tests to validate // crash conditions. ReallyCrash = true )
Functions ¶
func CopyMap ¶
func CopyMap[K comparable, V any](m map[K]V) map[K]V
CopyMap makes a shallow copy of a map.
func DefaultStringIfEmpty
deprecated
func FileSize ¶
func FileSize[T constraints.Integer](s T) string
FileSize translate bytes number into human-readable size
func FilterInPlace ¶
func FilterLegacy ¶
func FilterLegacy(slice, fn interface{}) interface{}
FilterLegacy a slice with fn
func FormatMsgAndArgs ¶
FormatMsgAndArgs format msg and args
func GetCaller ¶
func GetCaller() string
GetCaller returns the caller of the function that calls it.
func HandleCrash ¶
func HandleCrash(additionalHandlers ...func(interface{}))
HandleCrash simply catches a crash and logs an error. Meant to be called via defer. Additional context-specific handlers can be provided, and will be called in case of panic. HandleCrash actually crashes, after calling the handlers and logging the panic message.
E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully.
func HandleError ¶
func HandleError(err error)
HandlerError is a method to invoke when a non-user facing piece of code cannot return an error and needs to indicate it has been ignored. Invoking this method is preferable to logging the error - the default behavior is to log but the errors may be sent to a remote server for analysis.
func HumanReadableDuration ¶
HumanReadableDuration translates seconds into human-readable text
func IgnoreErr1 ¶
func Indent ¶
Indent inserts prefix at the beginning of each non-empty line of s. The end-of-line marker is NL.
func IndentBytes ¶
IndentBytes inserts prefix at the beginning of each non-empty line of b. The end-of-line marker is NL.
func Index ¶
Index return the location of a string in another long string, if it doesn't exist, returns -1 this function supports CJK characters
func MapInPlace ¶
func MapInPlace[T any](src []T, fn func(obj T) T)
func MarshalAndWriteFile ¶
func MergeMap ¶
func MergeMap[K comparable, V any](base map[K]V, overrides ...map[K]V) map[K]V
MergeMap merges multiple maps into one
func MergeStrIFaceMaps ¶
MergeStrIFaceMaps merge 2 map[string]any into one
func Must ¶
func Must(err error)
Must panics on non-nil errors. Useful to handling programmer level errors.
func PartialSwap ¶
func ReadFileAndUnmarshal ¶
func ReadFileInt ¶
func RecoverFromPanic ¶
func RecoverFromPanic(err *error)
RecoverFromPanic replaces the specified error with an error containing the original error, and the call tree when a panic occurs. This enables error handlers to handle errors and panics the same way.
func Round ¶
Round round half up For example:
Round(0.363636, 3) // 0.364 Round(0.363636, 2) // 0.36 Round(0.363636, 1) // 0.4 Round(32, 1) // 30
func SafeExec ¶
func SafeExec(cmd *exec.Cmd, timeout time.Duration, fn func(*exec.Cmd) error) (killed bool, err error)
SafeExec exec command safely with timeout
If the command ended within timeout duration, it returns with (false, run error)
If the command not been ended within timeout duration, it would be killed with SIGKILL recursively (both parent and children)
func SafeExecWithCombinedOutput ¶
func SafeExecWithCombinedOutput(cmd *exec.Cmd, timeout time.Duration) (output []byte, killed bool, err error)
SafeExecWithCombinedOutput safely run the command with cmd.CombinedOutput() and returns the output
It is the wrapper of SafeExec()
func UnsafeBytesToString ¶
UnsafeBytesToString returns the byte slice as a volatile string THIS IS EVIL CODE. YOU HAVE BEEN WARNED.
func UnsafeStringToBytes ¶
UnsafeStringToBytes returns the string as a byte slice THIS IS EVIL CODE. YOU HAVE BEEN WARNED.
func WildcardMatch ¶
WildcardMatch - finds whether the text matches/satisfies the pattern string. supports '*' and '?' wildcards in the pattern string. unlike path.Match(), considers a path as a flat name space while matching the pattern. The difference is illustrated in the example here https://play.golang.org/p/Ega9qgD4Qz .
func WildcardMatchSimple ¶
WildcardMatchSimple - finds whether the text matches/satisfies the pattern string. supports only '*' wildcard in the pattern. considers a file system path as a flat name space.
Types ¶
type Counter ¶
type Counter[T comparable] struct { // contains filtered or unexported fields }
func NewCounterFromSlice ¶
func NewCounterFromSlice[T comparable](list []T) Counter[T]
type RingBuffer ¶
type RingBuffer[T any] struct { // contains filtered or unexported fields }
func NewRingBuffer ¶
func NewRingBuffer[T any](length int) *RingBuffer[T]
func (*RingBuffer[T]) Peak ¶
func (rb *RingBuffer[T]) Peak() (res T, ok bool)
func (*RingBuffer[T]) PeakN ¶
func (rb *RingBuffer[T]) PeakN(n int) (res []T, ok bool)
func (*RingBuffer[T]) Pop ¶
func (rb *RingBuffer[T]) Pop() (res T, ok bool)
func (*RingBuffer[T]) PopN ¶
func (rb *RingBuffer[T]) PopN(n int) (res []T, ok bool)
func (*RingBuffer[T]) Size ¶
func (rb *RingBuffer[T]) Size() int
func (*RingBuffer[T]) Write ¶
func (rb *RingBuffer[T]) Write(data []T)
type SysStatus ¶
type SysStatus struct { Uptime string NumGoroutine int // General statistics. MemAllocated string // bytes allocated and still in use MemTotal string // bytes allocated (even if freed) MemSys string // bytes obtained from system (sum of XxxSys below) Lookups uint64 // number of pointer lookups MemMallocs uint64 // number of mallocs MemFrees uint64 // number of frees // Main allocation heap statistics. HeapAlloc string // bytes allocated and still in use HeapSys string // bytes obtained from system HeapIdle string // bytes in idle spans HeapInuse string // bytes in non-idle span HeapReleased string // bytes released to the OS HeapObjects uint64 // total number of allocated objects // Low-level fixed-size structure allocator statistics. // Inuse is bytes used now. // Sys is bytes obtained from system. StackInuse string // bootstrap stacks StackSys string MSpanInuse string // mspan structures MSpanSys string MCacheInuse string // mcache structures MCacheSys string BuckHashSys string // profiling bucket hash table GCSys string // GC metadata OtherSys string // other system allocations // Garbage collector statistics. NextGC string // next run in HeapAlloc time (bytes) LastGC string // last run in absolute time (ns) PauseTotalNs string PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256] NumGC uint32 }
SysStatus describes system runtime environment