/
simpleconf.go
72 lines (57 loc) · 1.04 KB
/
simpleconf.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
package simpleconf
import (
"github.com/mitchellh/go-homedir"
"path"
"os"
"github.com/BurntSushi/toml"
"errors"
)
type Config struct {
path string
File string
Data interface{}
}
func (c *Config) Ensure() error {
home, err := homedir.Dir()
if err != nil {
return err
}
c.path = path.Join(home, c.File)
_, err = os.Stat(c.path);
if os.IsNotExist(err) {
c.Flush()
}
return nil
}
func (c *Config) Load() error {
if _, err := toml.DecodeFile(c.path, &c.Data); err != nil {
return err
}
return nil
}
func (c *Config) Flush() error {
if c.Data == nil {
return errors.New("Cannot flush config without loading/creating it first!")
}
file, err := os.Create(c.path)
if err != nil {
panic(err)
}
encoder := toml.NewEncoder(file)
err = encoder.Encode(c.Data)
if err != nil {
panic(err)
}
return nil
}
func New(fileName string, defaultData interface{}) (*Config, error) {
conf := &Config{
File: fileName,
Data: defaultData,
}
if err := conf.Ensure(); err != nil {
return nil, err
}
conf.Load()
return conf, nil
}