summaryrefslogtreecommitdiff
path: root/core/core.go
diff options
context:
space:
mode:
authornytpu <alex@nytpu.com>2021-03-18 14:46:05 -0600
committernytpu <alex@nytpu.com>2021-03-18 14:50:40 -0600
commitd0a71b360d034fb0005f5552b3875a55061161f4 (patch)
treea3470da32ce78e595deebd8c39cf6cd67f8554b1 /core/core.go
parent843d1b677aeedd54f5ed29f215e87df53a40e581 (diff)
first write to .new then move after finishing writing to prevent data corruption
Diffstat (limited to 'core/core.go')
-rw-r--r--core/core.go13
1 files changed, 9 insertions, 4 deletions
diff --git a/core/core.go b/core/core.go
index a97b8e3..513c84c 100644
--- a/core/core.go
+++ b/core/core.go
@@ -63,16 +63,21 @@ func Init(dataPath string) error {
}
func (d *FullData) WriteJSON(dataPath string) error {
- d.Lock()
+ // use .new so if there's a corruption when writing the old file is intact
+ path := filepath.Join(dataPath, "comitium.json.new")
+
+ d.RLock()
jsonBytes, err := json.MarshalIndent(&d, "", "\t")
- d.Unlock()
+ d.RUnlock()
if err != nil {
return err
}
- err = ioutil.WriteFile(filepath.Join(dataPath, "comitium.json"), jsonBytes, 0666)
+ err = ioutil.WriteFile(path, jsonBytes, 0666)
if err != nil {
return err
}
- return nil
+ // if full write was successful then overwrite original
+ err = os.Rename(path, filepath.Join(dataPath, "comitium.json"))
+ return err
}