-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
97 lines (83 loc) · 1.81 KB
/
option.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
package conf
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/lafrinte/nops/fs"
"github.com/rs/zerolog/log"
"path/filepath"
"strings"
)
type Option func(c *Config)
func WithAllowEmptyEnv() Option {
return func(c *Config) {
c.viper.AllowEmptyEnv(true)
}
}
func WithEnvKeyReplacer(r *strings.Replacer) Option {
return func(c *Config) {
c.viper.SetEnvKeyReplacer(r)
}
}
func WithAutomaticEnv() Option {
return func(c *Config) {
c.viper.AutomaticEnv()
}
}
func WithBindEnv(envs map[string]string) Option {
return func(c *Config) {
for n, v := range envs {
_ = c.viper.BindEnv(n, v)
}
}
}
func WithOptionConfigPath(path []string) Option {
return func(c *Config) {
for _, p := range path {
c.viper.AddConfigPath(p)
}
}
}
func WithConfigName(in string) Option {
return func(c *Config) {
c.viper.SetConfigName(in)
}
}
func WithConfigType(in string) Option {
return func(c *Config) {
c.viper.SetConfigType(in)
}
}
func WithFsNotify() Option {
return func(c *Config) {
c.viper.WatchConfig()
c.viper.OnConfigChange(func(event fsnotify.Event) {
log.Info().Str("action", "conf").Msg(fmt.Sprintf("conf changed: %s", event))
})
}
}
func WithTemplate(template string) Option {
return func(c *Config) {
c.Template = strings.Replace(template, "\t", " ", -1)
}
}
func WriteTemplateFromFile(path string) Option {
return func(c *Config) {
if s, err := fs.ReadFile(path); err == nil {
c.Template = strings.Replace(s, "\t", " ", -1)
}
}
}
func WithWriteTo(path string) Option {
return func(c *Config) {
c.WriteTo = path
dir, file := filepath.Split(path)
c.viper.AddConfigPath(dir)
c.viper.SetConfigName(file)
}
}
// WithDefaultVal is used to set the conf struct unmarshalling to
func WithDefaultVal(i interface{}) Option {
return func(c *Config) {
c.DefaultVal = i
}
}