Documentation
¶
Overview ¶
Package goutil provides safe goroutine utilities with built-in panic recovery.
Goroutines may panic due to programming errors such as nil pointer dereference or out-of-bounds access. Panics can be recovered without crashing the whole process. This package offers wrappers to run goroutines safely and recover from such panics.
A global `OnPanic` handler is triggered whenever a panic is recovered. It allows developers to log the panic, report metrics, or perform other custom recovery logic, making it easier to monitor and debug failures in concurrent code.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var OnPanic = func(ctx context.Context, r any, stack []byte) { fmt.Printf("[PANIC] %v\n%s\n", r, stack) }
OnPanic is a global callback function triggered 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 it during initialization to provide custom logging, metrics, or alerting.
Note: being global means it is shared across all usages. In testing scenarios, remember to restore it after modification if necessary.
Functions ¶
This section is empty.
Types ¶
type Status ¶
type Status struct {
// contains filtered or unexported fields
}
Status provides a handle to wait for a goroutine to finish.
func Go ¶
Go launches a goroutine that recovers from panics and invokes the global OnPanic handler when a panic occurs.
The provided context is passed to the goroutine function `f` and to OnPanic. The goroutine does not stop automatically when the context is cancelled; `f` should check `ctx.Done()` and return when appropriate.
type ValueStatus ¶
type ValueStatus[T any] struct { // contains filtered or unexported fields }
ValueStatus represents a goroutine that returns a value and an error. It allows the caller to wait for the result.
func GoValue ¶
GoValue launches a goroutine that executes the provided function `f`, recovers from any panic, and invokes the global OnPanic handler.
The context is passed to both `f` and OnPanic. The caller must ensure that `f` observes `ctx.Done()` if early cancellation is desired.
If a panic occurs, the recovered panic and stack trace are also reported via OnPanic and wrapped into the returned error.
func (*ValueStatus[T]) Wait ¶
func (s *ValueStatus[T]) Wait() (T, error)
Wait blocks until the goroutine completes and returns its value and error.