golang-lib/file/json.go

36 lines
691 B
Go
Raw Permalink Normal View History

// Package file provides functionality to load and save marshal files
2017-10-25 18:58:54 +02:00
package file
import (
"encoding/json"
"os"
)
// 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
}