小编典典

为什么Cobra无法读取我的配置文件?

go

Cobra和Viper中的文档使我感到困惑。我做了cobra init fooproject,然后在项目目录中做了cobra add bar。我有一个PersistentFlag名为foo,这里是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:

因此它正在使用配置文件,但是似乎没有人正在读取它。也许我误解了眼镜蛇和毒蛇的工作方式。有任何想法吗?


阅读 737

收藏
2020-07-02

共2个答案

小编典典

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

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

与Viper绑定:

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

并通过Viper方法获取变量:

fmt.Println("fooString is: ", viper.GetString("foo"))
2020-07-02
mattyou

一开始也比较懵,看文档也没有说明。cobra和viper的结合,可以理解为:不是viper到flag的传值,而是flag到viper的传值,所以viper绑定时候,是使用viper的Getxxx()函数取值,如果flag设置了值,viper取到的是flag设置的值,如果没有设置flag,取到就是配置文件的值。

2020-09-30