-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpersistence.go
65 lines (51 loc) · 1.25 KB
/
persistence.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
package chronos
import (
"encoding/json"
"io/ioutil"
"os"
"path"
)
type Storage interface {
SaveSchedule(schedule TaskSchedule) error
LoadSchedule() (TaskSchedule, error)
}
func NewFileStorage(path string, filename string) *FileStorage {
return &FileStorage{Path: path, Filename: filename}
}
type FileStorage struct {
Path string
Filename string
}
func (fs *FileStorage) SaveSchedule(schedule *TaskSchedule) error {
// ensure path exists
os.MkdirAll(fs.Path, 0666)
jsonSchedule, err := json.Marshal(schedule)
if err != nil {
return err
}
// truncate existing file
os.Truncate(path.Join(fs.Path, fs.Filename), 0)
file, err := os.OpenFile(path.Join(fs.Path, fs.Filename), os.O_CREATE|os.O_RDWR, 0777)
if err != nil {
return err
}
defer file.Close()
if _, err := file.Write(jsonSchedule); err != nil {
return err
}
return nil
}
func (fs *FileStorage) LoadSchedule() (*TaskSchedule, error) {
fileContent, err := ioutil.ReadFile(path.Join(fs.Path, fs.Filename))
if err != nil {
return nil, err
}
schedule := &TaskSchedule{}
if err := json.Unmarshal(fileContent, schedule); err != nil {
return nil, err
}
return schedule, nil
}
func (fs *FileStorage) RemoveSchedule() error {
return os.Remove(path.Join(fs.Path, fs.Filename))
}