【问题标题】:Trouble using Cobra/Viper使用 Cobra/Viper 遇到问题
【发布时间】:2019-12-05 18:18:06
【问题描述】:

我无法同时使用 Cobra 和 Viper。这就是我正在做的:

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()
}

我正在尝试在我的子命令(log.Cmd(&options) 中添加的命令)中检索值 options.Password,但是该字段没有被填充。我很确定我正确地关注 Cobra 文档:https://github.com/spf13/cobra#create-rootcmd

【问题讨论】:

    标签: go go-cobra


    【解决方案1】:

    将 cobra 标志绑定到 viper 选项只会将 cobra 标志绑定到 viper 选项,反之亦然。因此您可以通过

    访问密码
    pass := viper.GetString("password")
    

    如果密码是通过 viper 或 cobra 设置的,但不是通过标志定义中定义的变量。

    基本上,您在这里有两个选择:要么使用 cobra 而不将标志指向变量,然后通过对 viper.Get* 的各种调用来设置全局变量(您甚至可以在处理它们时对其进行消毒),或者使用 viper作为一种“参数注册表”并在需要时调用viper.Get*。我倾向于使用前一种解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-25
      • 1970-01-01
      • 2011-07-29
      • 2012-03-29
      • 2013-05-19
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多