This file contains hidden or 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
// Agent is a simple pub/sub agent | |
type Agent struct { | |
mu sync.Mutex | |
subs map[string][]chan string | |
quit chan struct{} | |
closed bool | |
} |
This file contains hidden or 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
func NewAgent() *Agent { | |
return &Agent{ | |
subs: make(map[string][]chan string), | |
quit: make(chan struct{}), | |
} | |
} |
This file contains hidden or 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
// 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] { |
This file contains hidden or 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
// 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) |
This file contains hidden or 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
// Close closes the agent | |
func (b *Agent) Close() { | |
b.mu.Lock() | |
defer b.mu.Unlock() | |
if b.closed { | |
return | |
} | |
b.closed = true |
This file contains hidden or 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
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") |