forked from jacobstr/confer
/
configreader.go
87 lines (71 loc) · 1.71 KB
/
configreader.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
package reader
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"path/filepath"
"github.com/BurntSushi/toml"
"github.com/jacobstr/confer/errors"
jww "github.com/spf13/jwalterweatherman"
"gopkg.in/yaml.v2"
)
type ConfigFormat string
const (
FormatYAML ConfigFormat = "yaml"
FormatJSON ConfigFormat = "json"
FormatTOML ConfigFormat = "toml"
)
type ConfigReader struct {
Format string
reader io.Reader
}
// Retuns the configuration data into a generic object for for us.
func (cr *ConfigReader) Export() (interface{}, error) {
var config interface{}
buf := new(bytes.Buffer)
buf.ReadFrom(cr.reader)
switch cr.Format {
case "yaml":
if err := yaml.Unmarshal(buf.Bytes(), &config); err != nil {
jww.ERROR.Fatalf("Error parsing config: %s", err)
}
case "json":
if err := json.Unmarshal(buf.Bytes(), &config); err != nil {
jww.ERROR.Fatalf("Error parsing config: %s", err)
}
case "toml":
if _, err := toml.Decode(buf.String(), &config); err != nil {
jww.ERROR.Fatalf("Error parsing config: %s", err)
}
default:
return nil, err.UnsupportedConfigError(cr.Format)
}
return config, nil
}
func ReadFile(path string) (interface{}, error) {
file, err := ioutil.ReadFile(path)
if err != nil {
jww.DEBUG.Println("Error reading config file:", err)
return nil, err
}
reader := bytes.NewReader(file)
cr := &ConfigReader{Format: getConfigType(path), reader: reader}
return cr.Export()
}
func ReadBytes(data []byte, format string) (interface{}, error) {
cr := ConfigReader{
Format: format,
reader: bytes.NewReader(data),
}
return cr.Export()
}
func getConfigType(path string) string {
ext := filepath.Ext(path)
switch ext[1:] {
case "yml":
return "yaml"
default:
return ext[1:]
}
}