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

Allow defer statements after error checking #31

Closed
cloudlena opened this issue Oct 11, 2019 · 3 comments · Fixed by #37
Closed

Allow defer statements after error checking #31

cloudlena opened this issue Oct 11, 2019 · 3 comments · Fixed by #37
Labels
enhancement New feature or request

Comments

@cloudlena
Copy link

cloudlena commented Oct 11, 2019

It is good practice to defer a close statement for a HTTP response body after the error check as discussed in https://stackoverflow.com/questions/33238518/what-could-happen-if-i-dont-close-response-body-in-golang#33238755

In my opinion, this defer statement should logically be part of the block where the body originates so I think we should allow the following:

resp, err := client.Do(req)
if err != nil {
    return err
}
defer resp.Body.Close()

instead of enforcing the following:

resp, err := client.Do(req)
if err != nil {
    return err
}

defer resp.Body.Close()
@bombsimon
Copy link
Owner

Hi, thanks for the report!

Seems reasonable, I'll add this to the TODO list!

@DmitriiDunaev
Copy link

It might be beneficial to allow methods other than Close() to be used in defer. Many libraries use names like Free(), Release(), Shutdown(), etc.

@bombsimon
Copy link
Owner

It might be beneficial to allow methods other than Close() to be used in defer. Many libraries use names like Free(), Release(), Shutdown(), etc.

This was reworked in #133 in June, it's now allowed to defer any call as long as it's used two statements above. There are a bunch of examples with allowed values in the test:

undoMaxProcs, err := maxprocsSet()
if err != nil {
return fmt.Errorf("failed to set GOMAXPROCS, err: %w", err)
}
defer undoMaxProcs()
callback, x := getCb()
if x != b {
return
}
defer callback()
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
db, err := OpenDB()
requireNoError(t, err)
defer db.Close()
tx := BeginTx(db)
defer func() {
EndTx(tx, err)
}()
thingOne := getOne()
thingTwo := getTwo()
defer thingOne.Close()

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

Successfully merging a pull request may close this issue.

3 participants