-
Notifications
You must be signed in to change notification settings - Fork 0
/
serializer.go
77 lines (65 loc) · 1.81 KB
/
serializer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Library for reading and parsing config files.
package conf
import (
"encoding/gob"
"encoding/json"
"os"
"github.com/golang/glog"
)
// Loads data from the gob file.
func LoadFromFile(filePath string, object interface{}) error {
glog.V(1).Infof("Opening file %q.", filePath)
file, err := os.Open(filePath)
if err != nil {
return err
}
decoder := gob.NewDecoder(file)
err = decoder.Decode(object)
if err != nil {
return err
}
return file.Close()
}
// Saves data to the gob file.
func SaveToFile(filePath string, object interface{}) error {
glog.V(1).Infof("Opening file %q.", filePath)
file, err := os.Create(filePath)
if err != nil {
return err
}
encoder := gob.NewEncoder(file)
encoder.Encode(object)
return file.Close()
}
// Loads data from the JSON file.
func LoadFromJson(filePath string, object interface{}) error {
glog.V(1).Infof("Opening file %q.", filePath)
file, err := os.Open(filePath)
if err != nil {
return err
}
decoder := json.NewDecoder(file)
err = decoder.Decode(object)
if err != nil {
return err
}
return file.Close()
}
// Loads data from the gob file in the config directory:
// $HOME/.config/{appName}.gob
func LoadConfigFromFile(appName string, object interface{}) error {
return LoadFromFile(getPath(appName, "gob"), object)
}
// Saves data from the gob file in the config directory:
// $HOME/.config/{appName}.gob
func SaveConfigToFile(appName string, object interface{}) error {
return SaveToFile(getPath(appName, "gob"), object)
}
// Loads data from the JSON file in the config directory:
// $HOME/.config/{appName}.json
func LoadConfigFromJson(appName string, object interface{}) error {
return LoadFromJson(getPath(appName, "json"), object)
}
func getPath(appName string, extension string) string {
return os.Getenv("HOME") + "/.config/" + appName + "." + extension
}