-
Notifications
You must be signed in to change notification settings - Fork 12
/
config.go
61 lines (54 loc) · 1.78 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
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
package config
import "reflect"
// Config is a common interface for configuration objects that may be used by Loader.
type Config interface {
SetProviderDefaults(dp DataProvider)
Set(dp DataProvider) error
}
// KeyPrefixProvider is an interface for providing key prefix that will be used for configuration parameters.
type KeyPrefixProvider interface {
KeyPrefix() string
}
// CallSetProviderDefaultsForFields finds all initialized (non-nil) fields of the passed object
// that implement Config interface and calls SetProviderDefaults() method for each of them.
func CallSetProviderDefaultsForFields(obj interface{}, dp DataProvider) {
el := reflect.ValueOf(obj).Elem()
for i := 0; i < el.NumField(); i++ {
v := el.Field(i).Interface()
if reflect.ValueOf(v).Kind() == reflect.Ptr && reflect.ValueOf(v).IsNil() {
continue
}
if c, ok := v.(Config); ok {
cDp := dp
if kpDp, ok := v.(KeyPrefixProvider); ok && kpDp.KeyPrefix() != "" {
cDp = NewKeyPrefixedDataProvider(dp, kpDp.KeyPrefix())
}
c.SetProviderDefaults(cDp)
}
}
}
// CallSetForFields finds all initialized (non-nil) fields of the passed object
// that implement Config interface and calls Set() method for each of them.
func CallSetForFields(obj interface{}, dp DataProvider) error {
el := reflect.ValueOf(obj).Elem()
for i := 0; i < el.NumField(); i++ {
v := el.Field(i).Interface()
if reflect.ValueOf(v).Kind() == reflect.Ptr && reflect.ValueOf(v).IsNil() {
continue
}
if c, ok := v.(Config); ok {
cDp := dp
if kpDp, ok := v.(KeyPrefixProvider); ok && kpDp.KeyPrefix() != "" {
cDp = NewKeyPrefixedDataProvider(dp, kpDp.KeyPrefix())
}
if err := c.Set(cDp); err != nil {
return err
}
}
}
return nil
}