This is a simple implementation of an event bus in golang. Actually support:
- publish/subscribe messaging.
To start use eventbus in your project, you can run the following command.
go get github.com/stanipetrosyan/go-eventbus
And import
import (
goeventbus "github.com/stanipetrosyan/go-eventbus"
)
Simple example of publish/subscribe pattern.
var eventbus = goeventbus.NewEventBus()
address := "topic"
options := goeventbus.NewMessageOptions().AddHeader("header", "value")
message := goeventbus.CreateMessage().SetBody("Hi Topic").SetOptions(options)
eventbus.Channel(address).Subscriber().Listen(func(dc goeventbus.Context) {
fmt.Printf("Message %s\n", dc.Result().Data)
})
eventbus.Channel(address).Publisher().Publish(message)
For publishing, you need to create a Message object using this method.
message := goeventbus.CreateMessage().SetBody("Hi Topic")
Each message can have some options:
options := goeventbus.NewMessageOptions().AddHeader("header", "value")
message := goeventbus.CreateMessage()
message.SetOptions(options)
eventBus.Channel("address").Publisher().Publish(message)
A processor works like a middleware, in fact forwards messages only if the predicate is satisfied. The method accepts a function with message and return must return a boolean.
eventbus.Channel("topic1").Processor(func(message goeventbus.Message) bool {
return message.Options.Headers().Contains("header")
})
A Network bus create a tcp connection between different services.
NetworkBus is a wrapper of local eventbus.
A simple server/client example is in examples/networkbus
directory.