This repository contains an implementation of an EventBus in Go. An EventBus is a design pattern that offers a simple communication system between components in an application.
- Supports multiple subscribers: Multiple components can subscribe to the same event.
- Asynchronous event delivery: Events are delivered to subscribers asynchronously.
To use EventBus in your Go project, you can install it using go get:
go get github.com/ksysoev/sebus
First, create a new EventBus:
import (
"github.com/ksysoev/sebus"
)
eb := sebus.NewEventBus()
To publish an event, your event classes should satisfy the interface sebus.Event
:
event := YourEvent{...}
err := eb.Publish(event)
To subscribe to events:
sub, err := eb.Subscribe("topic", 5)
To unsubscribe:
err := eb.Unsubscribe(sub)
package main
import (
"fmt"
"log"
"github.com/ksysoev/sebus"
)
type MyEvent struct {
topic string
data string
}
func (e MyEvent) Topic() string {
return e.topic
}
func (e MyEvent) Data() any {
return e.data
}
func main() {
eb := sebus.NewEventBus()
sub, err := eb.Subscribe("my_topic", 0)
if err != nil {
log.Fatalf("Failed to subscribe: %v", err)
}
event := MyEvent{
topic: "my_topic",
data: "Hello, world!",
}
err = eb.Publish(event)
if err != nil {
log.Fatalf("Failed to publish event: %v", err)
}
msg, ok := <-sub.Stream()
if ok {
fmt.Printf("Received message: %v", msg)
} else {
log.Fatalf("Subscription closed with error: %v", sub.Err())
}
eb.Close()
}
This project is licensed under the MIT License - see the LICENSE file for details.