/
TomlLoad.go
64 lines (55 loc) · 1.05 KB
/
TomlLoad.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 TomlConfiguration
import (
"errors"
"github.com/BurntSushi/toml"
"io"
"os"
"path/filepath"
)
var (
ErrSourceNotSet = errors.New("config path or reader is not set")
ErrFileNotFound = errors.New("config file not found")
)
type TOMLLoader struct {
Path string
Reader io.Reader
}
func (t *TOMLLoader) Load(s interface{}) error {
var r io.Reader
tag := TagLoader{}
tag.load(s)
if t.Reader != nil {
r = t.Reader
} else if t.Path != "" {
file, err := getConfig(t.Path)
if err != nil {
return err
}
defer file.Close()
r = file
} else {
return ErrSourceNotSet
}
if _, err := toml.DecodeReader(r, s); err != nil {
return err
}
return nil
}
func getConfig(path string) (*os.File, error) {
pwd, err := os.Getwd()
if err != nil {
return nil, err
}
configPath := path
if !filepath.IsAbs(path) {
configPath = filepath.Join(pwd, path)
}
if _, err := os.Stat(configPath); !os.IsNotExist(err) {
return os.Open(configPath)
}
f, err := os.Open(path)
if os.IsNotExist(err) {
return nil, ErrFileNotFound
}
return f, err
}