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
|
package util
import (
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
type ViperWrap struct {
cmd *cobra.Command
}
func WrapViper(cmd *cobra.Command, prefix string) *ViperWrap {
viper.SetEnvPrefix(prefix)
viper.AutomaticEnv()
return &ViperWrap{cmd}
}
func (v *ViperWrap) bindViper(name, short string, defaultv interface{}, help string) {
vname := strings.ReplaceAll(name, "-", "_")
viper.BindPFlag(vname, v.cmd.Flags().Lookup(name))
viper.SetDefault(vname, defaultv)
}
func (v *ViperWrap) BindString(name, short, defaultv, help string) *ViperWrap {
v.cmd.Flags().StringP(name, short, defaultv, help)
v.bindViper(name, short, defaultv, help)
return v
}
func (v *ViperWrap) BindBool(name, short string, defaultv bool, help string) *ViperWrap {
v.cmd.Flags().BoolP(name, short, defaultv, help)
v.bindViper(name, short, defaultv, help)
return v
}
|