Hi,
How can i export loaded config (with ie. override some parts of it using ENV or CLI args) back to original or even different config file?
+1 option for writing config back to a file would be great
Nevermind, i've just wrote a simple function which saves everything to a file:
type config struct {
DataDir string
Debug bool
Devel bool
ApiKey string
SnatchFolder string
Port int
TvdbUrl string
TvdbKey string
LogJSON bool
FirstRun bool
}
var C config
func saveConfig(cfgpath string) error {
viper.Marshal(&C)
b, err := json.MarshalIndent(C, "", " ")
if err != nil {
return err
}
f, err := os.Create(cfgpath)
if err != nil {
return err
}
defer f.Close()
f.WriteString(string(b))
return nil
}
I feel like this would be a huge gain for viper. I would love to be able to modify the configuration and save it back. Viper already knows which file type was loaded and how to format that language.
Needing this feature, too, I have opened PR #287. Once complete, writing will be available.
@theherk @spf13 It looks like this issue can be closed now that #287 is complete. Although it would be nice if the functionality was documented. I didn't see anything about it in the README.md.
Excellent point. I'll make sure the documentation for this feature set is ship shape this week.
@theherk Thanks for the work you did on this feature. It saved me time writing my own!!
Great to see this functionality available. But it is really missing from the main README.md!
There is no viper.Marshal() method at https://github.com/spf13/viper/blob/master/viper.go
What am I doing wrong? :)
There is no viper.Marshal() method at https://github.com/spf13/viper/blob/master/viper.go
What am I doing wrong? :)
I believe it's actually supposed to be viper.Unmarshal(). The idea being that you save everything to the struct (Unmarshal is a good way of getting the "final" values if you have multiple sources) and then writing it all to JSON.
@f1mishutka since my comment is from 2015 here's a link to the version i was using at the time: https://github.com/spf13/viper/blob/d8f2aa78d42b618f51e668d0b7e05fe203f889de/viper.go#L314 as you might see there are a shitload of changes made since then. I guess it has been renamed to Unmarshal but since WriteConfig has been implemented a while ago, id recommend using this instead ;)
Most helpful comment
Nevermind, i've just wrote a simple function which saves everything to a file: