cpubsub package (from gocopper/pkg) allows your packages to publish events without knowing who consumes them. Two backends are included: an in-process local backend, and a Redis backend for when multiple processes need to hear about events. To get started, install the package:
The PubSub Interface
Both backends implement the same small interface:Publishing Events
You should define topics as package constants so that subscribers may import them:OnCommit callback so that the event is only sent once the transaction commits. To learn more, see Transactions.
Subscribing to Topics
It is most common to subscribe in a constructor so that the subscription is in place when the app starts:Payloads Across Backends
The local backend hands your handler the exact Go value you published. The Redis backend, however, serializes payloads as JSON, so handlers receive the decoded form (amap[string]any for structs). If a handler needs the typed struct, you may convert it by marshaling and unmarshaling again: