timakin/bodyclose

Detect if the body is closed in all code branches

scriptnull opened this issue · 0 comments

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.