2022-10-02 14:39:55 -04:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
2022-10-25 00:16:29 -04:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2022-10-02 14:39:55 -04:00
|
|
|
"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"`
|
|
|
|
}
|
|
|
|
|
2022-10-25 00:16:29 -04:00
|
|
|
type store struct {
|
2022-10-02 14:39:55 -04:00
|
|
|
fs.FS
|
|
|
|
}
|
|
|
|
|
2022-10-25 00:16:29 -04:00
|
|
|
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) {
|
2022-10-02 14:39:55 -04:00
|
|
|
stor, err := fs.Sub(dir, ".storage")
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-10-25 00:16:29 -04:00
|
|
|
return &store{stor}, nil
|
2022-10-02 14:39:55 -04:00
|
|
|
}
|