-
Notifications
You must be signed in to change notification settings - Fork 2
/
gob_handler.go
84 lines (66 loc) · 1.44 KB
/
gob_handler.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
78
79
80
81
82
83
84
package storage
import (
"bytes"
"encoding/gob"
"github.com/ActiveState/log"
"io/ioutil"
"os"
"sync"
)
// exposing these for testing
type Storage interface {
Encode(data interface{}) ([]byte, error)
Load(data interface{}) error
Write(buf []byte) error
}
type FileStorage struct {
file_path string
writeLock *sync.Mutex
}
const FILE_MODE = 0666
func NewFileStorage(path string) Storage {
return &FileStorage{
file_path: path,
writeLock: &sync.Mutex{},
}
}
func (s *FileStorage) Encode(data interface{}) ([]byte, error) {
m := new(bytes.Buffer)
enc := gob.NewEncoder(m)
err := enc.Encode(data)
if err != nil {
return nil, err
}
return m.Bytes(), nil
}
func (s *FileStorage) Write(buf []byte) error {
s.writeLock.Lock()
defer s.writeLock.Unlock()
if err := ioutil.WriteFile(s.file_path, buf, FILE_MODE); err != nil {
return err
}
// this extra step to make the file accessible by stackato user
if err := os.Chmod(s.file_path, FILE_MODE); err != nil {
return err
}
return nil
}
func (s *FileStorage) Load(e interface{}) error {
var err error
if _, err = os.Stat(s.file_path); os.IsNotExist(err) {
log.Infof("Creating %s since it does not exist", s.file_path)
_, err = os.Create(s.file_path)
} else {
n, err := ioutil.ReadFile(s.file_path)
if err != nil {
log.Error(err)
}
p := bytes.NewBuffer(n)
dec := gob.NewDecoder(p)
err = dec.Decode(e)
if err != nil {
log.Error(err)
}
}
return err
}