How to Build a Notification Service in Go

Web
Build a Go notification service using a buffered channel and a worker goroutine to handle messages asynchronously.

Build a notification service in Go by creating a channel-based producer-consumer pattern with a dedicated worker goroutine.

package main

import (
	"fmt"
	"time"
)

type Notification struct {
	ID    int
	Msg   string
}

func main() {
	notifications := make(chan Notification, 10)

	go func() {
		for i := 1; i <= 5; i++ {
			notifications <- Notification{ID: i, Msg: fmt.Sprintf("Alert %d", i)}
			time.Sleep(1 * time.Second)
		}
		close(notifications)
	}()

	for n := range notifications {
		fmt.Printf("Sent: %s (ID: %d)\n", n.Msg, n.ID)
	}
}