-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
41 lines (35 loc) · 1 KB
/
file.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
package cnfg
import (
"encoding/json"
"encoding/xml"
"io/ioutil"
"strings"
toml "github.com/pelletier/go-toml"
yaml "gopkg.in/yaml.v2"
)
// UnmarshalFile parses a configuration file (of any format) into a config struct.
// This is a shorthand method for calling Unmarshal against the json, xml, yaml
// or toml packages. If the file name contains an appropriate suffix it is
// unmarshaled with the corresponding package. If the suffix is missing, TOML
// is assumed. Works with multiple files, so you can have stacked configurations.
func UnmarshalFile(c interface{}, configFile ...string) error {
for _, f := range configFile {
buf, err := ioutil.ReadFile(f)
switch {
case err != nil:
return err
case strings.Contains(f, ".json"):
err = json.Unmarshal(buf, c)
case strings.Contains(f, ".xml"):
err = xml.Unmarshal(buf, c)
case strings.Contains(f, ".yaml"):
err = yaml.Unmarshal(buf, c)
default:
err = toml.Unmarshal(buf, c)
}
if err != nil {
return err
}
}
return nil
}