-
Notifications
You must be signed in to change notification settings - Fork 3
/
config.go
208 lines (175 loc) · 5.34 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package config
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/go-playground/validator/v10"
"github.com/mitchellh/mapstructure"
"github.com/spf13/viper"
)
const defaultConfigYamlDir = "./"
// ConfigEditorFn is a function that can be used to modify the configuration values after they have been loaded
type ConfigEditorFn[T any] func(cfg *T) error
type ConfigLoader[T any] struct {
ConfigEditors []ConfigEditorFn[T]
ConfigYamlDir string
}
// ConfigOption is a function that can be used to modify the configuration loader
type ConfigOption[T any] func(*ConfigLoader[T]) error
// WithConfigEditorFn allows setting up a callback function, which will be
// called right after loading the configs. This can be used to mutate the config,
// for example to set default values where none were set by the call to LoadConfiguration.
func WithConfigEditorFn[T any](fn ConfigEditorFn[T]) ConfigOption[T] {
return func(c *ConfigLoader[T]) error {
c.ConfigEditors = append(c.ConfigEditors, fn)
return nil
}
}
func WithConfigYamlDir[T any](dir string) ConfigOption[T] {
return func(c *ConfigLoader[T]) error {
c.ConfigYamlDir = dir
return nil
}
}
// LoadConfiguration loads the configuration from the app-config.yaml and app-config.<env>.yaml files
func LoadConfiguration[T any](cfg *T, opts ...ConfigOption[T]) error {
configYamlDir := defaultConfigYamlDir
if len(os.Getenv("CONFIG_YAML_DIRECTORY")) > 0 {
configYamlDir = os.Getenv("CONFIG_YAML_DIRECTORY")
}
loader := &ConfigLoader[T]{
ConfigEditors: []ConfigEditorFn[T]{},
ConfigYamlDir: configYamlDir,
}
for _, opt := range opts {
err := opt(loader)
if err != nil {
return fmt.Errorf("ConfigOption failed: %w", err)
}
}
loader.populateConfiguration(cfg)
for _, fn := range loader.ConfigEditors {
err := fn(cfg)
if err != nil {
return fmt.Errorf("ConfigEditorFn failed: %w", err)
}
}
return validateConfiguration(cfg)
}
func (c *ConfigLoader[T]) populateConfiguration(cfg *T) error {
configYamlDir := c.ConfigYamlDir
path, err := filepath.Abs(configYamlDir)
if err != nil {
return fmt.Errorf("failed to get absolute path of %s: %w", configYamlDir, err)
}
vpr := viper.New()
appConfigFile := filepath.Join(path, "app-config.yaml")
if _, err := os.Stat(appConfigFile); err == nil {
tmp, err := evaluateConfigWithEnvToTmp(appConfigFile)
if len(tmp) != 0 {
defer os.Remove(tmp)
}
if err != nil {
return err
}
vpr.SetConfigFile(tmp)
err = vpr.ReadInConfig()
if err != nil {
return fmt.Errorf("failed to read config file: %w", err)
}
}
envConfigFilename := fmt.Sprintf("app-config.%s.yaml", getAppEnv())
appEnvConfigFile := filepath.Join(path, envConfigFilename)
if _, err := os.Stat(appEnvConfigFile); err == nil {
tmp, err := evaluateConfigWithEnvToTmp(appEnvConfigFile)
if len(tmp) != 0 {
defer os.Remove(tmp)
}
if err != nil {
return err
}
vpr.SetConfigFile(tmp)
err = vpr.MergeInConfig()
if err != nil {
return fmt.Errorf("failed to merge env config: %w", err)
}
}
err = vpr.Unmarshal(cfg, viper.DecodeHook(mapstructure.TextUnmarshallerHookFunc()))
if err != nil {
return fmt.Errorf("failed to unmarshal configuration: %w", err)
}
return nil
}
func evaluateConfigWithEnvToTmp(configPath string) (string, error) {
tmp, err := os.CreateTemp("./", "*.yaml")
if err != nil {
return "", fmt.Errorf("unable to create a temp config file: %w", err)
}
cfile, err := os.Open(configPath)
if err != nil {
return "", fmt.Errorf("unable to open %s: %w", configPath, err)
}
_, err = evaluateConfigWithEnv(cfile, tmp)
if err != nil {
return "", fmt.Errorf("unable to populate the environment: %w", err)
}
return tmp.Name(), nil
}
func envToMap() map[string]string {
envMap := make(map[string]string)
for _, v := range os.Environ() {
s := strings.SplitN(v, "=", 2)
if len(s) != 2 {
continue
}
envMap[s[0]] = s[1]
}
return envMap
}
// evaluateConfigWithEnv reads a configuration reader and injects environment variables
// that exist as part of the configuration in the form a go template. For example
// {{.ENV_VAR1}} will be replace with the value of the environment variable ENV_VAR1.
// Optional support for writting the contents to other places is supported by providing
// other writers. By default, the evaluated configuartion is returned as a reader.
func evaluateConfigWithEnv(configFile io.Reader, writers ...io.Writer) (io.Reader, error) {
envMap := envToMap()
b, err := io.ReadAll(configFile)
if err != nil {
return nil, fmt.Errorf("unable to read the config file: %w", err)
}
t := template.New("appConfigTemplate").Option("missingkey=zero")
tmpl, err := t.Parse(string(b))
if err != nil {
return nil, fmt.Errorf("unable to parse template from: \n%s: %w", string(b), err)
}
populated := []byte{}
buff := bytes.NewBuffer(populated)
writers = append(writers, buff)
err = tmpl.Execute(io.MultiWriter(writers...), envMap)
if err != nil {
return nil, fmt.Errorf("unable to execute template: %w", err)
}
return buff, nil
}
func getAppEnv() string {
env := os.Getenv("APP_ENV")
if env == "" {
env = os.Getenv("DEPLOYMENT_STAGE")
}
return env
}
func validateConfiguration[T any](cfg *T) error {
validate := validator.New()
err := validate.Struct(*cfg)
if err != nil {
errSlice := &validator.ValidationErrors{}
errors.As(err, errSlice)
return errSlice
}
return nil
}