基本信息:我创建了一个 go 应用程序并使用了 Cobra。 Cobra 使用 Viper 作为命令行参数和标志。
我有一个带有标志绑定(bind)的命令监听,我想在 yaml 文件中配置它。
代码:
listen 命令的初始化函数如下所示:
func init() {
RootCmd.AddCommand(listenCmd)
listenCmd.Flags().StringP("bind", "b", ":50051", "Provide bind definition")
viper.BindPFlag("bind", listenCmd.Flags().Lookup("bind"))
}
我的申请代码在 https://github.com/sascha-andres/go-logsink
问题:
当我使用 listen --bind "bla"
调用应用程序时,标志被正确设置为 bla
,但我还没有找到使用YAML 文件位于我的主目录中。
尝试的配置文件:
---
connect:
bind: "bla"
和
---
bind: "bla"
在这两种情况下都找到了配置文件,但标志不是预期值而是默认值。
我必须如何编写配置文件才能正确填充标志?
最佳答案
好的,感谢您提供的额外信息,帮助很大!
问题
问题出在您检索标志值的方式上。这是您目前拥有的:
bind := cmd.Flag("bind").Value.String()
fmt.Printf("Binding definition provided: %s\n", bind)
server.Listen(bind)
当用 viper 绑定(bind)标志时,根据以下优先级,实际上 viper 将保存最终值:
1. If present, use the flag value
2. Else, use the value from the config file
3. Else, use the default flag value
您的问题是您是从命令的标志集中检索标志值,而不是从 viper 中检索标志值。
行为
这是我测试的代码:
bind := cmd.Flag("bind").Value.String()
fmt.Printf("Binding definition provided: %s\n", bind)
fmt.Printf("Binding definition provided from viper: %s\n", viper.GetString("bind"))
没有绑定(bind)配置参数:
$ go-logsink listen
Using config file: /xxx/.go-logsink.yaml
Binding definition provided: :50051
Binding definition provided from viper: :50051
将绑定(bind)配置参数设置为“bla”(未嵌套,第二个配置文件):
$ go-logsink listen
Using config file: /xxx/.go-logsink.yaml
Binding definition provided: :50051
Binding definition provided from viper: bla
将绑定(bind)配置参数设置为“bla”(非嵌套,第二个配置文件)和一个显式标志:
$ go-logsink listen --bind ":3333"
Using config file: /xxx/.go-logsink.yaml
Binding definition provided: :3333
Binding definition provided from viper: :3333
底线:将您的标志与 viper 绑定(bind)时,请使用 viper 检索它们。
附加说明:在您的自述文件中,生成 grpc 兼容代码的正确方法是将 grpc 插件添加到 protobuf 生成:protoc --go_out=plugins=grpc:。 *.proto
关于go - cobra 和 viper 的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41578264/