This repository has been archived by the owner on Apr 29, 2020. It is now read-only.
/
config.go
113 lines (101 loc) · 2.42 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Package config provides convenience facilities for Golang-based pods to read their
// configuration files provided either by the environment or a custom path.
package config
import (
"errors"
"fmt"
"io/ioutil"
"os"
"sort"
"gopkg.in/yaml.v2"
)
type Config struct {
unpacked map[interface{}]interface{}
}
func LoadFromUnpacked(unpacked map[interface{}]interface{}) *Config {
return &Config{unpacked}
}
func LoadFromEnvironment() (*Config, error) {
env := os.Getenv("CONFIG_PATH")
if env == "" {
return nil, errors.New("No value was found for the environment variable CONFIG_PATH")
}
return LoadConfigFile(env)
}
func LoadConfigFile(filepath string) (*Config, error) {
config := &Config{}
contents, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, err
}
if err = yaml.Unmarshal(contents, &config.unpacked); err != nil {
return nil, err
}
return config, nil
}
func (c *Config) ReadString(key string) (string, error) {
readVal := c.Read(key)
if readVal == nil {
return "", nil
}
strVal, ok := readVal.(string)
if !ok {
return "", fmt.Errorf("%s is not a string value", key)
}
return strVal, nil
}
func (c *Config) ReadBool(key string) (bool, error) {
readVal := c.Read(key)
if readVal == nil {
return false, nil
}
boolVal, ok := readVal.(bool)
if !ok {
return false, fmt.Errorf("%s is not a bool value", key)
}
return boolVal, nil
}
func (c *Config) Read(key string) interface{} {
return c.unpacked[key]
}
func (c *Config) ReadMap(key string) (*Config, error) {
readVal := c.Read(key)
if readVal == nil {
return &Config{make(map[interface{}]interface{})}, nil
}
mapVal, ok := readVal.(map[interface{}]interface{})
if !ok {
return &Config{make(map[interface{}]interface{})}, fmt.Errorf("%s is not a map", key)
}
return &Config{mapVal}, nil
}
func (c *Config) ReadStringSlice(key string) ([]string, error) {
readVal := c.Read(key)
retV := []string{}
if readVal == nil {
return retV, nil
}
slice, ok := readVal.([]interface{})
if !ok {
return retV, fmt.Errorf("%s is not a string slice", key)
}
for _, intf := range slice {
strVal, ok := intf.(string)
if !ok {
return []string{}, fmt.Errorf("%v is not a string", intf)
}
retV = append(retV, strVal)
}
return retV, nil
}
func (c *Config) Keys() []string {
keys := []string{}
for intf := range c.unpacked {
strVal, ok := intf.(string)
if ok {
keys = append(keys, strVal)
}
}
sort.Strings(keys)
return keys
}