-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig.go
72 lines (59 loc) · 1.56 KB
/
config.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 config
import (
"errors"
"io/ioutil"
"github.com/Clinet/clinet_features"
"github.com/JoshuaDoes/json"
)
type ConfigType int
const (
ConfigTypeJSON ConfigType = iota
ConfigTypeTOML
ConfigTypeXML
)
type Config struct {
Features map[string]features.Feature `json:"features"`
path string //The path to the configuration file
}
//NewConfig returns a new configuration struct
func NewConfig() *Config {
return &Config{
Features: make(map[string]features.Feature),
}
}
//LoadConfig creates a new configuration struct with the values in the specified configuration file
func LoadConfig(path string, cfgType ConfigType) (*Config, error) {
cfg := &Config{path: path}
switch cfgType {
case ConfigTypeJSON:
configJSON, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
err = json.Unmarshal(configJSON, cfg)
if err != nil {
return nil, err
}
default:
return nil, errors.New("bot: config: unknown configuration type")
}
return cfg, nil
}
func SaveConfig(cfg *Config, path string, cfgType ConfigType) error {
configJSON, err := json.Marshal(cfg, true)
if err != nil {
return err
}
err = ioutil.WriteFile(path, configJSON, 0644)
return err
}
//LoadFrom loads the configuration from the specified path into the current cfg
func (cfg *Config) LoadFrom(path string, cfgType ConfigType) (err error) {
cfg, err = LoadConfig(path, cfgType)
return err
}
//SaveTo saves the current cfg to the specified path
func (cfg *Config) SaveTo(path string, cfgType ConfigType) (err error) {
err = SaveConfig(cfg, path, cfgType)
return err
}