kogs/store.go

47 lines
828 B
Go
Raw Normal View History

2024-03-31 13:43:35 -06:00
package main
import (
2024-03-31 15:12:44 -06:00
"errors"
2024-03-31 13:43:35 -06:00
"fmt"
"log"
"os"
"path"
"strings"
)
func NewStore(s string) (*Store, error) {
fi, err := os.Lstat(s)
if err != nil {
return nil, err
}
if !fi.IsDir() {
return nil, fmt.Errorf("not a directory")
}
fstore := Store(s)
return &fstore, nil
}
type Store string
func (s Store) Set(key string, value string) {
err := os.WriteFile(path.Join(string(s), key), []byte(value), 0600)
if err != nil {
2024-03-31 15:12:44 -06:00
log.Println(fmt.Errorf("failed to set %q: %s", key, err))
2024-03-31 13:43:35 -06:00
}
}
func (s Store) Get(key string) (string, error) {
2024-03-31 15:12:44 -06:00
keyPath := path.Join(string(s), key)
_, err := os.Stat(keyPath)
if errors.Is(err, os.ErrNotExist) {
return "", os.ErrNotExist
}
2024-03-31 13:43:35 -06:00
data, err := os.ReadFile(path.Join(string(s), key))
if err != nil {
return "", nil
}
return strings.TrimSpace(string(data)), nil
}