Чтение значения yaml с помощью Viper из проекта Cobra - PullRequest
0 голосов
/ 25 мая 2020

Попытка прочитать значение yaml, которое будет использоваться в init() для установки некоторых аргументов в rootCmd.SetArgs([]string{""})

Похоже, что это можно сделать только с помощью флагов кобры.

Знаете ли вы, как?

yaml:

debug: "true"
cmd: "server"
args:
    - "up"
    - "down"

cfgFile is empty evn есть файл в моем $ Home:

func initConfig() {
    if cfgFile != "" {
        // Use config file from the flag.
        viper.SetConfigFile(cfgFile)
    } else {
        // Find home directory.
        home, err := homedir.Dir()
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }

        // Search config in home directory with name ".gaz" (without extension).
        viper.AddConfigPath(home)
        viper.SetConfigName("my.yaml")
    }

    viper.AutomaticEnv() // read in environment variables that match

    // If a config file is found, read it in.
    if err := viper.ReadInConfig(); err == nil {
        fmt.Println("Using config file:", viper.ConfigFileUsed())
    }

    // conf := &config{}
    // err := viper.Unmarshal(conf)
    // if err != nil {
    //  fmt.Printf("unable to decode into config struct, %v", err)
    // }

}

Никакие значения не читаются следующие пусто:

rootCmd := &cobra.Command{
    Use: "app",
    Run: func(ccmd *cobra.Command, args []string) {

        fmt.Println("item exists?", viper.IsSet("debug"))
        fmt.Println("GetString  :", viper.GetString("debug"))
        fmt.Println("Keys       :", viper.AllKeys())
        fmt.Println("Settings   :", viper.AllSettings())
    },
}
...