-
Notifications
You must be signed in to change notification settings - Fork 2
/
config.go
83 lines (66 loc) · 2.21 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
package igconfig
import (
"context"
"errors"
"fmt"
"github.com/rs/zerolog/log"
"github.com/worldline-go/igconfig/internal"
"github.com/worldline-go/igconfig/loader"
)
// DefaultLoaders is a list of default loaders to use.
var DefaultLoaders = []loader.Loader{
&loader.Default{},
&loader.Consul{},
&loader.Vault{},
&loader.File{},
&loader.Env{},
&loader.Flags{},
}
// LoadConfig loads a configuration struct from loaders.
func LoadConfig(appName string, c interface{}) error {
return LoadConfigWithContext(context.Background(), appName, c)
}
// LoadConfigWithContext loads a configuration struct from a fileName, the environment and finally from
// command-line parameters (the latter override the former) into a config struct.
// This is a convenience function encapsulating all individual loaders specified in DefaultLoaders.
func LoadConfigWithContext(ctx context.Context, appName string, c interface{}) error {
return LoadWithLoadersWithContext(ctx, appName, c, DefaultLoaders...)
}
// LoadWithLoaders loads a configuration struct from a loaders.
func LoadWithLoaders(appName string, configStruct interface{}, loaders ...loader.Loader) error {
return LoadWithLoadersWithContext(context.Background(), appName, configStruct, loaders...)
}
// LoadWithLoadersWithContext uses provided Loader's to fill 'configStruct'.
func LoadWithLoadersWithContext(ctx context.Context, appName string, configStruct interface{}, loaders ...loader.Loader) error {
for _, configLoader := range loaders {
select {
case <-ctx.Done():
return nil
default:
}
err := configLoader.LoadWithContext(ctx, appName, configStruct)
if err == nil {
continue
}
if errors.Is(err, loader.ErrNoClient) {
log.Ctx(ctx).Warn().
Str("loader", fmt.Sprintf("%T", configLoader)).
Msgf("%v, skipping", err)
continue
}
if internal.IsLocalNetworkError(err) {
log.Ctx(ctx).Warn().
Str("loader", fmt.Sprintf("%T", configLoader)).
Msg("local server is not available, skipping")
continue
}
if errors.Is(err, loader.ErrNoConfFile) {
log.Ctx(ctx).Warn().
Str("loader", fmt.Sprintf("%T", configLoader)).
Msgf("%v, skipping", err)
continue
}
return fmt.Errorf("%T: %w", configLoader, err)
}
return nil
}