From 10b84dc8ee1992d1d38e938ca62970ad2dadf12d Mon Sep 17 00:00:00 2001 From: NatureFreshMilk Date: Fri, 25 Jan 2019 16:06:24 +0100 Subject: [PATCH] event bus --- server/eventbus/eventbus.go | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 server/eventbus/eventbus.go diff --git a/server/eventbus/eventbus.go b/server/eventbus/eventbus.go new file mode 100644 index 0000000..478d3ad --- /dev/null +++ b/server/eventbus/eventbus.go @@ -0,0 +1,38 @@ +package eventbus + +import ( + "sync" +) + +type Listener interface { + OnEvent(eventtype string, o interface{}) +} + +type Eventbus struct { + mutex *sync.RWMutex + listeners []Listener +} + +func New() *Eventbus { + eb := Eventbus{} + eb.mutex = &sync.RWMutex{} + eb.listeners = make([]Listener, 0) + + return &eb +} + +func (this *Eventbus) Emit(eventtype string, o interface{}) { + this.mutex.RLock() + defer this.mutex.RUnlock() + + for _, l := range this.listeners { + l.OnEvent(eventtype, o) + } +} + +func (this *Eventbus) AddListener(l Listener) { + this.mutex.Lock() + defer this.mutex.Unlock() + + this.listeners = append(this.listeners, l) +}