go - 为什么 Cobra 不读取我的配置文件?

标签 go cobra viper-go

Cobra 和 Viper 中的文档让我感到困惑。我执行了 cobra init fooproject,然后在项目目录中执行了 cobra add bar。我有一个名为 fooPersistentFlag,这是来自 root 命令的 init 函数。

func Execute() {
    if err := RootCmd.Execute(); err != nil {
        fmt.Println(err)
        os.Exit(-1)
    }

    fmt.Println(cfgFile)
    fmt.Println("fooString is: ", fooString)
}


func init() {
    cobra.OnInitialize(initConfig)

    // Here you will define your flags and configuration settings.
    // Cobra supports Persistent Flags, which, if defined here,
    // will be global for your application.

    RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.fooproject.yaml)")
    RootCmd.PersistentFlags().StringVar(&fooString, "foo", "", "loaded from config")

    viper.BindPFlag("foo", RootCmd.PersistentFlags().Lookup("foo"))
    // Cobra also supports local flags, which will only run
    // when this action is called directly.
    RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

我的配置文件是这样的...

---
foo: aFooString

当我调用 go run main.go 时,我看到了这个...

A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.

Usage:
  fooproject [command]

Available Commands:
  bar         A brief description of your command
  help        Help about any command

Flags:
      --config string   config file (default is $HOME/.fooproject.yaml)
      --foo string      loaded from config
  -h, --help            help for fooproject
  -t, --toggle          Help message for toggle

Use "fooproject [command] --help" for more information about a command.

fooString is:

当我调用 go run main.go bar 时,我看到了这个...

Using config file: my/gopath/github.com/user/fooproject/.fooproject.yaml
bar called

fooString is:

所以它正在使用配置文件,但他们似乎都没有读取它。也许我误解了 Cobra 和 Viper 的工作方式。有什么想法吗?

最佳答案

要结合 spf13/cobraspf13/viper,首先用 Cobra 定义标志:

RootCmd.PersistentFlags().StringP("foo", "", "loaded from config")

用 Viper 绑定(bind)它:

viper.BindPFlag("foo", RootCmd.PersistentFlags().Lookup("foo"))

然后通过 Viper 的方法获取变量:

fmt.Println("fooString is: ", viper.GetString("foo"))

关于go - 为什么 Cobra 不读取我的配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43847791/

相关文章:

go - 忽略 "imported and not used"编译时错误

go - 通用函数中的Golang眼镜蛇命令标志未从cli获取值

go - 如何提取注册信息?

java - 已解析页面的 HTML

go - 使用 viper 验证配置文件

go - 字符串到二维 slice

tcp - 是否可以通过 websockets 或其他协议(protocol)传输 TCP 连接?

go - 如何从 Viper 访问数组中的特定项目

go - 使用 Viper Go 读取环境变量

go - Go 如何进行字符串比较?