Skip to content

Instantly share code, notes, and snippets.

@percybolmer
Last active September 10, 2022 06:47
Show Gist options
  • Save percybolmer/eda5050e183af299d717d9210f08fe4e to your computer and use it in GitHub Desktop.
Save percybolmer/eda5050e183af299d717d9210f08fe4e to your computer and use it in GitHub Desktop.
...
var (
ErrEventNotSupported = errors.New("this event type is not supported")
)
// Manager is used to hold references to all Clients Registered, and Broadcasting etc
type Manager struct {
clients ClientList
// Using a syncMutex here to be able to lcok state before editing clients
// Could also use Channels to block
sync.RWMutex
// handlers are functions that are used to handle Events
handlers map[string]EventHandler
}
// NewManager is used to initalize all the values inside the manager
func NewManager() *Manager {
m := &Manager{
clients: make(ClientList),
handlers: make(map[string]EventHandler),
}
m.setupEventHandlers()
return m
}
// setupEventHandlers configures and adds all handlers
func (m *Manager) setupEventHandlers() {
m.handlers[EventSendMessage] = func(e Event, c *Client) error {
fmt.Println(e)
return nil
}
}
// routeEvent is used to make sure the correct event goes into the correct handler
func (m *Manager) routeEvent(event Event, c *Client) error {
// Check if Handler is present in Map
if handler, ok := m.handlers[event.Type]; ok {
// Execute the handler and return any err
if err := handler(event, c); err != nil {
return err
}
return nil
} else {
return ErrEventNotSupported
}
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment