Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close via defer #47

Merged
merged 4 commits into from
Mar 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,26 @@ func removeAll(fs billy.Basic, path string) error {
// WriteFile writes data to a file named by filename in the given filesystem.
// If the file does not exist, WriteFile creates it with permissions perm;
// otherwise WriteFile truncates it before writing.
func WriteFile(fs billy.Basic, filename string, data []byte, perm os.FileMode) error {
func WriteFile(fs billy.Basic, filename string, data []byte, perm os.FileMode) (err error) {
f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
defer func() {
if f != nil {
spennymac marked this conversation as resolved.
Show resolved Hide resolved
err1 := f.Close()
if err == nil {
err = err1
}
}
}()

n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}

if err1 := f.Close(); err == nil {
err = err1
}

return err
return nil
}

// Random number state.
Expand Down
Loading