69 lines
1.0 KiB
Go
69 lines
1.0 KiB
Go
package settingsdb
|
|
|
|
import (
|
|
"encoding/json"
|
|
|
|
"gitea.codeblob.work/pk/gut/generics"
|
|
|
|
"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)
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
func (s *SettingsDB) Close() {
|
|
s.db.Close()
|
|
}
|