serialize.go 674 Bytes
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package config

import (
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
4 5 6 7
	"encoding/json"
	"io/ioutil"
	"os"
	"path"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9 10
)

func ReadFile(filename string) ([]byte, error) {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
11
	return ioutil.ReadFile(filename)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13 14
}

func WriteFile(filename string, buf []byte) error {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
15 16 17 18
	err := os.MkdirAll(path.Dir(filename), 0777)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
19

Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
20
	return ioutil.WriteFile(filename, buf, 0666)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
21 22 23
}

func ReadConfigFile(filename string, cfg *Config) error {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
24 25 26 27
	buf, err := ReadFile(filename)
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
28

Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
29
	return json.Unmarshal(buf, cfg)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30 31 32
}

func WriteConfigFile(filename string, cfg *Config) error {
Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
33 34 35 36
	buf, err := json.MarshalIndent(cfg, "", "  ")
	if err != nil {
		return err
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
37

Juan Batiz-Benet's avatar
gofmt  
Juan Batiz-Benet committed
38
	return WriteFile(filename, buf)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
39
}