-
Notifications
You must be signed in to change notification settings - Fork 3
/
registry.go
56 lines (44 loc) · 1.31 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
package config
import (
"fmt"
"github.com/go-kratos/kratos/v2/config"
"net/url"
)
var globalRegistry = NewRegistry()
type Factory func(dsn *url.URL, v interface{}) (config.Config, error)
// Registry is the interface for callers to get registered middleware.
type Registry interface {
Register(name string, factory Factory)
Create(dsn *url.URL, v interface{}) (config.Config, error)
}
type configRegistry struct {
discovery map[string]Factory
}
// NewRegistry returns a new middleware registry.
func NewRegistry() Registry {
return &configRegistry{
discovery: map[string]Factory{},
}
}
func (d *configRegistry) Register(name string, factory Factory) {
d.discovery[name] = factory
}
func (d *configRegistry) Create(dsn *url.URL, v interface{}) (config.Config, error) {
factory, ok := d.discovery[dsn.Scheme]
if !ok {
return nil, fmt.Errorf("discovery %s has not been registered", dsn.Scheme)
}
impl, err := factory(dsn, v)
if err != nil {
return nil, fmt.Errorf("create discovery error: %s", err)
}
return impl, nil
}
// Register registers one discovery.
func Register(name string, factory Factory) {
globalRegistry.Register(name, factory)
}
// Create instantiates a discovery based on `discoveryDSN`.
func Create(dsn *url.URL, v interface{}) (config.Config, error) {
return globalRegistry.Create(dsn, v)
}