Documentation
¶
Overview ¶
Package atomicfile provides a mechanism (on Unix-like platforms) to present a consistent view of a file to separate processes even while the file is being written. This is accomplished by writing a temporary file, syncing to disk, and renaming over the destination file name.
Partial/inconsistent reads can occur due to:
- A process attempting to read the file while it is being written to (both in the case of a new file with a short/incomplete write or in the case of an existing, updated file where new bytes may be written at the beginning but old bytes may still be present after).
- Concurrent goroutines leading to multiple active writers of the same file.
The above mechanism explicitly protects against (1) as all writes are to a file with a temporary name.
There is no explicit protection against multiple, concurrent goroutines attempting to write the same file. However, atomically writing the file should mean only one writer will "win" and a consistent file will be visible.
Note: atomicfile is partially implemented for Windows. The Windows codepath performs the same operations, however Windows does not guarantee that a rename operation is atomic; a crash in the middle may leave the destination file truncated rather than with the expected content.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("file is closed")
ErrClosed is returned if Read or Write are called on a closed File.
Functions ¶
This section is empty.
Types ¶
type File ¶
type File interface { io.ReadWriteCloser // Cancel abandons a change to a file. This can be called if a write fails or another error occurs. Cancel() error }
File is an io.ReadWriteCloser that can also be Canceled if a change needs to be abandoned.
func New ¶
New returns a new atomic file. On Unix-like platforms, the writer (an io.ReadWriteCloser) is backed by a temporary file placed into the same directory as the destination file (using filepath.Dir to split the directory from the name). On a call to Close the temporary file is synced to disk and renamed to its final name, hiding any previous file by the same name.
Note: Take care to call Close and handle any errors that are returned. Errors returned from Close may indicate that the file was not written with its final name.