我无法同时使用 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()
}
我正在尝试在我的子命令中检索值 options.Password (在 中添加的命令log.Cmd(&options)
)但是该字段没有被填充。我很确定我正确地关注 Cobra 文档:https ://github.com/spf13/cobra#create-rootcmd