Skip to content

Commit

Permalink
services/ticker: update *.json files atomically (#2362)
Browse files Browse the repository at this point in the history
  • Loading branch information
accordeiro authored Mar 6, 2020
1 parent 10ee142 commit 19254e9
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions services/ticker/internal/utils/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ func PanicIfError(e error) {
}
}

// WriteJSONToFile wrtites a json []byte dump to <filename>
// WriteJSONToFile atomically writes a json []byte dump to <filename>
// It ensures atomicity by first creating a tmp file (filename.tmp), writing
// the contents to it, then renaming it to the originally specified filename.
func WriteJSONToFile(jsonBytes []byte, filename string) (numBytes int, err error) {
f, err := os.Create(filename)
tmp := fmt.Sprintf("%s.tmp", filename)
f, err := os.Create(tmp)
PanicIfError(err)
defer f.Close()

Expand All @@ -32,6 +35,7 @@ func WriteJSONToFile(jsonBytes []byte, filename string) (numBytes int, err error
return
}

err = os.Rename(tmp, filename)
return
}

Expand Down

0 comments on commit 19254e9

Please sign in to comment.