-
Notifications
You must be signed in to change notification settings - Fork 0
/
registry.go
79 lines (59 loc) · 1.43 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package waitfor
import (
"context"
"errors"
"net/url"
"strings"
)
type (
ResourceFactory func(u *url.URL) (Resource, error)
ResourceConfig struct {
Scheme []string
Factory ResourceFactory
}
Resource interface {
Test(ctx context.Context) error
}
Registry struct {
resources map[string]ResourceFactory
}
)
func newRegistry(configs []ResourceConfig) *Registry {
resources := make(map[string]ResourceFactory)
for _, c := range configs {
for _, s := range c.Scheme {
resources[s] = c.Factory
}
}
return &Registry{resources}
}
// Register adds a resource factory to the registry
func (r *Registry) Register(scheme string, factory ResourceFactory) error {
scheme = strings.TrimSpace(scheme)
_, exists := r.resources[scheme]
if exists {
return errors.New("resource is already registered with a given scheme:" + scheme)
}
r.resources[scheme] = factory
return nil
}
// Resolve returns a resource instance by a given url
func (r *Registry) Resolve(location string) (Resource, error) {
u, err := url.Parse(location)
if err != nil {
return nil, err
}
rf, found := r.resources[u.Scheme]
if !found {
return nil, errors.New("resource with a given scheme is not found:" + u.Scheme)
}
return rf(u)
}
// List returns a list of schemes of registered resources
func (r *Registry) List() []string {
list := make([]string, 0, len(r.resources))
for k := range r.resources {
list = append(list, k)
}
return list
}