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.

54 lines
1.3 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. if event.killed {
  17. break
  18. }
  19. }
  20. eventHandler.mutex.RUnlock()
  21. }
  22. // Handle adds a new handler to the irc handling. It returns a pointer that can be passed to RemoveHandler
  23. // later on to unsubscribe.
  24. func Handle(handler Handler) *Handler {
  25. eventHandler.mutex.Lock()
  26. defer eventHandler.mutex.Unlock()
  27. eventHandler.handlers = append(eventHandler.handlers, handler)
  28. return &eventHandler.handlers[len(eventHandler.handlers)-1]
  29. }
  30. // RemoveHandler unregisters a handler.
  31. func RemoveHandler(handlerPtr *Handler) (ok bool) {
  32. eventHandler.mutex.Lock()
  33. defer eventHandler.mutex.Unlock()
  34. for i := range eventHandler.handlers {
  35. if &eventHandler.handlers[i] == handlerPtr {
  36. eventHandler.handlers = append(eventHandler.handlers[:i], eventHandler.handlers[i+1:]...)
  37. return true
  38. }
  39. }
  40. return false
  41. }
  42. func init() {
  43. eventHandler.handlers = make([]Handler, 0, 8)
  44. }