first write to .new then move after finishing writing to prevent data corruption

This commit is contained in:
nytpu
2021-03-18 14:46:05 -06:00
parent 843d1b677a
commit d0a71b360d
+9 -4
View File
@@ -63,16 +63,21 @@ func Init(dataPath string) error {
} }
func (d *FullData) WriteJSON(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") jsonBytes, err := json.MarshalIndent(&d, "", "\t")
d.Unlock() d.RUnlock()
if err != nil { if err != nil {
return err return err
} }
err = ioutil.WriteFile(filepath.Join(dataPath, "comitium.json"), jsonBytes, 0666) err = ioutil.WriteFile(path, jsonBytes, 0666)
if err != nil { if err != nil {
return err return err
} }
return nil // if full write was successful then overwrite original
err = os.Rename(path, filepath.Join(dataPath, "comitium.json"))
return err
} }