Viper: SafeWriteConfig() fails if file does not exist

Created on 28 Jan 2018  路  3Comments  路  Source: spf13/viper

When calling viper.SafeWriteCofig() it fails with a file not found error.

Test code attached.

package main

import (
    "fmt"
    "os"

    "github.com/spf13/viper"
)

func main() {
    viper.AddConfigPath("/tmp")
    viper.SetConfigName("filename")
    viper.SetConfigType("yaml")
    viper.SetDefault("LogLevel", "Info")

    fmt.Println("Writing Config file!")
    err := viper.SafeWriteConfig()

    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }

    fmt.Println("wrote config file")
}

Output:

Writing Config file!
Config File "filename" Not Found in "[/tmp]"

Expected output:

Write Config file!
wrote config file

Most helpful comment

All 3 comments

+1

Currently the documentation for SafeWriteConfig is quite misleading 馃槄

SafeWriteConfig writes current configuration to file only if the file does not exist.

This is issue is also present for SafeWriteConfigAs

Use viper.SetConfigFile("filename.yaml") instead of viper.SetConfigName("filename") then SafeWriteConfig and SafeWriteConfigAs() will work

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xh3b4sd picture xh3b4sd  路  6Comments

GrapeBaBa picture GrapeBaBa  路  5Comments

akshaylb picture akshaylb  路  4Comments

therealfakemoot picture therealfakemoot  路  5Comments

gmaxwell94 picture gmaxwell94  路  5Comments