Implementing pub/sub messaging in Go can be achieved using built-in channels, but for more robust solutions, you can consider using libraries or packages such as Gorilla WebSocket or NATS. Below is a simple example using Go channels to demonstrate how pub/sub messaging works.
package main
import (
"fmt"
"sync"
)
type Publisher struct {
subscribers []chan string
mu sync.Mutex
}
func (p *Publisher) Subscribe() chan string {
ch := make(chan string)
p.mu.Lock()
p.subscribers = append(p.subscribers, ch)
p.mu.Unlock()
return ch
}
func (p *Publisher) Publish(message string) {
p.mu.Lock()
defer p.mu.Unlock()
for _, ch := range p.subscribers {
ch <- message
}
}
func main() {
pub := &Publisher{}
// Subscribe two subscribers
sub1 := pub.Subscribe()
sub2 := pub.Subscribe()
go func() {
for msg := range sub1 {
fmt.Println("Subscriber 1 received:", msg)
}
}()
go func() {
for msg := range sub2 {
fmt.Println("Subscriber 2 received:", msg)
}
}()
// Publish messages
pub.Publish("Hello Subscribers!")
pub.Publish("Another message")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?