/genericpubsub

A lightweight, type-safe publish/subscribe system for Go, using generics and context-based cancellation

Primary LanguageGoMIT LicenseMIT

genericpubsub

Go Tests Go Reference GitHub tag License: MIT Go Version

genericpubsub is a lightweight, type-safe publish/subscribe system for Go, using generics and context-based cancellation. It allows you to publish messages of any type to multiple subscribers concurrently, with clean shutdown and resource management.

Features

  • Type-safe using Go generics
  • Simple API: Send, Subscribe
  • Context-based cancellation
  • Graceful shutdown of subscribers
  • Fully tested with unit tests

Installation

go get github.com/sesopenko/genericpubsub

Documentation

https://pkg.go.dev/github.com/sesopenko/genericpubsub

Example

package main

import (
    "context"
    "fmt"
	"time"
    "github.com/sesopenko/genericpubsub"
)

type Message struct {
    Value string
}

func main() {
    channelBuffer := 64
    ps := genericpubsub.New[Message](context.Background(), channelBuffer)
    sub := ps.Subscribe(context.TODO(), channelBuffer)
    
    go ps.Send(Message{Value: "hello"})
    time.Sleep(50 * time.Millisecond)
    msg, ok := <-sub
    fmt.Println("Received:", msg.Value)
    fmt.Printf("channel wasn't closed: %t\n", ok)
}

License

This project is licensed under the MIT license. See LICENSE.txt for details.

© 2025 Sean Esopenko