我在同時使用 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*
。我傾向于使用前一種解決方案。
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消