goutils

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2024 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const EmptyStr = ""

EmptyStr is the empty string const

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

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

View Source
var PanicHandlers = []func(interface{}){logPanic}

PanicHandlers is a list of functions which will be invoked when a panic happens.

View Source
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 DefaultStringIfEmpty(s, dv string) string

Deprecated: DefaultStringIfEmpty returns a default string if s is empty Use cmp.Or instead

func Download

func Download(url string, dest string) (err error)

Download is used to conveniently download a file to the certain path

func FileSize

func FileSize[T constraints.Integer](s T) string

FileSize translate bytes number into human-readable size

func Filter

func Filter[T any](slice []T, fn func(T) bool) []T

Filter a slice with fn

func FilterInPlace

func FilterInPlace[T any](slice *[]T, fn func(T) bool)

func FilterLegacy

func FilterLegacy(slice, fn interface{}) interface{}

FilterLegacy a slice with fn

func FormatMsgAndArgs

func FormatMsgAndArgs(msgAndArgs ...any) string

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

func HumanReadableDuration(diffSeconds int64) string

HumanReadableDuration translates seconds into human-readable text

func IgnoreErr

func IgnoreErr[R any](fn func() (R, error)) func() R

func IgnoreErr1

func IgnoreErr1[P any, R any](fn func(P) (R, error)) func(P) R

func IgnoreErr2

func IgnoreErr2[P1 any, P2 any, R any](fn func(P1, P2) (R, error)) func(P1, P2) R

func Indent

func Indent(s, prefix string) string

Indent inserts prefix at the beginning of each non-empty line of s. The end-of-line marker is NL.

func IndentBytes

func IndentBytes(b, prefix []byte) []byte

IndentBytes inserts prefix at the beginning of each non-empty line of b. The end-of-line marker is NL.

func Index

func Index(s, substr string) int

Index return the location of a string in another long string, if it doesn't exist, returns -1 this function supports CJK characters

func IsDir

func IsDir(path string) bool

IsDir tells a path is a directory or not

func IsExist

func IsExist(path string) bool

IsExist is used to determine whether a path exists or not

func IsFile

func IsFile(path string) bool

IsFile tells a path is a file or not

func IsIPv4

func IsIPv4(s string) bool

IsIPv4 tells a string matches IPv4 form or not

func LeftPad

func LeftPad(s string, padStr string, length int) string

LeftPad pad a string with specified character to the left side

func ListAllEnvs

func ListAllEnvs() map[string]string

ListAllEnvs list all envs in map type

func MakeRange

func MakeRange(min, max int) []int

MakeRange returns a slice starts from min and ends with max

func Map

func Map[From any, To any](src []From, fn func(obj From) To) []To

func MapInPlace

func MapInPlace[T any](src []T, fn func(obj T) T)

func MarshalAndWriteFile

func MarshalAndWriteFile(v any, file string) error

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

func MergeStrIFaceMaps(to, from map[string]any) map[string]any

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 PartialSwap[P1 any, P2 any, R any](fn func(P1, P2) R) func(P2, P1) R

func ReadFileAndUnmarshal

func ReadFileAndUnmarshal(file string, v any) error

func ReadFileInt

func ReadFileInt(file string) (val int, err error)

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 Reduce

func Reduce[T any, R any](slice []T, fn func(T, R) R, zeroValue R) R

Reduce a alice with

func RightPad

func RightPad(s string, padStr string, length int) string

RightPad pad a string with specified character to the right side

func Round

func Round(val float64, precision int) float64

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 Trim

func Trim(str string) string

Trim cuts the blanks of a string, the beginning and the end

func TrimLeft

func TrimLeft(str string) string

TrimLeft cuts the left side blanks of a string

func TrimRight

func TrimRight(str string) string

TrimRight cuts the right side blanks of a string

func UUID

func UUID() string

UUID returns a random generated UUID string

func UnsafeBytesToString

func UnsafeBytesToString(b []byte) string

UnsafeBytesToString returns the byte slice as a volatile string THIS IS EVIL CODE. YOU HAVE BEEN WARNED.

func UnsafeStringToBytes

func UnsafeStringToBytes(s string) (b []byte)

UnsafeStringToBytes returns the string as a byte slice THIS IS EVIL CODE. YOU HAVE BEEN WARNED.

func WildcardMatch

func WildcardMatch(pattern, name string) (matched bool)

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

func WildcardMatchSimple(pattern, name string) bool

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.

func ZeroFill

func ZeroFill(s string, length int) string

ZeroFill pad a string(usually a number string) with "0" to the left

Types

type Counter

type Counter[T comparable] struct {
	// contains filtered or unexported fields
}

func NewCounterFromSlice

func NewCounterFromSlice[T comparable](list []T) Counter[T]

func (Counter[T]) Add

func (c Counter[T]) Add(ele T, n int)

func (Counter[T]) Count

func (c Counter[T]) Count() map[T]int

func (Counter[T]) Inc

func (c Counter[T]) Inc(ele T)

func (Counter[T]) Update

func (c Counter[T]) Update(list []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

func GetSysStatus

func GetSysStatus() *SysStatus

GetSysStatus returns runtime information

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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