mirror of
https://github.com/spf13/viper
synced 2025-05-06 20:27:17 +00:00
Added functionality to export configuration based on config type. The feature supports JSON and TOML.
This commit is contained in:
parent
985fae64ee
commit
71d6b8c96f
1 changed files with 18 additions and 5 deletions
23
viper.go
23
viper.go
|
@ -23,6 +23,7 @@ import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/csv"
|
"encoding/csv"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
|
@ -1073,7 +1074,7 @@ func (v *Viper) InConfig(key string) bool {
|
||||||
func SaveConfig() error { return v.SaveConfig() }
|
func SaveConfig() error { return v.SaveConfig() }
|
||||||
func (v *Viper) SaveConfig() error {
|
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) {
|
if !stringInSlice(v.getConfigType(), SupportedExts) {
|
||||||
return UnsupportedConfigError(v.getConfigType())
|
return UnsupportedConfigError(v.getConfigType())
|
||||||
}
|
}
|
||||||
|
@ -1085,12 +1086,23 @@ func (v *Viper) SaveConfig() error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
w := bufio.NewWriter(f)
|
switch v.getConfigType() {
|
||||||
|
case "json":
|
||||||
|
|
||||||
if err := toml.NewEncoder(w).Encode(v.AllSettings()); err != nil {
|
b, err := json.MarshalIndent(v.AllSettings(), "", " ")
|
||||||
jww.FATAL.Println("Panic while writing into the file")
|
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 encoding into TOML format.")
|
||||||
|
}
|
||||||
|
w.Flush()
|
||||||
}
|
}
|
||||||
w.Flush()
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -1144,6 +1156,7 @@ func (v *Viper) ReadInConfig() error {
|
||||||
return UnsupportedConfigError(v.getConfigType())
|
return UnsupportedConfigError(v.getConfigType())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
jww.DEBUG.Println("Reading file: ", v.getConfigFile())
|
||||||
file, err := afero.ReadFile(v.fs, filename)
|
file, err := afero.ReadFile(v.fs, filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
Loading…
Add table
Reference in a new issue