-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloader.go
66 lines (54 loc) · 1.27 KB
/
loader.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
package config
import (
"context"
"log"
"github.com/heetch/confita"
"github.com/heetch/confita/backend"
"github.com/heetch/confita/backend/flags"
"github.com/etf1/go-config/dotenv"
"github.com/etf1/go-config/env"
)
type Loader struct {
backends []backend.Backend
}
func (cb *Loader) AppendBackends(backends ...backend.Backend) *Loader {
cb.backends = append(cb.backends, backends...)
return cb
}
func (cb *Loader) PrependBackends(backends ...backend.Backend) *Loader {
cb.backends = append(backends, cb.backends...)
return cb
}
func (cb *Loader) Load(ctx context.Context, to interface{}) error {
for _, b := range cb.backends {
if b != nil {
err := confita.NewLoader(b).Load(ctx, to)
if err != nil {
return err
}
}
}
return nil
}
func (cb *Loader) LoadOrFatal(ctx context.Context, to interface{}) {
if err := cb.Load(ctx, to); err != nil {
log.Fatal(err)
}
}
func NewConfigLoader(backends ...backend.Backend) *Loader {
return &Loader{backends: backends}
}
/*
* Create Loader preconfigured with:
* - .env file loader if file exist
* - environment variable loader
* - flags loader
*/
func NewDefaultConfigLoader() *Loader {
return NewConfigLoader(
dotenv.GetBackendsFromFlag()...
).AppendBackends(
env.NewBackend(),
flags.NewBackend(),
)
}