gut/settingsdb/settingsdb.go

132 lines
1.7 KiB
Go
Raw Permalink Normal View History

2024-02-04 14:38:36 +01:00
package settingsdb
import (
"encoding/json"
2024-02-17 22:46:50 +01:00
"os"
"sync"
2024-02-04 14:38:36 +01:00
)
type SettingsDB struct {
2024-02-17 22:46:50 +01:00
l sync.Mutex
m map[string]any
path string
2024-02-04 14:38:36 +01:00
}
func NewOrLoadSettingsDB(path string) (*SettingsDB, error) {
2024-02-17 22:46:50 +01:00
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)
2024-02-04 14:38:36 +01:00
if err != nil {
return nil, err
}
return &SettingsDB{
2024-02-17 22:46:50 +01:00
m: m,
path: path,
2024-02-04 14:38:36 +01:00
}, nil
}
func (s *SettingsDB) Set(key string, value any) error {
2024-02-17 22:46:50 +01:00
s.l.Lock()
defer s.l.Unlock()
s.m[key] = value
data, err := json.Marshal(s.m)
if err != nil {
return err
2024-02-04 14:38:36 +01:00
}
2024-02-17 22:46:50 +01:00
return os.WriteFile(s.path, data, 0755)
2024-02-04 14:38:36 +01:00
}
2024-02-17 22:46:50 +01:00
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]
}
2024-02-04 14:38:36 +01:00
return ""
}
2024-02-17 22:46:50 +01:00
val, ok := v.(string)
if !ok {
if len(defValue) > 0 {
return defValue[0]
}
return ""
}
return val
2024-02-04 14:38:36 +01:00
}
2024-02-05 23:04:14 +01:00
func (s *SettingsDB) GetStrings(key string) []string {
2024-02-17 22:46:50 +01:00
v := s.Get(key)
if v == nil {
2024-02-05 23:04:14 +01:00
return nil
}
2024-02-17 22:46:50 +01:00
val, ok := v.([]string)
if !ok {
2024-02-05 23:04:14 +01:00
return nil
}
2024-02-17 22:46:50 +01:00
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
2024-02-05 23:04:14 +01:00
}
2024-02-17 22:46:50 +01:00
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
2024-02-04 14:38:36 +01:00
}