Bell is the simplest event system written in Go (Golang) which is based on the execution of handlers independent of the main channel.
- Written in pure go. Has no third-party libraries.
- Support for custom event data.
- Internally, it launches each handler in a separate goroutine and passes messages to them through channels, the handlers are executed independently of the main thread.
- Support for adding multiple handlers to an event.
- Complete unit testing.
Bull does not contain logic for automatic restarts in case of a crash and does not have a persistent execution state store.
To install Bell package, you need install Go with modules support and set Go workspace first.
- Use the below Go command to install Bell:
go get -u github.com/nuttech/bell/v2
- Import package in your code:
import "github.com/nuttech/bell/v2"
The handler function accepts the Message type as input
bell.Listen("event_name", func(message bell.Message) { // here you must write your handler code })
bell.Message has interface{} type and can consist any data.
You can add more handlers one event:
bell.Listen("event_name", func(message bell.Message) { // first handler }) bell.Listen("event_name", func(message bell.Message) { // second handler })
You can add a handler with multiple copies for parallel event processing.
bell.ListenN("event_name", func(msg bell.Message) { fmt.Println(msg) }, 42)
This code call event. Activating handlers, who subscribed on "event_name" event
bell.Ring("event_name", "some data") bell.Ring("event_name", 1) // int bell.Ring("event_name", false) // bool
If you passing struct type of data:
type userStruct struct { Name string } bell.Ring("event_name", userStruct{Name: "Jon"})
Then parsing the data in the handler may look like this:
bell.Listen("event_name", func(message bell.Message) { user := message.(userStruct) fmt.Printf("%#v\n", userStruct{Name: "Jon"}) // main.userStruct{Name:"Jon"} })
To get a list of events to which handlers are subscribed, call the code:
bell.List()
You can check the existence of subscribers to an event like this:
bell.Has("event_name")
You can delete all listeners or listeners of only one event.
_ = bell.Remove()
_ = bell.Remove("event_name")
bell.Wait()
bell.Queue(42)
You can also use the bell package without using global state. To do this, you need to create a state storage object and use it.
events := bell.New() events.Listen("event", func(message bell.Message) {}) _ = events.Ring("event", "Hello bell!")
See full example in example_test.go.