-
Notifications
You must be signed in to change notification settings - Fork 3
/
loader.go
86 lines (72 loc) · 1.62 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
package conf
import (
"os"
)
type adapterList struct {
list []Adapter
}
func (s *adapterList) Add(a Adapter) bool {
for _, adapter := range s.list {
if adapter == a {
return false
}
}
s.list = append(s.list, a)
return true
}
type Loader struct {
adapters *adapterList
defaultConf *Conf
overrideConf *Conf
}
// Define default configuration
func (l *Loader) Defaults(m map[string]interface{}) *Loader {
l.defaultConf.Merge(m)
return l
}
// Override configuration loaded from any Adapter
func (l *Loader) Overrides(m map[string]interface{}) *Loader {
l.overrideConf.Merge(m)
return l
}
// Load configuration from command line arguments
func (l *Loader) Argv() *Loader {
l.adapters.Add(argv{os.Args})
return l
}
// Load configuration from environment variables
func (l *Loader) Env() *Loader {
l.adapters.Add(env{})
return l
}
// Load configuration from a JSON file
func (l *Loader) File(path string) *Loader {
l.adapters.Add(file{path})
return l
}
// Register a custom Adapter for loading configuration
func (l *Loader) Register(a Adapter) *Loader {
l.adapters.Add(a)
return l
}
// Load configuration with registered Adapters
func (l *Loader) Load() (*Conf, error) {
c := &Conf{make(map[string]interface{})}
c.Merge(l.defaultConf.conf)
for _, a := range l.adapters.list {
err := a.Apply(c)
if err != nil {
return nil, err
}
}
c.Merge(l.overrideConf.conf)
return c, nil
}
// Create a Loader
func NewLoader() *Loader {
return &Loader{
adapters: &adapterList{make([]Adapter, 0)},
defaultConf: &Conf{make(map[string]interface{})},
overrideConf: &Conf{make(map[string]interface{})},
}
}