events/README.md
2025-09-17 07:55:38 +02:00

73 lines
2.7 KiB
Markdown

# Events
This events package in Go provides a simple and robust implementation for a publish-subscribe pattern (Pub/Sub). It enables you to create events that can contain generic data and distribute these events to registered listeners. The package is concurrently safe thanks to the internal use of mutex locks, making it ideal for multithreaded applications.
This package is perfect for decoupling components in your application. Instead of modules depending directly on each other, they can communicate via events. For example:
- A user module can publish a UserCreatedEvent.
- An email module can subscribe to this event to automatically send a welcome email without directly calling the user module.
## Core features
- Generic events: Create events with any data type (NewEvent[T]). The generic implementation ensures that events are strongly typed, improving code safety and readability.
- Secure data extraction: The Data method enables secure extraction of event data by passing a pointer. It automatically checks for type matching and ensures that the target pointer can be set to avoid common runtime errors.
- Simple subscription management: Subscribe to events using the Subscribe method. Each subscription returns an ISubscription instance that provides a simple Unsubscribe method. This makes it easy to cleanly remove event handlers.
- Concurrency-safe: The package is designed to be used safely in parallel environments. Internal locks (sync.Mutex) prevent race conditions when managing subscriptions and publishing events.
## Install
```bash
go get git.apihub24.de/admin/events
```
## Usage
```go
package main
import (
"fmt"
"git.apihub24.de/admin/events"
)
// create some Events
const (
NameEventType events.EventType = "name"
GreetEventType events.EventType = "greet"
)
// and Event Data
type (
NameEventData struct {
Name string
}
GreetEventData struct {
Greeting string
}
)
// use handler to subscribe and publish
func main() {
handler := events.NewEventHandler()
nameEvent := events.NewEvent(NameEventType, NameEventData{Name: "Tom"})
nameSubscription := handler.Subscribe(NameEventType, func(event events.IEvent) {
// read the Name Event Data
data, _ := events.ParseEventData[NameEventData](event)
// Publish the Greet Event
_ = handler.Publish(events.NewEvent(GreetEventType, GreetEventData{Greeting: fmt.Sprintf("Hello, %s", data.Name)}))
})
greetSubscription := handler.Subscribe(GreetEventType, func(event events.IEvent) {
data, _ := events.ParseEventData[GreetEventData](event)
println(fmt.Sprintf("%v", data))
})
// publish the Name Event
_ = handler.Publish(nameEvent)
// unsubscribe Events
nameSubscription.Unsubscribe()
greetSubscription.Unsubscribe()
}
```