-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreader.go
More file actions
58 lines (50 loc) · 983 Bytes
/
reader.go
File metadata and controls
58 lines (50 loc) · 983 Bytes
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
package go_config
import (
"bytes"
"encoding/json"
"fmt"
toml "github.com/pelletier/go-toml"
yaml "gopkg.in/yaml.v2"
"io"
)
type ConfigType int
type ConfigParseError struct {
err error
}
const (
JSON ConfigType = iota
YAML
TOML
)
func (pe ConfigParseError) Error() string {
return fmt.Sprintf("Config parsing error: %s", pe.err.Error())
}
func ReadConfig(in io.Reader, ct ConfigType, c map[string]interface{}) error {
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(in)
if err != nil {
return err
}
switch ct {
case JSON:
decoder := json.NewDecoder(buf)
decoder.UseNumber()
if err := decoder.Decode(&c); err != nil {
return ConfigParseError{err}
}
case YAML:
if err := yaml.Unmarshal(buf.Bytes(), &c); err != nil {
return ConfigParseError{err}
}
case TOML:
tree, err := toml.LoadReader(buf)
if err != nil {
return ConfigParseError{err}
}
tomlMap := tree.ToMap()
for k, v := range tomlMap {
c[k] = v
}
}
return nil
}