This repository has been archived on 2024-07-27. You can view files and clone it, but cannot push or open issues or pull requests.
state/state.go
kekskurse bc5c7d6f9e init
2024-03-04 11:20:04 +01:00

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
}