blasphem/pkg/storage/storage.go
2022-10-25 00:16:29 -04:00

58 lines
863 B
Go

package storage
import (
"encoding/json"
"fmt"
"io/fs"
)
type Data interface {
}
type Item struct {
Version int `json:"version"`
MinorVersion *int `json:"minor_version,omitempty"`
Key string `json:"key"`
Data Data `json:"data"`
}
type store struct {
fs.FS
}
type Store interface {
Get(key string, data interface{}) error
}
func (s *store) Get(key string, data interface{}) error {
f, err := s.Open(key)
if err != nil {
return err
}
defer f.Close()
item := Item{
Data: data,
}
d := json.NewDecoder(f)
err = d.Decode(&item)
if err != nil {
return err
}
if item.Key != key {
return fmt.Errorf("key mismatch '%s' != '%s'", item.Key, key)
}
return nil
}
func Open(dir fs.FS) (*store, error) {
stor, err := fs.Sub(dir, ".storage")
if err != nil {
return nil, err
}
return &store{stor}, nil
}