-
Notifications
You must be signed in to change notification settings - Fork 3
/
registry.go
61 lines (50 loc) · 1.28 KB
/
registry.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
package core
import (
"fmt"
)
var globalRegistry = NewRegistry()
type Factory func(c *Conf) (Logger, error)
// Registry is the interface for callers to get registered middleware.
type Registry interface {
Register(name string, factory Factory)
Create(c *Conf) (Logger, error)
}
type coreRegistry struct {
cores map[string]Factory
}
// NewRegistry returns a new middleware registry.
func NewRegistry() Registry {
return &coreRegistry{
cores: map[string]Factory{},
}
}
func (d *coreRegistry) Register(name string, factory Factory) {
d.cores[name] = factory
}
func (d *coreRegistry) Create(c *Conf) (Logger, error) {
factory, ok := d.cores[c.Type.String()]
if !ok {
return nil, fmt.Errorf("cores %s has not been registered", c.Type.String())
}
impl, err := factory(c)
if err != nil {
return nil, fmt.Errorf("create cores error: %s", err)
}
return impl, nil
}
// Register registers one cores.
func Register(name string, factory Factory) {
globalRegistry.Register(name, factory)
}
// Create instantiates a cores based on `discoveryDSN`.
func Create(c *Conf) (Logger, error) {
return globalRegistry.Create(c)
}
// MustCreate instantiates a cores based on `discoveryDSN`.
func MustCreate(c *Conf) Logger {
co, err := globalRegistry.Create(c)
if err != nil {
panic(err)
}
return co
}