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

fix: close file #232

Merged
merged 2 commits into from
May 12, 2024
Merged

fix: close file #232

merged 2 commits into from
May 12, 2024

Conversation

testwill
Copy link
Contributor

No description provided.

Copy link
Owner

@benhoyt benhoyt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the fix. Out of interest, how did you find/notice this?

Note that the "defer close" needs to be before the isNewFile block, otherwise if that first write fails the file still won't be closed.

Also, because it's a file we're writing to, we need to handle and return the error from f.Close(). I suggest changing the return value to a named return value, (err error) and doing something like this:

	defer func() {
		closeErr := f.Close()
		err = errors.Join(err, closeErr)
	}()

Is there any way we can test for this? I'm guessing it won't be easy, so probably not worth it.

@testwill
Copy link
Contributor Author

Thanks for the fix. Out of interest, how did you find/notice this?

Note that the "defer close" needs to be before the isNewFile block, otherwise if that first write fails the file still won't be closed.

Also, because it's a file we're writing to, we need to handle and return the error from f.Close(). I suggest changing the return value to a named return value, (err error) and doing something like this:

	defer func() {
		closeErr := f.Close()
		err = errors.Join(err, closeErr)
	}()

Is there any way we can test for this? I'm guessing it won't be easy, so probably not worth it.

Found by browsing the code

Copy link
Owner

@benhoyt benhoyt left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You forgot the (err error) named return and moving the defer up.

I fixed this and also remembered errors.Join is Go 1.20+ (currently go.mod is on 1.16) so I removed the use of that, see 1962653

@benhoyt benhoyt merged commit 722cffe into benhoyt:master May 12, 2024
10 checks passed
@benhoyt
Copy link
Owner

benhoyt commented May 12, 2024

Thanks again for spotting this!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants