A lightweight, thread-safe event management system for Go applications that implements the publish-subscribe pattern.
- Thread-safe event management
- Singleton pattern implementation
- Support for multiple channels
- User and tenant-based subscription system
- Buffered channels for event delivery
- Automatic cleanup of empty channels
go get github.com/0xataru/go_eventmanager
package main
import (
"fmt"
"github.com/0xataru/go_eventmanager"
)
func main() {
// Get the event manager instance
em := event_manager.NewEventManager()
// Subscribe to a channel
ch := em.Subscribe("my-channel", 1, "tenant-1")
// Start listening for events
go func() {
for event := range ch {
fmt.Printf("Received event: %s with data: %v\n", event.Event, event.Data)
}
}()
// Send an event
em.SendEvent("my-channel", "user-login", map[string]string{
"username": "john_doe",
})
// Unsubscribe when done
em.Unsubscribe("my-channel", ch)
}
The main struct that manages all event subscriptions and deliveries.
type EventManager struct {
subscribers map[string][]SubscriberInfo
mutex sync.RWMutex
}
NewEventManager() *EventManager
- Creates a new event manager instance (singleton)Subscribe(channel string, userID int, tenantID string) chan EventData
- Subscribes to a channelUnsubscribe(channel string, ch chan EventData)
- Unsubscribes from a channelSendEvent(channel, event string, data any)
- Sends an event to all subscribers of a channel
type EventData struct {
Event string `json:"event"`
Data any `json:"data"`
}
- Always unsubscribe when you're done with a channel to prevent memory leaks
- Use buffered channels (default size is 1000) to handle high-frequency events
- Consider implementing error handling for your event processing logic
- Use meaningful channel names that reflect your application's domain
The EventManager is fully thread-safe and can be used in concurrent applications. It uses a read-write mutex to protect the subscribers map and ensure safe concurrent access.
This project is dual-licensed under both the MIT License and Apache License 2.0.