-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
64 lines (57 loc) · 1.55 KB
/
load.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
package snuffler
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/BurntSushi/toml"
yaml "gopkg.in/yaml.v2"
)
// unmarshalFiles loads each file in turn into the interface, starting with
// the first files added to the snuffler.
func (s *Snuffler) unmarshalFiles(conf interface{}) error {
for _, f := range s.files {
if err := unmarshalFile(f, conf); err != nil {
return err
}
}
return nil
}
// unmarshalFile loads the contents of one file into the provided interface.
func unmarshalFile(f *configFile, conf interface{}) error {
if f.fileType == yamlType {
return unmarshalYAML(f, conf)
} else if f.fileType == tomlType {
return unmarshalTOML(f, conf)
} else if f.fileType == jsonType {
return unmarshalJSON(f, conf)
} else {
// Since JSON is valid YAML, we don't need to try that one.
if errYAML := unmarshalYAML(f, conf); errYAML != nil {
if errTOML := unmarshalTOML(f, conf); errTOML != nil {
return fmt.Errorf("couldn't read %s as YAML/JSON (%v) or TOML (%v)", f.fileName, errYAML, errTOML)
} else {
return nil
}
} else {
return nil
}
}
}
func unmarshalYAML(f *configFile, conf interface{}) error {
contents, err := ioutil.ReadFile(f.fileName)
if err != nil {
return err
}
return yaml.Unmarshal(contents, conf)
}
func unmarshalTOML(f *configFile, conf interface{}) error {
_, err := toml.DecodeFile(f.fileName, conf)
return err
}
func unmarshalJSON(f *configFile, conf interface{}) error {
contents, err := ioutil.ReadFile(f.fileName)
if err != nil {
return err
}
return json.Unmarshal(contents, conf)
}