99 lines
2 KiB
Go
99 lines
2 KiB
Go
package state
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
type StateStore interface {
|
|
StoreState(key string, object interface{}) error
|
|
GetState(key string, object any) error
|
|
}
|
|
|
|
// Locale Filesystem
|
|
func NewLocaleFilesystem(path string) (StateStore, error) {
|
|
l := localeFilesystem{}
|
|
l.path = path
|
|
|
|
if _, err := os.Stat(l.path); os.IsNotExist(err) {
|
|
err = os.MkdirAll(l.path, 0744)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%e: %s", ErrLocaleFilesystemCantCreateFolder, err)
|
|
}
|
|
}
|
|
return l, nil
|
|
}
|
|
|
|
type localeFilesystem struct {
|
|
path string
|
|
}
|
|
|
|
func (s localeFilesystem) GetState(key string, object any) error {
|
|
data, err := os.ReadFile(fmt.Sprintf("%v/%v.json", s.path, key))
|
|
if err != nil {
|
|
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantReadState, err)
|
|
}
|
|
|
|
err = json.Unmarshal(data, object)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantReadState, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s localeFilesystem) StoreState(key string, object any) error {
|
|
data, err := json.Marshal(object)
|
|
if err != nil {
|
|
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantStoreState, err)
|
|
}
|
|
|
|
err = os.WriteFile(fmt.Sprintf("%v/%v.json", s.path, key), data, 0644)
|
|
if err != nil {
|
|
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantStoreState, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// ROM
|
|
func NewRamFilesystem() (StateStore, error) {
|
|
l := ramFilesystem{}
|
|
l.data = make(map[string][]byte)
|
|
|
|
return &l, nil
|
|
}
|
|
|
|
type ramFilesystem struct {
|
|
data map[string][]byte
|
|
}
|
|
|
|
func (s *ramFilesystem) GetState(key string, object any) error {
|
|
data, ok := s.data[key]
|
|
|
|
if !ok {
|
|
return errors.New("cant get state from ram")
|
|
}
|
|
|
|
err := json.Unmarshal(data, object)
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantReadState, err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *ramFilesystem) StoreState(key string, object any) error {
|
|
data, err := json.Marshal(object)
|
|
if err != nil {
|
|
return fmt.Errorf("%e: %v", ErrLocaleFilesystemCantStoreState, err)
|
|
}
|
|
|
|
s.data[key] = data
|
|
|
|
return nil
|
|
}
|