From d0a71b360d034fb0005f5552b3875a55061161f4 Mon Sep 17 00:00:00 2001 From: nytpu Date: Thu, 18 Mar 2021 14:46:05 -0600 Subject: [PATCH] first write to .new then move after finishing writing to prevent data corruption --- core/core.go | 13 +++++++++---- 1 file 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 }