The body of an HTTP response is never closed, which keeps its connection from being reused
What it finds
resp, err := http.Get(url) in a function that never calls resp.Body.Close(): the client keeps the connection of an open body, so it can neither reuse it for the next request nor free it, and a program that does this in a loop runs out of connections or file descriptors.
The call must be Get, Head, Post or PostForm of net/http, or the method Do, Get, Head, Post or PostForm of http.DefaultClient or of a variable declared in the file as an http.Client or a pointer to one, and its first result must go to a local variable. The function must not call Close on the body of that variable, and the variable must not leave the function: a response that is returned, stored or passed to another function, or whose body is passed to a function other than one that only reads it, such as io.ReadAll, may be closed elsewhere.
From the rule's source, response_body_not_closed.rs.
package p import ( "io" "net/http" "time") func f(url string) ([]byte, error) { resp, err := http.Get(url)tx0 reports: the body of resp is never closed if err != nil { return nil, err } return io.ReadAll(resp.Body)} func g(url string) (int, error) { client := &http.Client{Timeout: time.Second} resp, err := client.Get(url)tx0 reports: the body of resp is never closed if err != nil { return 0, err } return resp.StatusCode, nil} func h(url string) ([]byte, error) { resp, err := http.DefaultClient.Get(url) if err != nil { return nil, err } defer resp.Body.Close() return io.ReadAll(resp.Body)} func returned(url string) (*http.Response, error) { resp, err := http.Get(url) return resp, err} func drained(url string) error { resp, err := http.Get(url) if err != nil { return err } drain(resp.Body) return nil} func drain(r io.ReadCloser) { r.Close() } func body(url string) (io.ReadCloser, error) { resp, err := http.Get(url) if err != nil { return nil, err } return resp.Body, nil} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/go:response-body-not-closed" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/go:response-body-not-closed] reason="..."tx0 explain tx0/go:response-body-not-closed shows the same in the terminal. Found a false positive? Report it.