[英]Trouble using Cobra/Viper
我在同時使用 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
將眼鏡蛇標志綁定到毒蛇選項只會將眼鏡蛇標志綁定到毒蛇選項,反之亦然。 所以你可以通過訪問密碼
pass := viper.GetString("password")
如果密碼是通過 viper 或 cobra 設置的,但不是通過標志定義中定義的變量設置的。
基本上,您在這里有兩個選擇:要么使用 cobra 而不將標志指向變量,然后通過對viper.Get*
各種調用設置全局變量(您甚至可以在使用時對其進行消毒),或者使用 viper 作為排序“參數注冊表”,並在需要時調用viper.Get*
。 我傾向於采用前一種解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.