71 lines
1.3 KiB
Go
71 lines
1.3 KiB
Go
package events
|
|
|
|
import (
|
|
"sync"
|
|
)
|
|
|
|
// ClientMessage represents a message sent by the client
|
|
type ClientMessage struct {
|
|
Type string `json:"type"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
// ServerEvent represents an event sent to the client
|
|
type ServerEvent struct {
|
|
Type string `json:"type"`
|
|
Data interface{} `json:"message"`
|
|
}
|
|
|
|
// Eventer define an interface that any eventer must follow
|
|
type Eventer interface {
|
|
Subscribe(func())
|
|
Unsubscribe()
|
|
Launch()
|
|
}
|
|
|
|
// Notifier represents the base of any Eventer
|
|
// Notify implements Subscribe and Unsubscribe methods
|
|
type Notifier struct {
|
|
sync.RWMutex
|
|
subscribed bool
|
|
done chan struct{}
|
|
eventStream chan ServerEvent
|
|
}
|
|
|
|
// NewNotifier returns a new notifier
|
|
func NewNotifier(eventStream chan ServerEvent) *Notifier {
|
|
return &Notifier{
|
|
eventStream: eventStream,
|
|
done: make(chan struct{}),
|
|
}
|
|
}
|
|
|
|
// Subscribe subscribes a client on the Notifier
|
|
func (t *Notifier) Subscribe(launch func()) {
|
|
t.Lock()
|
|
defer t.Unlock()
|
|
|
|
// Check if already subscribed
|
|
if t.subscribed {
|
|
return
|
|
}
|
|
t.subscribed = true
|
|
|
|
go launch()
|
|
}
|
|
|
|
// Unsubscribe unsubscribes a client from receiving any more events from
|
|
// the Notifier
|
|
func (t *Notifier) Unsubscribe() {
|
|
t.Lock()
|
|
defer t.Unlock()
|
|
|
|
// Check if already unsubscribed
|
|
if !t.subscribed {
|
|
return
|
|
}
|
|
t.subscribed = false
|
|
|
|
t.done <- struct{}{}
|
|
}
|