mirror of
https://github.com/spf13/viper
synced 2024-12-23 12:07:02 +00:00
Added functionality to export configuration based on config type. The feature supports JSON and TOML.
This commit is contained in:
parent
48e0b61d8c
commit
d5c009456e
1 changed files with 19 additions and 5 deletions
20
viper.go
20
viper.go
|
@ -22,6 +22,7 @@ package viper
|
|||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
|
@ -880,7 +881,7 @@ func (v *Viper) InConfig(key string) bool {
|
|||
func SaveConfig() error { return v.SaveConfig() }
|
||||
func (v *Viper) SaveConfig() error {
|
||||
|
||||
jww.INFO.Println("Attempting to write config into the file")
|
||||
jww.INFO.Println("Attempting to write config into the file.")
|
||||
if !stringInSlice(v.getConfigType(), SupportedExts) {
|
||||
return UnsupportedConfigError(v.getConfigType())
|
||||
}
|
||||
|
@ -892,12 +893,23 @@ func (v *Viper) SaveConfig() error {
|
|||
return err
|
||||
}
|
||||
|
||||
w := bufio.NewWriter(f)
|
||||
switch v.getConfigType() {
|
||||
case "json":
|
||||
|
||||
b, err := json.MarshalIndent(v.AllSettings(), "", " ")
|
||||
if err != nil {
|
||||
jww.FATAL.Println("Panic while encoding into JSON format.")
|
||||
}
|
||||
f.WriteString(string(b))
|
||||
|
||||
case "toml":
|
||||
|
||||
w := bufio.NewWriter(f)
|
||||
if err := toml.NewEncoder(w).Encode(v.AllSettings()); err != nil {
|
||||
jww.FATAL.Println("Panic while writing into the file")
|
||||
jww.FATAL.Println("Panic while encoding into TOML format.")
|
||||
}
|
||||
w.Flush()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
@ -930,6 +942,8 @@ func (v *Viper) ReadInConfig() error {
|
|||
return UnsupportedConfigError(v.getConfigType())
|
||||
}
|
||||
|
||||
jww.DEBUG.Println("Reading file: ", v.getConfigFile())
|
||||
|
||||
file, err := ioutil.ReadFile(v.getConfigFile())
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
Loading…
Reference in a new issue