亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 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 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號