From f6063e0d6cfd359d82bf578c14059004dbdd1ce5 Mon Sep 17 00:00:00 2001 From: ffdfgdfg Date: Wed, 19 Feb 2020 23:20:44 +0800 Subject: [PATCH] fix file not close before rename --- lib/file/file.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/file/file.go b/lib/file/file.go index 0bcf61c3..f8aafb60 100644 --- a/lib/file/file.go +++ b/lib/file/file.go @@ -3,6 +3,7 @@ package file import ( "encoding/json" "errors" + "github.com/astaxie/beego/logs" "os" "path/filepath" "strings" @@ -151,7 +152,6 @@ func storeSyncMapToFile(m sync.Map, filePath string) { if err != nil { panic(err) } - defer file.Close() m.Range(func(key, value interface{}) bool { var b []byte var err error @@ -191,6 +191,11 @@ func storeSyncMapToFile(m sync.Map, filePath string) { return true }) _ = file.Sync() + _ = file.Close() + // must close file first, then rename it err = os.Rename(filePath+".tmp", filePath) + if err != nil { + logs.Error(err, "store to file err, data will lost") + } // replace the file, maybe provides atomic operation }