templatefile/pkg/templater/persist.go

52 lines
862 B
Go

package templater
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
"sync"
)
var lock sync.Mutex
func marshal(v interface{}) (io.Reader, error) {
b, err := json.MarshalIndent(v, "", "\t")
if err != nil {
return nil, err
}
return bytes.NewReader(b), nil
}
func unmarshal(r io.Reader, v interface{}) error {
return json.NewDecoder(r).Decode(v)
}
func Save(path string, v interface{}) error {
lock.Lock()
defer lock.Unlock()
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("Saving Templater configuration failed with error : %v", err)
}
defer f.Close()
r, err := marshal(v)
if err != nil {
return err
}
_, err = io.Copy(f, r)
return err
}
func Load(path string, v interface{}) error {
lock.Lock()
defer lock.Unlock()
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
return unmarshal(f, v)
}