Skip to content

Instantly share code, notes, and snippets.

View glober-vaibhav's full-sized avatar

Vaibhav Chichmalkar glober-vaibhav

  • Globant
  • Pune
  • 20:03 (UTC +05:30)
View GitHub Profile
func main() {
// Create a new agent
agent := NewAgent()
// Subscribe to a topic
sub := agent.Subscribe("foo")
// Publish a message to the topic
go agent.Publish("foo", "hello world")
// Close closes the agent
func (b *Agent) Close() {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return
}
b.closed = true
// Subscribe subscribes to a topic
func (b *Agent) Subscribe(topic string) <-chan string {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return nil
}
ch := make(chan string)
// Publish publishes a message to a topic
func (b *Agent) Publish(topic string, msg string) {
b.mu.Lock()
defer b.mu.Unlock()
if b.closed {
return
}
for _, ch := range b.subs[topic] {
func NewAgent() *Agent {
return &Agent{
subs: make(map[string][]chan string),
quit: make(chan struct{}),
}
}
// Agent is a simple pub/sub agent
type Agent struct {
mu sync.Mutex
subs map[string][]chan string
quit chan struct{}
closed bool
}