Documentation
¶
Overview ¶
Package goutil provides utilities for running goroutines safely with built-in panic recovery.
In Go, a panic that occurs inside a goroutine will terminate the entire process if it is not recovered. This package wraps goroutine execution with a deferred recover handler to prevent such crashes.
When a panic is recovered, a global OnPanic callback is invoked, allowing applications to log the panic, emit metrics, or trigger alerts. This makes failures in concurrent code easier to observe and diagnose.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var OnPanic = func(ctx context.Context, info PanicInfo) { fmt.Printf("[PANIC] %v\n%s\n", info.Panic, info.Stack) }
OnPanic is a global callback invoked whenever a panic is recovered inside a goroutine launched by this package.
By default, it prints the panic value and stack trace to stdout. Applications may override this function during initialization to provide custom logging, metrics, or alerting behavior.
Functions ¶
This section is empty.
Types ¶
type Status ¶
type Status struct {
// contains filtered or unexported fields
}
Status represents the lifecycle of a goroutine launched by Go. It provides a synchronization point to wait for the goroutine to finish.
func Go ¶
Go launches a new goroutine to execute f with panic recovery enabled.
Any panic raised during execution of f is recovered, and the global OnPanic handler is invoked if it is not nil.
The provided context is passed to both f and OnPanic. Context cancellation is cooperative: the goroutine will NOT stop automatically when ctx is canceled. The function f must observe ctx.Done() and return explicitly.
If withoutCancel is true, f receives a context that is detached from cancellation of the parent context.
type ValueStatus ¶
type ValueStatus[T any] struct { // contains filtered or unexported fields }
ValueStatus represents the execution status of a goroutine that returns a value and an error.
func GoValue ¶
func GoValue[T any](ctx context.Context, f GoValueFunc[T], withoutCancel bool) *ValueStatus[T]
GoValue launches a new goroutine to execute f, capturing its returned value and error, with panic recovery enabled.
If f panics, the panic is recovered, reported via OnPanic, and converted into an error that is returned by Wait. In this case, the returned value is the zero value of T.
As with Go, context cancellation is cooperative: f must observe ctx.Done() if early termination is required.
If withoutCancel is true, f receives a context that is detached from cancellation of the parent context.
func (*ValueStatus[T]) Wait ¶
func (s *ValueStatus[T]) Wait() (T, error)
Wait blocks until the goroutine completes and returns the produced value and error.
If a panic occurred during execution, the returned error will describe the recovered panic.