82 lines
1.6 KiB
Go
82 lines
1.6 KiB
Go
package events
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
// NewEventHandler creates a new event handler
|
|
func NewEventHandler() *EventHandler {
|
|
return &EventHandler{
|
|
events: make(map[string]EventFunction),
|
|
}
|
|
}
|
|
|
|
// Register registers an event function
|
|
func (h *EventHandler) Register(eventName string, fn EventFunction) error {
|
|
if fn == nil {
|
|
return fmt.Errorf("event function cannot be nil")
|
|
}
|
|
|
|
h.mutex.Lock()
|
|
defer h.mutex.Unlock()
|
|
|
|
h.events[eventName] = fn
|
|
return nil
|
|
}
|
|
|
|
// Unregister removes an event function
|
|
func (h *EventHandler) Unregister(eventName string) {
|
|
h.mutex.Lock()
|
|
defer h.mutex.Unlock()
|
|
|
|
delete(h.events, eventName)
|
|
}
|
|
|
|
// Execute executes an event function
|
|
func (h *EventHandler) Execute(ctx *EventContext) error {
|
|
if ctx == nil {
|
|
return fmt.Errorf("context cannot be nil")
|
|
}
|
|
|
|
h.mutex.RLock()
|
|
fn, exists := h.events[ctx.EventName]
|
|
h.mutex.RUnlock()
|
|
|
|
if !exists {
|
|
return fmt.Errorf("event %s not found", ctx.EventName)
|
|
}
|
|
|
|
// Set up context with timeout if needed
|
|
if ctx.Context == nil {
|
|
timeout, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
ctx.Context = timeout
|
|
}
|
|
|
|
// Execute the function
|
|
return fn(ctx)
|
|
}
|
|
|
|
// HasEvent checks if an event is registered
|
|
func (h *EventHandler) HasEvent(eventName string) bool {
|
|
h.mutex.RLock()
|
|
defer h.mutex.RUnlock()
|
|
|
|
_, exists := h.events[eventName]
|
|
return exists
|
|
}
|
|
|
|
// ListEvents returns all registered event names
|
|
func (h *EventHandler) ListEvents() []string {
|
|
h.mutex.RLock()
|
|
defer h.mutex.RUnlock()
|
|
|
|
events := make([]string, 0, len(h.events))
|
|
for name := range h.events {
|
|
events = append(events, name)
|
|
}
|
|
|
|
return events
|
|
} |