Skip to content

Instantly share code, notes, and snippets.

@AustinHunt
Created August 30, 2023 15:28
Show Gist options
  • Save AustinHunt/37db00cb0b1a3fd01932ce450becd0d1 to your computer and use it in GitHub Desktop.
Save AustinHunt/37db00cb0b1a3fd01932ce450becd0d1 to your computer and use it in GitHub Desktop.
A simple pubsub in golang
package pubsub
import (
"sync"
)
// PubSub - a simple publish-subscribe structure
type PubSub[T any] struct {
mu sync.RWMutex
subscribers map[string][]chan T
}
// NewPubSub - creates a new PubSub
func NewPubSub[T any]() *PubSub[T] {
return &PubSub[T]{
subscribers: make(map[string][]chan T),
}
}
// Subscribe - subscribes to a topic
func (ps *PubSub[T]) Subscribe(topic string) <-chan T {
ps.mu.Lock()
defer ps.mu.Unlock()
ch := make(chan T)
ps.subscribers[topic] = append(ps.subscribers[topic], ch)
return ch
}
// Publish - publishes a message to a topic
func (ps *PubSub[T]) Publish(topic string, msg T) {
ps.mu.RLock()
defer ps.mu.RUnlock()
for _, ch := range ps.subscribers[topic] {
ch <- msg
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment