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
|
package storage
import (
"context"
"encoding/gob"
"fmt"
"io"
"log"
"os"
"go.neonxp.dev/djson/internal/model"
)
type FileStorage struct {
enc *gob.Encoder
dec *gob.Decoder
fh *os.File
fileName string
mutationsLog []model.Mutation
}
func NewFileStorage(fileName string) (*FileStorage, error) {
fh, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0o666)
if err != nil {
return nil, err
}
return &FileStorage{
fileName: fileName,
fh: fh,
enc: gob.NewEncoder(fh),
dec: gob.NewDecoder(fh),
mutationsLog: []model.Mutation{},
}, nil
}
func (fs *FileStorage) Commit(ctx context.Context, mut model.Mutation) error {
if fs.enc == nil {
return fmt.Errorf("file storage not initiated")
}
return fs.enc.Encode(mut)
}
func (fs *FileStorage) Load() chan model.Mutation {
ch := make(chan model.Mutation)
go func() {
for {
m := model.Mutation{}
if err := fs.dec.Decode(&m); err != nil {
if err != io.EOF {
log.Println(err.Error())
}
close(ch)
return
}
log.Println("Loaded from fs", m.String())
fs.mutationsLog = append(fs.mutationsLog, m)
ch <- m
}
}()
return ch
}
func (fs *FileStorage) Close() error {
return fs.fh.Close()
}
|