events

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package events provides an in-process event dispatcher modelled on Laravel's Event facade.

Events are arbitrary values (typically structs). Listeners are functions that receive the dispatched event and an error. Dispatch is synchronous — listeners run in registration order on the calling goroutine. Background fan-out is left to the caller (spawn a goroutine inside a listener, or use a queue package).

Type-safe registration uses Go generics so listeners don't need to type-assert:

type UserRegistered struct{ ID uint64; Email string }

d := events.New()
events.Listen(d, func(ctx context.Context, e UserRegistered) error {
    return sendWelcomeEmail(ctx, e.Email)
})
_ = d.Dispatch(ctx, UserRegistered{ID: 42, Email: "a@b.co"})

If a listener returns an error, the dispatcher records it and (by default) continues with the remaining listeners. Use StopOnError(true) to short-circuit instead. Errors are joined with errors.Join so callers can inspect each one.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Forget

func Forget[E any](d *Dispatcher) bool

Forget removes every listener registered for events of type E. The returned bool is true if anything was removed.

func HasListeners

func HasListeners[E any](d *Dispatcher) bool

HasListeners reports whether at least one listener is registered for events of type E. Handy for unit tests and conditional dispatch.

func Listen

func Listen[E any](d *Dispatcher, fn func(ctx context.Context, e E) error)

Listen registers fn as a listener for events of type E. Listeners run in registration order.

Types

type Dispatcher

type Dispatcher struct {
	// contains filtered or unexported fields
}

Dispatcher routes events to registered listeners.

func New

func New() *Dispatcher

New returns a fresh Dispatcher.

func (*Dispatcher) Dispatch

func (d *Dispatcher) Dispatch(ctx context.Context, event any) error

Dispatch fans the event out to its listeners. Returns the joined errors from listeners (or nil).

func (*Dispatcher) StopOnError

func (d *Dispatcher) StopOnError(v bool) *Dispatcher

StopOnError toggles short-circuit behaviour. Default false: every listener runs, errors are joined and returned together.

Jump to

Keyboard shortcuts

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