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

Detect if the body is closed in all code branches #58

Open
scriptnull opened this issue May 9, 2024 · 0 comments · May be fixed by #66
Open

Detect if the body is closed in all code branches #58

scriptnull opened this issue May 9, 2024 · 0 comments · May be fixed by #66

Comments

@scriptnull
Copy link

scriptnull commented May 9, 2024

Consider the program:

package main

import (
	"fmt"
	"io"
	"net/http"
)

func main() {
	req, err := http.NewRequest(http.MethodGet, "https://example.com", nil)
	if err != nil {
		panic(err)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	if resp.StatusCode >= 400 {
		defer resp.Body.Close()
		errResponse, err := io.ReadAll(resp.Body)
		if err != nil {
			panic(err)
		}
		fmt.Println("do something with error reponse", string(errResponse))
	}
}

bodyclose is happy with the above program and won't show any errors. But in reality, the above program will cause a resource leak as resp.Body.Close() is not being called in places outside the if condition.

It is safe to generalize that, whenever a branch occurs in the code like an if or switch, then bodyclose could look at all the branches to check if the resp.Body.Close() is called.

@ma91n ma91n linked a pull request Sep 9, 2024 that will close this issue
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 a pull request may close this issue.

1 participant