How do I implement pub/sub messaging in Go?

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.

Keywords: Go, pub/sub messaging, messaging pattern, channels, concurrency, NATS, Gorilla WebSocket
Description: This tutorial demonstrates how to implement pub/sub messaging in Go using channels. Explore the pub/sub messaging pattern to enable communication between different parts of your application efficiently.

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")
}
    

Keywords: Go pub/sub messaging messaging pattern channels concurrency NATS Gorilla WebSocket