49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
package bus
|
|
|
|
import "sync"
|
|
|
|
// Subscriber represents a named handler for an event.
|
|
type Subscriber struct {
|
|
Name string
|
|
Handler func(any)
|
|
}
|
|
|
|
// CustomEventBus is a simple in-memory event bus using Go primitives.
|
|
type CustomEventBus struct {
|
|
mu sync.RWMutex
|
|
subscribers map[string][]Subscriber
|
|
}
|
|
|
|
func NewCustomEventBus() *CustomEventBus {
|
|
return &CustomEventBus{
|
|
subscribers: make(map[string][]Subscriber),
|
|
}
|
|
}
|
|
|
|
func (eb *CustomEventBus) Subscribe(event string, name string, handler func(any)) {
|
|
eb.mu.Lock()
|
|
defer eb.mu.Unlock()
|
|
eb.subscribers[event] = append(eb.subscribers[event], Subscriber{Name: name, Handler: handler})
|
|
}
|
|
|
|
func (eb *CustomEventBus) Publish(event string, data any) {
|
|
eb.mu.RLock()
|
|
subs := eb.subscribers[event]
|
|
eb.mu.RUnlock()
|
|
for _, sub := range subs {
|
|
go sub.Handler(data) // Run handlers asynchronously
|
|
}
|
|
}
|
|
|
|
func (eb *CustomEventBus) GetSubscribers() map[string][]string {
|
|
eb.mu.RLock()
|
|
defer eb.mu.RUnlock()
|
|
result := make(map[string][]string)
|
|
for event, subs := range eb.subscribers {
|
|
for _, sub := range subs {
|
|
result[event] = append(result[event], sub.Name)
|
|
}
|
|
}
|
|
return result
|
|
}
|