topic.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package server
  2. import (
  3. "log"
  4. "math/rand"
  5. "sync"
  6. )
  7. // topic represents a channel to which subscribers can subscribe, and publishers
  8. // can publish a message
  9. type topic struct {
  10. ID string
  11. subscribers map[int]subscriber
  12. mu sync.Mutex
  13. }
  14. // subscriber is a function that is called for every new message on a topic
  15. type subscriber func(msg *message) error
  16. // newTopic creates a new topic
  17. func newTopic(id string) *topic {
  18. return &topic{
  19. ID: id,
  20. subscribers: make(map[int]subscriber),
  21. }
  22. }
  23. // Subscribe subscribes to this topic
  24. func (t *topic) Subscribe(s subscriber) int {
  25. t.mu.Lock()
  26. defer t.mu.Unlock()
  27. subscriberID := rand.Int()
  28. t.subscribers[subscriberID] = s
  29. return subscriberID
  30. }
  31. // Unsubscribe removes the subscription from the list of subscribers
  32. func (t *topic) Unsubscribe(id int) {
  33. t.mu.Lock()
  34. defer t.mu.Unlock()
  35. delete(t.subscribers, id)
  36. }
  37. // Publish asynchronously publishes to all subscribers
  38. func (t *topic) Publish(m *message) error {
  39. go func() {
  40. t.mu.Lock()
  41. defer t.mu.Unlock()
  42. for _, s := range t.subscribers {
  43. if err := s(m); err != nil {
  44. log.Printf("error publishing message to subscriber")
  45. }
  46. }
  47. }()
  48. return nil
  49. }
  50. // Subscribers returns the number of subscribers to this topic
  51. func (t *topic) Subscribers() int {
  52. t.mu.Lock()
  53. defer t.mu.Unlock()
  54. return len(t.subscribers)
  55. }