-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
86 lines (69 loc) · 1.83 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package jconf
import (
"encoding/json"
"fmt"
"os"
)
type Config struct {
file string
config map[string]interface{}
}
// NewConfig is used to parse configuration values from a JSON file.
func NewConfig(filename string) (*Config, error) {
config := &Config{
file: filename,
}
err := config.readConfig()
return config, err
}
// Internal function to read config JSON.
func (c *Config) readConfig() error {
file, err := os.Open(c.file)
if nil != err {
return fmt.Errorf("Could not read config %s: %s", c.file, err)
}
decoder := json.NewDecoder(file)
err = decoder.Decode(&c.config)
if nil != err {
return fmt.Errorf("Could not parse config %s: %s", c.file, err)
}
// Allow environment variable to override config setting.
for key, _ := range c.config {
newVal, ok := os.LookupEnv(key)
if ok {
c.config[key] = newVal
//fmt.Printf("Overriding config value %s:%s with env variable: %s\n", key, val, newVal)
}
}
return nil
}
// The HasConfig function can be used to determine if a config value
// exists before reading.
func (c *Config) HasConfig(key string) bool {
_, ok := c.config[key]
return ok
}
// The GetConfig function is used to get a config value as an interface.
// nil is returned if the config value does not exist.
func (c *Config) GetConfig(key string) interface{} {
val, _ := c.config[key]
return val
}
// The GetConfigStr function is used to get a config value as a string.
// An empty string is returned if the config value does not exist.
func (c *Config) GetConfigStr(key string) string {
val, ok := c.config[key]
if ok {
return val.(string)
}
return ""
}
// The GetConfigStr function is used to get a config as an integter.
// -1 is returned if the config value does not exist.
func (c *Config) GetConfigInt(key string) int {
val, ok := c.config[key]
if ok {
return val.(int)
}
return -1
}