/
manager.go
87 lines (68 loc) · 1.66 KB
/
manager.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 plugin
import (
"fmt"
"sync"
)
const defaultModule = "micro"
type manager struct {
sync.Mutex
plugins map[string][]Plugin
registered map[string]map[string]bool
}
var (
// global plugin manager
defaultManager = newManager()
)
func newManager() *manager {
return &manager{
plugins: make(map[string][]Plugin),
registered: make(map[string]map[string]bool),
}
}
func (m *manager) Plugins(opts ...PluginOption) []Plugin {
options := PluginOptions{Module: defaultModule}
for _, o := range opts {
o(&options)
}
m.Lock()
defer m.Unlock()
if plugins, ok := m.plugins[options.Module]; ok {
return plugins
}
return []Plugin{}
}
func (m *manager) Register(plugin Plugin, opts ...PluginOption) error {
options := PluginOptions{Module: defaultModule}
for _, o := range opts {
o(&options)
}
m.Lock()
defer m.Unlock()
name := plugin.String()
if reg, ok := m.registered[options.Module]; ok && reg[name] {
return fmt.Errorf("Plugin with name %s already registered", name)
}
if _, ok := m.registered[options.Module]; !ok {
m.registered[options.Module] = map[string]bool{name: true}
} else {
m.registered[options.Module][name] = true
}
if _, ok := m.plugins[options.Module]; ok {
m.plugins[options.Module] = append(m.plugins[options.Module], plugin)
} else {
m.plugins[options.Module] = []Plugin{plugin}
}
return nil
}
func (m *manager) isRegistered(plugin Plugin, opts ...PluginOption) bool {
options := PluginOptions{Module: defaultModule}
for _, o := range opts {
o(&options)
}
m.Lock()
defer m.Unlock()
if _, ok := m.registered[options.Module]; !ok {
return false
}
return m.registered[options.Module][plugin.String()]
}