first write to .new then move after finishing writing to prevent data corruption
This commit is contained in:
+9
-4
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user