-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_store.go
58 lines (52 loc) · 1.18 KB
/
file_store.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
package rivers
import (
"encoding/json"
"errors"
"io"
"os"
)
// FileStore represents a data store.
type FileStore struct {
path string
}
// NewFileStore takes a path and creates a new file store.
// It errors if the filepath is empty.
func NewFileStore(path string) (*FileStore, error) {
if path == "" {
return nil, errors.New("empty file path")
}
fstore := FileStore{
path: path,
}
return &fstore, nil
}
// Save takes a slice of records and saves them in a file.
func (fs *FileStore) Save(records []StationWaterLevelReading) error {
f, err := os.OpenFile(fs.path, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
defer f.Close()
return json.NewEncoder(f).Encode(records)
}
// Records returns records stored in a file.
func (fs *FileStore) Records() ([]StationWaterLevelReading, error) {
f, err := os.Open(fs.path)
if err != nil {
return nil, err
}
defer f.Close()
var records []StationWaterLevelReading
decoder := json.NewDecoder(f)
for {
rec := []StationWaterLevelReading{}
err := decoder.Decode(&rec)
if errors.Is(err, io.EOF) {
return records, nil
}
if err != nil {
return nil, err
}
records = append(records, rec...)
}
}