Quickstart
Latchfile is a small Go package for replacing files. Use it when a reader should see either the previous contents or the complete new contents, even while an update is in progress.
Write a settings file
payload := []byte("{\"workers\":4}\n")
if err := latchfile.WriteFile("settings.json", payload, 0644); err != nil {
return fmt.Errorf("save settings: %w", err)
}
Import example.org/latchfile. The parent directory must already exist. Set the mode explicitly on every write.
What gets created?
During the write there are two names in the directory. The destination still points at the old file, and a sibling temporary entry receives the new bytes. The rename gives the new file its final name. A reader that already opened the old file can finish reading its original contents.
Use mode
0600 for credentials and private state. Replacement creates a new file, so any previous file mode must be supplied again.Next, see recipes for streaming and checkpoints.