Created
August 30, 2023 15:28
-
-
Save AustinHunt/37db00cb0b1a3fd01932ce450becd0d1 to your computer and use it in GitHub Desktop.
A simple pubsub in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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