Skip to content

Commit

Permalink
Merge pull request #415 from ehang-io/dev
Browse files Browse the repository at this point in the history
fix file not close before rename
  • Loading branch information
ffdfgdfg authored Feb 19, 2020
2 parents 090be36 + f6063e0 commit 2f9ee71
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion lib/file/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package file
import (
"encoding/json"
"errors"
"github.com/astaxie/beego/logs"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}

0 comments on commit 2f9ee71

Please sign in to comment.