/
prefer.go
86 lines (66 loc) · 1.61 KB
/
prefer.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
package prefer
type filterable func(identifier string) bool
type Configuration struct {
Identifier string
Loaders map[Loader]filterable
Serializers map[Serializer]SerializerFactory
}
func Load(identifier string, dest interface{}) (*Configuration, error) {
this := NewConfiguration(identifier)
return this, this.Reload(dest)
}
func Watch(identifier string, dest interface{}) (chan interface{}, error) {
channel := make(chan interface{})
configuration := NewConfiguration(identifier)
go configuration.Watch(dest, channel)
return channel, nil
}
func NewConfiguration(identifier string) *Configuration {
return &Configuration{
Identifier: identifier,
}
}
func (this *Configuration) Reload(dest interface{}) error {
loader, err := NewLoader(this.Identifier)
if err != nil {
return err
}
identifier, content, err := loader.Load()
if err != nil {
return err
}
this.Identifier = identifier
serializer, err := NewSerializer(identifier, content)
if err != nil {
return err
}
return serializer.Deserialize(content, dest)
}
func (this *Configuration) Watch(dest interface{}, channel chan interface{}) error {
this.Reload(dest)
channel <- dest
update := make(chan bool)
loader, err := NewLoader(this.Identifier)
if err != nil {
return err
}
go loader.Watch(update)
for {
if <-update == true {
identifier, content, err := loader.Load()
if err != nil {
return err
}
serializer, err := NewSerializer(identifier, content)
if err != nil {
return err
}
err = serializer.Deserialize(content, dest)
if err != nil {
return err
}
channel <- dest
}
}
return err
}