Documentation
¶
Overview ¶
To write to files in a robust way we should:
- handle error returned by `Close()`
- handle error returned by `Write()`
- remove partially written file if `Write()` or `Close()` returned an error
This logic is non-trivial.
Package atomicfile makes it easy to get this logic right:
func writeToFileAtomically(filePath string, data []byte) error { w, err := atomicfile.New(filePath) if err != nil { return err } // calling Close() twice is a no-op defer w.Close() _, err = w.Write(data) if err != nil { return err } return w.Close() }
To learn more see https://presstige.io/p/atomicfile-22143bf788b542fda2262ca7aee57ae4
Index ¶
- Variables
- type File
- func (f *File) Close() error
- func (f *File) RemoveIfNotClosed()
- func (f *File) Seek(offset int64, whence int) (ret int64, err error)
- func (f *File) SetWriteDeadline(t time.Time) error
- func (f *File) Sync() error
- func (f *File) Truncate(size int64) error
- func (f *File) Write(d []byte) (int, error)
- func (f *File) WriteAt(b []byte, off int64) (n int, err error)
- func (f *File) WriteString(s string) (n int, err error)
Constants ¶
This section is empty.
Variables ¶
var ( // ErrCancelled is returned by calls subsequent to Cancel() ErrCancelled = errors.New("cancelled") )
Functions ¶
This section is empty.
Types ¶
type File ¶
type File struct {
// contains filtered or unexported fields
}
File allows writing to a file atomically i.e. if the while file is not written successfully, we make sure to clean things up
func (*File) Close ¶
Close closes the file. Can be called multiple times to make it easier to use via defer
func (*File) RemoveIfNotClosed ¶
func (f *File) RemoveIfNotClosed()
RemoveIfNotClosed removes the temp file if we didn't Close the file yet. Destination file will not be created. Use it with defer to ensure cleanup in case of a panic on the same goroutine that happens before Close. RemoveIfNotClosed after Close is a no-op.