timakin/bodyclose

Close in another function's defer function is not handled correctly

sejust opened this issue · 0 comments

Here is the sample code to reproduce:

package main

import (
        "net/http"
)

func closeByCall(res *http.Response) {
        defer res.Body.Close()
}

func closeByCallDefer(res *http.Response) {
        defer func() {
                res.Body.Close()
        }()
}

func responseCall() {
        res, _ := http.Get("https://example.com")
        closeByCall(res)
}

func responseCallDefer() {
        res, _ := http.Get("https://example.com")
        closeByCallDefer(res)
}

func main() {
        responseCall()
        responseCallDefer()
}

And the result with go vet:

go vet -vettool=$(which bodyclose) .
# mod
./main.go:23:20: response body must be closed