58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
package state
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
)
|
|
|
|
type StateStore interface {
|
|
StoreState(key string, object interface{}) error
|
|
GetState(key string, object any) error
|
|
}
|
|
|
|
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
|
|
}
|