/
config-reader.go
65 lines (52 loc) · 1.23 KB
/
config-reader.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
package module
import (
"fmt"
"os"
"regexp"
"gopkg.in/yaml.v2"
)
var config map[string]string
func InitConfigs() {
filename := "resources/application.yml"
data, err := os.ReadFile(filename)
if err != nil {
panic(err)
}
var result map[interface{}]interface{}
err = yaml.UnmarshalStrict(data, &result)
if err != nil {
panic(err)
}
config = make(map[string]string)
initKeys("", result)
}
func formatKey(prefix string, key interface{}) string {
if prefix == "" {
return fmt.Sprintf("%v", key)
}
return fmt.Sprintf("%s.%v", prefix, key)
}
func initKeys(prefix string, data map[interface{}]interface{}) {
for key, value := range data {
fullKey := formatKey(prefix, key)
if v, ok := value.(map[interface{}]interface{}); ok {
initKeys(fullKey, v)
} else {
config[fullKey] = formatValue(value)
}
}
}
func formatValue(value interface{}) string {
strValue := fmt.Sprintf("%s", value)
re := regexp.MustCompile("\\$\\{([^:]+)(:([^\\}]+))?\\}")
result := re.ReplaceAllStringFunc(strValue, func(match string) string {
matches := re.FindStringSubmatch(match)
envVar := matches[1]
defaultVal := matches[3]
if val, exists := os.LookupEnv(envVar); exists {
return val
}
return defaultVal
})
return result
}