-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
viper.go
239 lines (206 loc) · 6.57 KB
/
viper.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright (c) 2021 Patrick Ascher <development@fullhouse-productions.com>. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
// Package viper provides a wrapper for the https://github.com/spf13/viper package.
// It offers a different callback function, to get access to the viper instance.
// By default, the watcher will automatically unmarshal the data of the defined configuration struct.
// TODO: add remote features
package viper
import (
"errors"
"fmt"
"github.com/mitchellh/mapstructure"
"log"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"sync"
"github.com/fsnotify/fsnotify"
"github.com/patrickascher/gofer/config"
"github.com/patrickascher/gofer/registry"
"github.com/spf13/viper"
)
var mutex sync.Mutex
// init registers the viper provider.
func init() {
err := registry.Set(config.VIPER, new(viperProvider))
if err != nil {
log.Fatal(err)
}
}
// Error messages
var (
ErrOptions = errors.New("viper-provider: options must be of type viper.Options")
ErrMandatory = errors.New("viper-provider: viper.Options file-name, path and type are mandatory")
)
// Options for the viper provider.
type Options struct {
// FileName of the configuration.
FileName string
// FileType optional if the filename has no extension.
FileType string
// FilePath to look into.
FilePath string
// Watch for file changes.
Watch bool
// WatchCallback can be defined.
// By default, the config struct gets updated on changes.
WatchCallback func(cfg interface{}, viper *viper.Viper, e fsnotify.Event)
// EnvPrefix
EnvPrefix string
// EnvAutomatic check if environment variables match any of the existing keys.
EnvAutomatic bool
// EnvBind binds a Viper key to a ENV variable.
EnvBind []string
}
// vInstances of vipers.
// Mapping key is the absolute filepath, because this is the only argument of the viper watch-callback function.
var vInstances map[string]vInstance
// vInstance with the configuration and options.
// Needed for the callbacks, because of limits of the standard viper callback arguments.
type vInstance struct {
viper *viper.Viper
cfg interface{}
options Options
}
// viper struct to satisfy the config.Interface.
type viperProvider struct{}
// Parse will configure viper and unmarshal the config into the config struct.
// If Options.Watch is activated, the configuration will automatically be updated on file changes.
// An additional callback can be added.
// Filename,path and type are mandatory.
func (vp *viperProvider) Parse(cfg interface{}, opt interface{}) error {
// check if the options have the correct type.
if _, ok := opt.(Options); !ok {
return ErrOptions
}
options := opt.(Options)
// mandatory fields
if options.FileName == "" || options.FilePath == "" || options.FileType == "" {
return ErrMandatory
}
// create/get viper instance
i, err := instance(cfg, options)
if err != nil {
return fmt.Errorf("viper-provider: %w", err)
}
// add configurations
i.viper.SetConfigName(options.FileName)
i.viper.AddConfigPath(options.FilePath)
i.viper.SetConfigType(options.FileType)
// By default, the config will be updated on file change.
// If there is a custom function, it will be called as well.
if options.WatchCallback != nil {
i.viper.OnConfigChange(func(e fsnotify.Event) {
mutex.Lock()
if i, ok := vInstances[e.Name]; ok {
_ = i.viper.Unmarshal(i.cfg)
vInstances[e.Name].options.WatchCallback(vInstances[e.Name].cfg, vInstances[e.Name].viper, e)
}
mutex.Unlock()
})
} else {
i.viper.OnConfigChange(func(e fsnotify.Event) {
mutex.Lock()
if i, ok := vInstances[e.Name]; ok {
_ = i.viper.Unmarshal(i.cfg)
}
mutex.Unlock()
})
}
// add file watcher, goroutine will be spawned.
if options.Watch {
i.viper.WatchConfig()
}
// add env prefix.
if options.EnvPrefix != "" {
i.viper.SetEnvPrefix(options.EnvPrefix)
}
// add env bindings.
if len(options.EnvBind) != 0 {
// no error can happen because we are already checking the length.
_ = i.viper.BindEnv(options.EnvBind...)
}
// set env automatism.
if options.EnvAutomatic {
i.viper.AutomaticEnv()
}
// read config.
err = i.viper.ReadInConfig()
if err != nil {
return err
}
// unmarshal
err = i.viper.Unmarshal(&cfg)
// automaticEnv and unmarshal do not take care of slices example (Databases.0.Port).
// this is a solution for string and int only for the depth 1 for slices.
if options.EnvAutomatic {
// replacing env _ with a .
// this is needed because a . is not always allowed to set as env variable.
i.viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
decoderCfg := &mapstructure.DecoderConfig{
WeaklyTypedInput: true, // needed because env variables will be strings
Result: cfg,
}
decoder, err := mapstructure.NewDecoder(decoderCfg)
if err != nil {
panic(err)
}
err = decoder.Decode(i.viper.AllSettings())
if err != nil {
panic(err)
}
rvConfig := reflect.ValueOf(cfg).Elem()
for parent, v := range i.viper.AllSettings() {
rv := reflect.ValueOf(v)
if reflect.TypeOf(v).Kind() == reflect.Slice {
for index := 0; index < rv.Len(); index++ {
rf := rv.Index(index).Interface().(map[string]interface{})
for key := range rf {
c := rvConfig.FieldByName(strings.Title(parent)).Index(index).FieldByName(strings.Title(key))
if c.CanSet() {
switch c.Type().Kind() {
case reflect.String:
c.Set(reflect.ValueOf(i.viper.GetString(strings.ToUpper(parent + "." + strconv.Itoa(index) + "." + key))))
case reflect.Int:
c.Set(reflect.ValueOf(i.viper.GetInt(strings.ToUpper(parent + "." + strconv.Itoa(index) + "." + key))))
}
}
}
}
}
}
}
return err
}
// instance will check if there is already a viper instance for the given filepath.
// If so, the instance *cfg and options will be updated. Otherwise a new instance will be created.
func instance(cfg interface{}, opt Options) (vInstance, error) {
if vInstances == nil {
vInstances = make(map[string]vInstance)
}
// get absolute path and check if file exist.
name, err := filepath.Abs(opt.FilePath + "/" + opt.FileName)
if err != nil {
return vInstance{}, err
}
_, err = os.Stat(name)
if err != nil {
return vInstance{}, err
}
// create an instance if it does not exist yet.
if _, ok := vInstances[name]; !ok {
vInstances[name] = vInstance{options: opt, cfg: cfg, viper: viper.New()}
} else {
mutex.Lock()
// re-assign *cfg and config on multiple call.
v := vInstances[name]
v.cfg = cfg
v.options = opt
vInstances[name] = v
mutex.Unlock()
}
return vInstances[name], nil
}