golang-lib/file/main.go

48 lines
883 B
Go
Raw Normal View History

2017-10-25 18:58:54 +02:00
package file
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/BurntSushi/toml"
)
2018-08-23 21:02:51 +02:00
// ReadTOML reads a config model from path of a yml file
2017-10-25 18:58:54 +02:00
func ReadTOML(path string, data interface{}) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}
2018-08-23 21:02:51 +02:00
return toml.Unmarshal(file, data)
2017-10-25 18:58:54 +02:00
}
// ReadJSON reads a config model from path of a yml file
func ReadJSON(path string, data interface{}) error {
file, err := os.Open(path)
if err != nil {
return err
}
2018-08-23 21:02:51 +02:00
return json.NewDecoder(file).Decode(data)
2017-10-25 18:58:54 +02:00
}
// SaveJSON to path
func SaveJSON(outputFile string, data interface{}) error {
tmpFile := outputFile + ".tmp"
2018-03-22 22:10:05 +01:00
file, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
2017-10-25 18:58:54 +02:00
if err != nil {
return err
}
2018-08-23 21:02:51 +02:00
err = json.NewEncoder(file).Encode(data)
if err != nil {
2017-10-25 18:58:54 +02:00
return err
}
2018-03-22 22:10:05 +01:00
file.Close()
2018-08-23 21:02:51 +02:00
return os.Rename(tmpFile, outputFile)
2017-10-25 18:58:54 +02:00
}