-
Notifications
You must be signed in to change notification settings - Fork 0
/
viper.go
62 lines (49 loc) · 1.16 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
package xcm
import (
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
type Context struct {
*viper.Viper
}
func NewContext() *Context {
return &Context{Viper: viper.New()}
}
func LoadConfigFileWithContext(filename string, ctx *Context) error {
if ctx == nil {
ctx = &Context{Viper: viper.GetViper()}
}
ctx.SetConfigFile(filename)
if err := ctx.ReadInConfig(); err != nil {
return err
}
return nil
}
func LoadConfigFile(filename string) error {
return LoadConfigFileWithContext(filename, nil)
}
func MapToStructWithContext[T any](ctx *Context) (*T, error) {
if ctx == nil {
ctx = &Context{Viper: viper.GetViper()}
}
t := new(T)
if err := ctx.Unmarshal(t); err != nil {
return nil, err
}
return t, nil
}
func MapToStruct[T any]() (*T, error) {
return MapToStructWithContext[T](nil)
}
func BeginWatchConfigWithContext(cb func(), ctx *Context) {
if ctx == nil {
ctx = &Context{Viper: viper.GetViper()}
}
merger := NewTimeoutBasedMerger[fsnotify.Event]()
onEvent := merger.Start(func([]*fsnotify.Event) { cb() })
ctx.OnConfigChange(onEvent)
ctx.WatchConfig()
}
func BeginWatchConfig(cb func()) {
BeginWatchConfigWithContext(cb, nil)
}