forked from bearded-web/bearded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.go
91 lines (78 loc) · 1.92 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package load
import (
"fmt"
"io"
"os"
"path"
)
type Format string
const (
UnknownFormat = Format("")
)
type Opts struct {
Format Format
}
type LoaderFunc func(io.Reader, interface{}) error
type Loader struct {
ExtToFormat map[string]Format
Loaders map[Format]LoaderFunc
}
func New() *Loader {
return &Loader{
ExtToFormat: map[string]Format{},
Loaders: map[Format]LoaderFunc{},
}
}
// load data to dst struct from file according to format
func (l *Loader) FromFile(filename string, dst interface{}, opts ...Opts) error {
// take format from filename extension
format := UnknownFormat
for _, opt := range opts {
format = opt.Format
}
if format == UnknownFormat {
ext := path.Ext(filename)
if f, ok := l.ExtToFormat[ext]; !ok {
return fmt.Errorf("Cant't recognize format from extension %s", ext)
} else {
format = f
}
}
f, err := os.Open(filename)
if err != nil {
return err
}
return l.FromReader(f, dst, format)
}
// load data to dst struct from f according to format
func (l *Loader) FromReader(r io.Reader, dst interface{}, format Format) error {
var err error
if loaderFunc, ok := l.Loaders[format]; !ok {
err = fmt.Errorf("Unknown format %s", format)
} else {
err = loaderFunc(r, dst)
}
return err
}
var DefaultLoader = Loader{
Loaders: map[Format]LoaderFunc{
TomlFormat: LoadToml,
JsonFormat: LoadJson,
YamlFormat: LoadYaml,
},
ExtToFormat: map[string]Format{
".toml": TomlFormat,
".tml": TomlFormat,
".json": JsonFormat,
".yaml": YamlFormat,
".yml": YamlFormat,
},
}
// load data to dst struct from file according to format with default loader
func FromFile(filename string, dst interface{}, opts ...Opts) error {
return DefaultLoader.FromFile(filename, dst, opts...)
}
// load data to dst struct from f according to format with default loader
func FromReader(r io.Reader, dst interface{}, format Format) error {
return DefaultLoader.FromReader(r, dst, format)
}