diff options
author | NeonXP <i@neonxp.dev> | 2022-11-21 03:47:16 +0300 |
---|---|---|
committer | NeonXP <i@neonxp.dev> | 2022-12-04 19:06:13 +0300 |
commit | 9d46ca252151a2c48434f9ec201bcb3c9133ec78 (patch) | |
tree | b146450cf0c09355f06656768f88043078195f0e /internal/storage/file.go | |
parent | 340a623e1a35efe0182cadd780a5a3385b526705 (diff) |
Chi router
Diffstat (limited to 'internal/storage/file.go')
-rw-r--r-- | internal/storage/file.go | 31 |
1 files changed, 22 insertions, 9 deletions
diff --git a/internal/storage/file.go b/internal/storage/file.go index 7619e32..885d5ef 100644 --- a/internal/storage/file.go +++ b/internal/storage/file.go @@ -5,13 +5,24 @@ import ( "encoding/gob" "fmt" "io" - "log" "os" + "github.com/rs/zerolog" "go.neonxp.dev/djson/internal/model" + jsonModel "go.neonxp.dev/json/model" ) -type FileStorage struct { +func init() { + gob.Register(new(jsonModel.ArrayNode)) + gob.Register(new(jsonModel.ObjectNode)) + gob.Register(new(jsonModel.StringNode)) + gob.Register(new(jsonModel.BooleanNode)) + gob.Register(new(jsonModel.NullNode)) + gob.Register(new(jsonModel.NumberNode)) +} + +type fsStorage struct { + logger zerolog.Logger enc *gob.Encoder dec *gob.Decoder fh *os.File @@ -19,13 +30,15 @@ type FileStorage struct { mutationsLog []model.Mutation } -func NewFileStorage(fileName string) (*FileStorage, error) { +func New(fileName string, logger zerolog.Logger) (Storage, error) { + logger.Info().Str("path", fileName).Msg("loading db") fh, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0o666) if err != nil { return nil, err } - return &FileStorage{ + return &fsStorage{ + logger: logger, fileName: fileName, fh: fh, enc: gob.NewEncoder(fh), @@ -34,26 +47,26 @@ func NewFileStorage(fileName string) (*FileStorage, error) { }, nil } -func (fs *FileStorage) Commit(ctx context.Context, mut model.Mutation) error { +func (fs *fsStorage) 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 { +func (fs *fsStorage) 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()) + fs.logger.Err(err) } close(ch) return } - log.Println("Loaded from fs", m.String()) + fs.logger.Debug().RawJSON("json", []byte(m.String())).Msg("loaded mutation") fs.mutationsLog = append(fs.mutationsLog, m) ch <- m } @@ -61,6 +74,6 @@ func (fs *FileStorage) Load() chan model.Mutation { return ch } -func (fs *FileStorage) Close() error { +func (fs *fsStorage) Close() error { return fs.fh.Close() } |