53 lines
787 B
Go
53 lines
787 B
Go
package settingsdb
|
|
|
|
import (
|
|
"encoding/json"
|
|
|
|
"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) Close() {
|
|
s.db.Close()
|
|
}
|