forked from galthaus/ocb-dhcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstores.go
51 lines (45 loc) · 921 Bytes
/
stores.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type LoadSaver interface {
Save(*DataTracker) error
Load(*DataTracker) error
}
type FileStore struct {
backingDatabase string
}
func NewFileStore(dbFile string) (*FileStore, error) {
info, err := os.Stat(dbFile)
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() {
return nil, fmt.Errorf("%s is not a regular file", dbFile)
}
return &FileStore{backingDatabase: dbFile}, nil
}
func (fs *FileStore) Save(dt *DataTracker) error {
dt.Lock()
defer dt.Unlock()
data, err := json.Marshal(dt)
if err != nil {
return err
}
if err := ioutil.WriteFile(fs.backingDatabase, data, 0700); err != nil {
return err
}
return nil
}
func (fs *FileStore) Load(dt *DataTracker) error {
dt.Lock()
defer dt.Unlock()
data, err := ioutil.ReadFile(fs.backingDatabase)
if err != nil {
return err
}
return json.Unmarshal(data, dt)
}