简体   繁体   English

使用 Cobra/Viper 时遇到问题

[英]Trouble using Cobra/Viper

I'm having trouble using Cobra and Viper together.我在同时使用 Cobra 和 Viper 时遇到问题。 This is what I'm doing:这就是我正在做的:

var options util.Config = util.Config{}
var rootCmd = &cobra.Command{
    Use:   "test [command] [subcommands]",
    Run: func(cmd *cobra.Command, args []string) {
        if err := server.Run(); err != nil {
            l.Fatal(err)
        }
    },
}

// initConfig helps initialise configuration with a stated path
func initConfig() {
    if options.Path != "" {
        viper.SetConfigFile(options.Path)
    }
    viper.AutomaticEnv()
    if err := viper.ReadInConfig(); err != nil {
        fmt.Println("Could not use config file: ", viper.ConfigFileUsed())
    }
}

func init() {
    cobra.OnInitialize(initConfig)
    rootCmd.PersistentFlags().StringVarP(&options.Path, "config", "n", "", "Path of a configuration file")
    rootCmd.PersistentFlags().StringVarP(&options.Password, "password", "d", "", "Password to access the server")
    viper.BindPFlag("password", rootCmd.PersistentFlags().Lookup("password"))
    rootCmd.AddCommand(log.Cmd(&options))
}

func main() {
    rootCmd.Execute()
}

I'm trying to retrieve the value options.Password within my subcommand (an added command within log.Cmd(&options) ) however the field isn't being populated.我正在尝试在我的子命令( log.Cmd(&options)添加的命令)中检索值 options.Password 但是该字段没有被填充。 I'm pretty sure I'm following the Cobra docs properly: https://github.com/spf13/cobra#create-rootcmd我很确定我正在正确地遵循 Cobra 文档: https : //github.com/spf13/cobra#create-rootcmd

Binding cobra flags to viper options only binds cobra flags to viper options, not vice versa.将眼镜蛇标志绑定到毒蛇选项只会将眼镜蛇标志绑定到毒蛇选项,反之亦然。 So you can access the password via所以你可以通过访问密码

pass := viper.GetString("password")

if the password is set either via viper or cobra, but not via the variables defined in your flag definitions.如果密码是通过 viper 或 cobra 设置的,但不是通过标志定义中定义的变量设置的。

Basically, you have two options here: Either you use cobra without pointing your flags to variables, and then set your globals via various calls to viper.Get* (you can even sanitize them while being at it), or you use viper as sort of a „parameter registry“ and call viper.Get* where needed.基本上,您在这里有两个选择:要么使用 cobra 而不将标志指向变量,然后通过对viper.Get*各种调用设置全局变量(您甚至可以在使用时对其进行消毒),或者使用 viper 作为排序“参数注册表”,并在需要时调用viper.Get* I tend to go with the former solution.我倾向于采用前一种解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM