Mirror of github.com/gissleh/irc
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.2 KiB

7 years ago
  1. package irc
  2. import (
  3. "sync"
  4. )
  5. // A Handler is a function that is part of the irc event loop. It will receive all
  6. // events that haven't been killed up to that point.
  7. type Handler func(event *Event, client *Client)
  8. var eventHandler struct {
  9. mutex sync.RWMutex
  10. handlers []Handler
  11. }
  12. func emit(event *Event, client *Client) {
  13. eventHandler.mutex.RLock()
  14. for _, handler := range eventHandler.handlers {
  15. handler(event, client)
  16. }
  17. eventHandler.mutex.RUnlock()
  18. }
  19. // Handle adds a new handler to the irc handling. It returns a pointer that can be passed to RemoveHandler
  20. // later on to unsubscribe.
  21. func Handle(handler Handler) *Handler {
  22. eventHandler.mutex.Lock()
  23. defer eventHandler.mutex.Unlock()
  24. eventHandler.handlers = append(eventHandler.handlers, handler)
  25. return &eventHandler.handlers[len(eventHandler.handlers)-1]
  26. }
  27. // RemoveHandler unregisters a handler.
  28. func RemoveHandler(handlerPtr *Handler) (ok bool) {
  29. eventHandler.mutex.Lock()
  30. defer eventHandler.mutex.Unlock()
  31. for i := range eventHandler.handlers {
  32. if &eventHandler.handlers[i] == handlerPtr {
  33. eventHandler.handlers = append(eventHandler.handlers[:i], eventHandler.handlers[i+1:]...)
  34. return true
  35. }
  36. }
  37. return false
  38. }
  39. func init() {
  40. eventHandler.handlers = make([]Handler, 0, 8)
  41. }