-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
config.go
70 lines (57 loc) · 1.19 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
package main
import (
"encoding/json"
"io/ioutil"
)
// Option is a single configuration option.
type Option struct {
Name string
Value interface{}
}
// Config is a configuration file.
type Config struct {
Options []Option
}
// LoadConfig loads a configuration file.
func LoadConfig(filename string) (Config, error) {
config := Config{}
j, err := ioutil.ReadFile(filename)
if err != nil {
return config, err
}
err = json.Unmarshal(j, &config)
return config, err
}
// Save saves the configuration to a file.
func (c Config) Save(filename string) error {
j, err := json.MarshalIndent(c, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(filename, j, 0600)
}
// Value returns the value of a configuration option.
func (c Config) Value(name string) interface{} {
for _, v := range c.Options {
if v.Name == name {
return v.Value
}
}
return nil
}
// Set sets the value of a configuration option.
func (c *Config) Set(name, value string) {
found := false
var opts []Option
for _, v := range c.Options {
if v.Name == name {
v.Value = value
found = true
}
opts = append(opts, v)
}
if !found {
opts = append(opts, Option{name, value})
}
c.Options = opts
}