-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
101 lines (82 loc) · 1.71 KB
/
loader.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package config
import (
"context"
)
// load the config, it may internally uses Provider to read config
type Loader interface {
Load(ctx context.Context, fp string, opts ...Option) (Config, error)
}
type loader struct {
opts options
config config
}
func (r *loader) Load(ctx context.Context, fp string, opts ...Option) (Config, error) {
o := options{
fp: fp,
reload: r.opts.reload,
decoder: r.opts.decoder,
provider: r.opts.provider,
}
for _, opt := range opts {
opt(&o)
}
if o.reload {
r.reload(ctx, fp, o)
}
return r.load(ctx, fp, o)
}
func (r *loader) reload(ctx context.Context, fp string, opts options) error {
ch, err := opts.provider.Watch(ctx, fp)
if err != nil {
return err
}
go func() {
for {
select {
case v := <-ch:
if v.typ != Update {
continue
}
r.load(ctx, fp, opts)
case <-ctx.Done():
return
}
}
}()
return nil
}
func (r *loader) decode(ctx context.Context, data []byte, opts options) (interface{}, error) {
var cfg interface{}
var err error
switch v := opts.decoder.(type) {
case *YAMLDecoder:
cfg, err = v.Decode(data)
// y := YAMLConfig{}
// simpleyaml.NewYaml()
default:
panic("not support decode tyoe")
}
if err != nil {
return nil, err
}
return cfg, nil
}
func (r *loader) load(ctx context.Context, fp string, opts options) (Config, error) {
data, err := opts.provider.Load(ctx, fp)
if err != nil {
return nil, err
}
cfg, err := r.decode(ctx, data, opts)
if err != nil {
return nil, err
}
r.config.value.Store(cfg)
return &r.config, nil
}
func NewLoader(ctx context.Context, opts ...Option) (Loader, error) {
o := options{}
for _, opt := range opts {
opt(&o)
}
return &loader{opts: o}, nil
}