为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Cobra/Viper 时出现问题

使用 Cobra/Viper 时出现问题

Go
一只甜甜圈 2023-08-07 19:09:21
我在同时使用 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 pathfunc 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()}我正在尝试在子命令( 中添加的命令)中检索值 options.Passwordlog.Cmd(&options)但未填充该字段。我很确定我正确遵循了 Cobra 文档: https: //github.com/spf13/cobra#create-rootcmd
查看完整描述

1 回答

?
UYOU

TA贡献1878条经验 获得超4个赞

将 cobra 标志绑定到 viper 选项只会将 cobra 标志绑定到 viper 选项,反之亦然。所以您可以通过以下方式访问密码

pass := viper.GetString("password")

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

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


查看完整回答
反对 回复 2023-08-07
  • 1 回答
  • 0 关注
  • 74 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信