为什么眼镜蛇不读取我的配置文件

del*_*lta 4 go cobra viper-go

眼镜蛇和毒蛇中的文档使我感到困惑。我做了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")
}
Run Code Online (Sandbox Code Playgroud)

我的配置文件看起来像这样...

---
foo: aFooString
Run Code Online (Sandbox Code Playgroud)

当我打电话给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:
Run Code Online (Sandbox Code Playgroud)

当我打电话时go run main.go bar看到了...

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

fooString is:
Run Code Online (Sandbox Code Playgroud)

因此它正在使用配置文件,但似乎没有人正在阅读它,也许我误解了眼镜蛇和vi蛇的工作方式,有什么想法吗?

min*_*oyo 6

结合spf13/cobraspf13/viper

首先用眼镜蛇定义标志:

RootCmd.PersistentFlags().StringP("foo", "", "loaded from config")
Run Code Online (Sandbox Code Playgroud)

用毒蛇绑定它:

viper.BindPFlag("foo", RootCmd.PersistentFlags().Lookup("foo"))
Run Code Online (Sandbox Code Playgroud)

并通过毒蛇的方法获取变量:

fmt.Println("fooString is: ", viper.GetString("foo"))
Run Code Online (Sandbox Code Playgroud)

  • 这种方法有效,但我认为问题指向了一个我也没有弄清楚的问题:OP使用StringVar而不是StringP来获取传递给它的字符串指针中设置的值。链接在一起的Cobra和Viper似乎不会将值传播到那些传递的值指针中。如果任何人都可以提供如何进行该工作的指示,请随时发布另一个答案。 (3认同)

WGH*_*WGH 5

由于 Viper 值在某种程度上不如 pflags(例如,不支持自定义数据类型),因此我对“使用 Viper 检索值”的答案不满意,最终编写了小型帮助程序类型以将值放回 pflags 中。

type viperPFlagBinding struct {
        configName string
        flagValue  pflag.Value
}

type viperPFlagHelper struct {
        bindings []viperPFlagBinding
}

func (vch *viperPFlagHelper) BindPFlag(configName string, flag *pflag.Flag) (err error) {
        err = viper.BindPFlag(configName, flag)
        if err == nil {
                vch.bindings = append(vch.bindings, viperPFlagBinding{configName, flag.Value})
        }
        return
}

func (vch *viperPFlagHelper) setPFlagsFromViper() {
        for _, v := range vch.bindings {
                v.flagValue.Set(viper.GetString(v.configName))
        }
}


func main() {
        var rootCmd = &cobra.Command{}
        var viperPFlagHelper viperPFlagHelper

        rootCmd.PersistentFlags().StringVar(&config.Password, "password", "", "API server password (remote HTTPS mode only)")
        viperPFlagHelper.BindPFlag("password", rootCmd.Flag("password"))

        rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
                err := viper.ReadInConfig()
                if err != nil {
                        if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
                                return err
                        }
                }

                viperPFlagHelper.setPFlagsFromViper()

                return nil
        }
}
Run Code Online (Sandbox Code Playgroud)