Repository navigation
Expand file tree
/
Copy pathconfig.go
More file actions
99 lines (80 loc) · 2.35 KB
/
Copy pathconfig.go
File metadata and controls
99 lines (80 loc) · 2.35 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
package jconf
import (
"encoding/json"
"fmt"
"os"
"strings"
)
type Config struct {
config map[string]interface{}
}
// NewConfig is used to parse configuration values from a JSON file.
func NewConfig(filename string) (*Config, error) {
config := &Config{}
config.config = make(map[string]interface{})
err := config.readConfig(filename)
return config, err
}
func (c *Config) AddConfig(filename string) error {
return c.readConfig(filename)
}
// Internal function to read config JSON.
func (c *Config) readConfig(filename string) error {
file, err := os.Open(filename)
if nil != err {
return fmt.Errorf("Could not read config %s: %s", filename, err)
}
fmt.Printf("Reading config file %s\n", filename)
config := make(map[string]interface{})
decoder := json.NewDecoder(file)
err = decoder.Decode(&config)
if nil != err {
return fmt.Errorf("Could not parse config %s: %s", filename, err)
}
// Allow environment variable to override config setting.
for key, _ := range config {
fmt.Printf("Have config %s - looking for env variable overrides\n", key)
newVal, ok := os.LookupEnv(strings.ToUpper(key))
if ok {
fmt.Printf("Overriding config value %s with env variable\n", key)
//fmt.Printf("Overriding config value %s with env variable: %s\n", key, newVal)
config[key] = newVal
}
}
// Merge into main config map.
for key, val := range config {
//fmt.Printf("Adding config value %s:%s\n", key, val)
c.config[key] = val
}
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) float64 {
val, ok := c.config[key]
if ok {
return val.(float64)
}
return -1
}