An event handling library in Go
go get github.com/hetacode/go-eh
type UserEvent struct {
*goeh.EventData
FirstName string `json:"first_name"`
}
func (e *UserEvent) GetType() string {
return "UserEvent"
}
This event should be register in the EventsMapper:
eventsMapper := new(goeh.EventsMapper)
eventsMapper.Register(new(UserEvent))
Now, we can resolve event instance by json string:
json := `{
"id": "1",
"type": "UserEvent",
"first_name": "John"
}`
event, err := eventsMapper.Resolve(json)
if err != nil {
t.Fatal(err)
}
trueEvent := event.(*UserEvent)
// trueEvent.FirstName == "John"
Event handler struct should implement an EventHandler interface with Handle
function.
type UserEventHandler struct {
}
// Execute message
func (e *UserEventHandler) Handle(event goeh.Event) {
e := event.(*UserEvent)
/// some magic tricks here, processing and more...
}
EventHandler and his Event should be register in EventsHandlerManager:
manager := goeh.NewEventsHandlerManager()
if err := manager.Register(new(UserEvent), new(UserEventHandler); err != nil {
t.Fatal(err)
}
In order to Execute appropriate Event, just call Execute function in EventsHandlerManager:
if err := manager.Execute(event); err != nil {
t.Fatal(err)
}
And the same with EventsMapper together:
json := `{
"id": "1",
"type": "UserEvent",
"first_name": "John"
}`
event, err := eventsMapper.Resolve(json)
if err != nil {
t.Fatal(err)
}
if err := manager.Execute(event); err != nil {
t.Fatal(err)
}
That's all!