gut/settingsdb/settingsdb.go
2024-02-17 22:46:50 +01:00

132 lines
1.7 KiB
Go

package settingsdb
import (
"encoding/json"
"os"
"sync"
)
type SettingsDB struct {
l sync.Mutex
m map[string]any
path string
}
func NewOrLoadSettingsDB(path string) (*SettingsDB, error) {
data, err := os.ReadFile(path)
if err != nil {
if os.IsNotExist(err) {
data = []byte("{}")
err := os.WriteFile(path, data, 0755)
if err != nil {
return nil, err
}
} else {
return nil, err
}
}
m := map[string]any{}
err = json.Unmarshal(data, &m)
if err != nil {
return nil, err
}
return &SettingsDB{
m: m,
path: path,
}, nil
}
func (s *SettingsDB) Set(key string, value any) error {
s.l.Lock()
defer s.l.Unlock()
s.m[key] = value
data, err := json.Marshal(s.m)
if err != nil {
return err
}
return os.WriteFile(s.path, data, 0755)
}
func (s *SettingsDB) Get(key string) any {
s.l.Lock()
defer s.l.Unlock()
v, ok := s.m[key]
if !ok {
return nil
}
return v
}
func (s *SettingsDB) GetString(key string, defValue ...string) string {
v := s.Get(key)
if v == nil {
if len(defValue) > 0 {
return defValue[0]
}
return ""
}
val, ok := v.(string)
if !ok {
if len(defValue) > 0 {
return defValue[0]
}
return ""
}
return val
}
func (s *SettingsDB) GetStrings(key string) []string {
v := s.Get(key)
if v == nil {
return nil
}
val, ok := v.([]string)
if !ok {
return nil
}
return val
}
func (s *SettingsDB) GetBool(key string) bool {
v := s.Get(key)
if v == nil {
return false
}
val, ok := v.(bool)
if !ok {
return false
}
return val
}
func (s *SettingsDB) Dump() (map[string]any, error) {
data, err := os.ReadFile(s.path)
if err != nil {
return nil, err
}
m := map[string]any{}
err = json.Unmarshal(data, &m)
if err != nil {
return nil, err
}
return m, nil
}