3.7 KiB
Bell
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.
Installation
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"
Usage
Adding event listener
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)
Calling an event
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"}
})
Getting events list
To get a list of events to which handlers are subscribed, call the code:
bell.List()
Checking if exists listeners of event
You can check the existence of subscribers to an event like this:
bell.Has("event_name")
Removing listeners of event (all events)
You can delete all listeners or listeners of only one event.
Removing all listeners on all events
_ = bell.Remove()
Removing listeners of only the event "event_name"
_ = bell.Remove("event_name")
Wait until all events finish their work
bell.Wait()
Change events queue size (apply only for new listeners)
bell.Queue(42)
Usage without global state
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!")
Examples
See full example in example_test.go.