forked from vardius/message-bus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbus.go
86 lines (66 loc) · 1.79 KB
/
bus.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
package messagebus
import (
"fmt"
"reflect"
"sync"
)
// MessageBus implements publish/subscribe messaging paradigm
type MessageBus interface {
Publish(topic string, args ...interface{})
Subscribe(topic string, fn interface{}) error
Unsubscribe(topic string, fn interface{}) error
}
type handlersMap map[string][]reflect.Value
type messageBus struct {
mtx sync.RWMutex
handlers handlersMap
}
// Publish publishes arguments to the given topic subscribers
func (b *messageBus) Publish(topic string, args ...interface{}) {
b.mtx.RLock()
defer b.mtx.RUnlock()
if hs, ok := b.handlers[topic]; ok {
rArgs := buildHandlerArgs(args)
for _, h := range hs {
go h.Call(rArgs)
}
}
}
// Subscribe subscribes to the given topic
func (b *messageBus) Subscribe(topic string, fn interface{}) error {
if reflect.TypeOf(fn).Kind() != reflect.Func {
return fmt.Errorf("%s is not a reflect.Func", reflect.TypeOf(fn))
}
b.mtx.Lock()
defer b.mtx.Unlock()
b.handlers[topic] = append(b.handlers[topic], reflect.ValueOf(fn))
return nil
}
// Unsubscribe unsubsribes from the given topic
func (b *messageBus) Unsubscribe(topic string, fn interface{}) error {
b.mtx.Lock()
defer b.mtx.Unlock()
if _, ok := b.handlers[topic]; ok {
rv := reflect.ValueOf(fn)
for i, h := range b.handlers[topic] {
if h == rv {
b.handlers[topic] = append(b.handlers[topic][:i], b.handlers[topic][i+1:]...)
}
}
return nil
}
return fmt.Errorf("Topic %s doesn't exist", topic)
}
func buildHandlerArgs(args []interface{}) []reflect.Value {
reflectedArgs := make([]reflect.Value, 0)
for _, arg := range args {
reflectedArgs = append(reflectedArgs, reflect.ValueOf(arg))
}
return reflectedArgs
}
// New creates new MessageBus
func New() MessageBus {
return &messageBus{
handlers: make(handlersMap),
}
}