我正试图编写一个只有一个命令的应用程序,因此,我想我可以跳过眼镜蛇。
应用程序应该能够支持所有类型的配置:
我用的是毒蛇,但我无法用它来读我的cli params。
v := viper.New()
viper.SetConfigName("config")
viper.AddConfigPath(".")
v.SetDefault(pathKey, defaultPath)
fs := pflag.NewFlagSet("app", pflag.ExitOnError)
fs.String(pathKey, defaultPath, "Default path")
fs.StringSlice(wordsKey, []string{""}, "Words")
fs.String(loglevelKey, "info", "Log level")
if err := v.BindPFlags(fs); err != nil {
fmt.Println(err)
os.Exit(1)
}
if err := fs.Parse(os.Args[1:]); err != nil {
fmt.Println(err)
os.Exit(1)
}
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
fmt.Println("no conf file") //ignore, it can be either cli params, or conf file
}
var c conf
if err := v.Unmarshal(&c); err != nil {
fmt.Println(err)
os.Exit(1)
}
但我从来没有让那些人进入建筑。在v
之前打印Unmarshal
没有显示我提供的任何cli参数。
我遗漏了什么?我需要用眼镜蛇做这个吗?还是必须手动将每个标记(例如fs.String(pathKey, defaultPath, "Default path")
)分配给配置结构?
发布于 2022-01-11 20:50:54
为了子孙后代,我想我发现了一个问题:
我的conf
结构没有像标志那样有对应的键名。例如,当字段名为json:"logLevel"
时,仅设置DisplayLogLevel是不够的,它必须是:
const (
pathKey = "path"
wordsKey = "words"
logLevelKey = "logLevel"
)
type conf struct {
Path string `json:"path"`
Words []string `json:"words"`
LogLevel string `json:"logLevel"`
}
发布于 2022-01-11 21:57:58
也许您必须设置配置类型。来自https://github.com/spf13/viper
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
https://stackoverflow.com/questions/70672896
复制相似问题