const TopicAll
TopicAll defines a topic for all types of message. This topic can be used to subscribe to message for all topics.
Package message provides a simple message broker implementation.
Package message provides a simple message broker implementation.
The message broker is a Pub/Sub one. It implements two different interfaces, `Publisher` and `Subscriber`, which are also defined within this package.
Published messages contain the topic where they are published and optional message data.
Subscribe to an event:
1broker := message.NewBroker()
2subID, err := broker.Subscribe("EventName", func(msg message.Message) {
3 println("EventName has been triggered")
4 println(msg.Data)
5})
6if err != nil {
7 panic(err)
8}
Unsubscribe from an event:
1unsubscribed, err := broker.Unsubscribe("EventName", subID)
2if err != nil {
3 panic(err)
4}
5
6if !unsubscribed {
7 panic("subscription not found")
8}
Publish an event:
1var (
2 // ErrInvalidTopic is triggered when an invalid topic is used.
3 ErrInvalidTopic = errors.New("invalid topic")
4
5 // ErrRequiredCallback is triggered when subscribing without a callback.
6 ErrRequiredCallback = errors.New("message callback is required")
7
8 // ErrRequiredSubscriptionID is triggered when unsubscribing without an ID.
9 ErrRequiredSubscriptionID = errors.New("message sibscription ID is required")
10
11 // ErrRequiredTopic is triggered when (un)subscribing without a topic.
12 ErrRequiredTopic = errors.New("message topic is required")
13)Broker is a message broker that handles subscriptions and message publishing.
Publish publishes a message for a topic.
Subscribe subscribes to messages published for a topic. It returns the callback ID within the topic.
Topics returns the list of current subscription topics.
Unsubscribe unsubscribes a callback from a message topic. ID is the callback ID within the topic, returned on subscription.
Callback defines a type for message callbacks.
Message defines a type for published messages.
Publisher defines an interface for message publishers.
1type Subscriber interface {
2 // Subscribe subscribes to messages published for a topic.
3 // It returns the callback ID within the topic.
4 Subscribe(Topic, Callback) (id int, _ error)
5
6 // Unsubscribe unsubscribes a callback from a message topic.
7 // ID is the callback ID within the topic, returned on subscription.
8 Unsubscribe(_ Topic, id int) (unsubscribed bool, _ error)
9}Subscriber defines an interface for message subscribers.
Topic defines a type for message topics.