forked from nnev/frank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlisteners.go
87 lines (70 loc) · 1.56 KB
/
listeners.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"log"
"sync"
"time"
)
type Runner func(Message)
type Listener struct {
desc string
created string
runner Runner
}
var listenersMutex sync.Mutex
var listeners []*Listener
func ListenerAdd(desc string, r Runner) *Listener {
log.Printf("Adding Listener for: %s", desc)
l := &Listener{runner: r, desc: desc, created: time.Now().Format("2006-01-02 15:04:05 -0700")}
l.Add()
return l
}
func (listener *Listener) Add() {
listenersMutex.Lock()
listeners = append(listeners, listener)
listenersMutex.Unlock()
listenersDebug()
}
func (listener *Listener) Remove() {
go func() {
listenersMutex.Lock()
index := -1
for idx, l := range listeners {
if listener == l {
index = idx
}
}
if index >= 0 {
log.Printf("Removing Listener: %s at index %d", listener, index)
listeners[index] = listeners[len(listeners)-1]
listeners = listeners[0 : len(listeners)-1]
} else {
log.Printf("Removing Listener: %s but was not found in list", listener)
}
listenersMutex.Unlock()
listenersDebug()
}()
}
func listenersDebug() {
listenersMutex.Lock()
s := ""
for _, listener := range listeners {
s += listener.desc + ", "
}
log.Printf("listeners #%d: %s", len(listeners), s)
listenersMutex.Unlock()
}
func listenersReset() {
listenersMutex.Lock()
listeners = []*Listener{}
log.Printf("# of listeners: 0")
listenersMutex.Unlock()
}
func listenersRun(parsed Message) {
listenersMutex.Lock()
for _, listener := range listeners {
go func(l *Listener) {
l.runner(parsed)
}(listener)
}
listenersMutex.Unlock()
}