gut/settingsdb/settingsdb.go

69 lines
1.0 KiB
Go
Raw Normal View History

2024-02-04 14:38:36 +01:00
package settingsdb
import (
"encoding/json"
2024-02-05 23:04:14 +01:00
"gitea.codeblob.work/pk/gut/generics"
2024-02-04 14:38:36 +01:00
"github.com/syndtr/goleveldb/leveldb"
)
type SettingsDB struct {
db *leveldb.DB
}
func NewOrLoadSettingsDB(path string) (*SettingsDB, error) {
db, err := leveldb.OpenFile(path, nil)
if err != nil {
return nil, err
}
return &SettingsDB{
db: db,
}, nil
}
func (s *SettingsDB) Set(key string, value any) error {
var data []byte
switch v := value.(type) {
case string:
data = []byte(v)
default:
var err error
data, err = json.Marshal(v)
if err != nil {
return err
}
}
return s.db.Put([]byte(key), data, nil)
}
func (s *SettingsDB) GetString(key string) string {
data, err := s.db.Get([]byte(key), nil)
if err != nil {
return ""
}
return string(data)
}
2024-02-05 23:04:14 +01:00
func (s *SettingsDB) GetStrings(key string) []string {
data, err := s.db.Get([]byte(key), nil)
if err != nil {
return nil
}
value, err := generics.UnmarshalTo[[]string](data)
if err != nil {
return nil
}
return *value
}
2024-02-04 14:38:36 +01:00
func (s *SettingsDB) Close() {
s.db.Close()
}