Viper failing to create default config when config doesn't exist

61 views Asked by At

I am trying to create a default configuration file with viper if it doesn't already exist.

However, I am at a loss because viper seems to need this file to already exist.

I get the following error message:

Error writing config file: open /Users/zrbecker/.appname/config.yaml: no such file or directory

Here is the code I am trying to use.

func main() {
    viper.SetConfigName("config")
    viper.SetConfigType("yaml")

    homeDir, err := os.UserHomeDir()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error getting home directory: %v\n", err)
        os.Exit(1)
    }

    configPath := filepath.Join(homeDir, ".appname")
    configFilePath := filepath.Join(configPath, "config.yaml")

    if err := os.MkdirAll(configPath, 0755); err != nil {
        fmt.Fprintf(os.Stderr, "Unable to create config directory: %v\n", err)
        os.Exit(1)
    }

    if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
        if err := viper.SafeWriteConfigAs(configFilePath); err != nil {
            fmt.Fprintf(os.Stderr, "Error writing config file: %v\n", err)
            os.Exit(1)
        }
    }
}
0

There are 0 answers