Response body must be closed

Following piece throws a linter warning. Please help me resolve the linter

if something {

        tr := &http.Transport{TLSClientConfig: config}

        client := &http.Client{Transport: tr}

        resp, err = client.Get(x5u) // Linter warning: response body must be closed

    } else {

        resp, err = http.Get(x5u)

    }

    if err != nil {

        return nil, err

    }

defer resp.Body.Close()

You have code pathes that won’t close the resp.Body(). If for some reason err is not nil, then your defer will never be reached. and therefore the body remains open.

I got the same warning even when I put defer before the err check

Where exactly? Best is to put the defer right after assigning the resp.

In case of error you don’t have to call defer resp.Body.Close(). Ref

It’s okay to ignore the linter this time. The defer statement is perfectly placed.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.