go - cobra 和 viper 的配置文件

标签 go viper-go go-cobra

基本信息:我创建了一个 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/

相关文章:

go - 从 viper 配置文件中删除键值对

go - 如何使 Viper 中的配置字段成为必需?

go - go-viper 的多个配置文件

unit-testing - 如何在 go 中实现 CLI 命令的单元测试

string - 将 "=?UTF 8?.."(RFC 2047) 转换为 golang 中的常规字符串

reactjs - 从 URL 中的前端 ReactJS 检索 Golang 服务器中的表单值

没有参数匹配的 golang cobra 子命令

go - 如何将 Viper 配置值解码为正确包含字符串数组的结构?

go - 返回 &obj 是什么意思?对等式检查有什么影响

go - 如何将时区信息添加到现有 time.Time