backive/database.go

48 lines
1008 B
Go
Raw Normal View History

package backive
import (
"encoding/json"
"log"
"os"
"path"
)
2022-01-30 00:16:59 +01:00
var mockOsWriteFile = os.WriteFile
var mockOsReadFile = os.ReadFile
// Database is a simple string to string mapping, where arbitrary strings can be stored and safed to disk or loaded
type Database struct {
2023-03-17 09:56:58 +01:00
data map[string]interface{}
}
2022-01-07 11:17:12 +01:00
var dbPath = "/var/lib/backive/data.json"
// Save saves the database
func (d *Database) Save() {
jsonstr, merr := json.Marshal(d.data)
if merr != nil {
panic(merr)
}
log.Printf("Writing database output to file: %s", jsonstr)
saveDir, _ := path.Split(dbPath)
CreateDirectoryIfNotExists(saveDir)
2022-01-30 00:16:59 +01:00
err := mockOsWriteFile(dbPath, []byte(jsonstr), 0644)
if err != nil {
panic(err)
}
}
2022-01-07 11:17:12 +01:00
// Load loads the database
func (d *Database) Load() {
if _, err := os.Stat(dbPath); err == nil {
2022-01-30 00:16:59 +01:00
data, rferr := mockOsReadFile(dbPath)
if rferr != nil {
panic(rferr)
}
json.Unmarshal(data, &d.data)
2023-03-17 09:56:58 +01:00
} else if os.IsNotExist(err) {
// initialize db
d.data = make(map[string]interface{})
}
}