This repository was archived by the owner on Apr 2, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmemory-pub-sub.go
More file actions
56 lines (44 loc) · 1.22 KB
/
memory-pub-sub.go
File metadata and controls
56 lines (44 loc) · 1.22 KB
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
package cluster
import (
"context"
"github.com/rs/zerolog"
)
// MemoryPubSub struct
type MemoryPubSub struct {
ctx context.Context
callbacks map[string]func(data string)
debug bool
logger *zerolog.Logger
prefix string
}
// NewMemoryPubSub create a new memory pub/sub client
// this is the default (mock) implementation for the internal pub/sub communications on standalone servers
// for clusters, use another solution, like RedisPubSub
func NewMemoryPubSub(ctx context.Context) (*MemoryPubSub, error) {
return &MemoryPubSub{
ctx: ctx,
callbacks: make(map[string]func(data string)),
}, nil
}
// Logger returns the logger to use
func (m *MemoryPubSub) Logger() *zerolog.Logger {
return m.logger
}
// Subscribe to a channel
func (m *MemoryPubSub) Subscribe(channel Channel, callback func(data string)) (func() error, error) {
channelName := m.prefix + string(channel)
m.callbacks[channelName] = callback
return func() error {
delete(m.callbacks, channelName)
return nil
}, nil
}
// Publish to a channel
func (m *MemoryPubSub) Publish(channel Channel, data string) error {
channelName := m.prefix + string(channel)
callback, ok := m.callbacks[channelName]
if ok {
callback(data)
}
return nil
}