Skip to content

Commit 2f9ee71

Browse files
authored
Merge pull request #415 from ehang-io/dev
fix file not close before rename
2 parents 090be36 + f6063e0 commit 2f9ee71

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

lib/file/file.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package file
33
import (
44
"encoding/json"
55
"errors"
6+
"github.com/astaxie/beego/logs"
67
"os"
78
"path/filepath"
89
"strings"
@@ -151,7 +152,6 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
151152
if err != nil {
152153
panic(err)
153154
}
154-
defer file.Close()
155155
m.Range(func(key, value interface{}) bool {
156156
var b []byte
157157
var err error
@@ -191,6 +191,11 @@ func storeSyncMapToFile(m sync.Map, filePath string) {
191191
return true
192192
})
193193
_ = file.Sync()
194+
_ = file.Close()
195+
// must close file first, then rename it
194196
err = os.Rename(filePath+".tmp", filePath)
197+
if err != nil {
198+
logs.Error(err, "store to file err, data will lost")
199+
}
195200
// replace the file, maybe provides atomic operation
196201
}

0 commit comments

Comments
 (0)