HTTP Response Body Not Closed

response body must be closed (bodyclose linter)

Quick Answer

Always close the HTTP response body with defer resp.Body.Close() after checking the error. Not closing it causes connection leaks.

Why This Happens

HTTP response bodies in Go must be closed to release the underlying TCP connection back to the pool. Failing to close the body causes connection leaks that eventually exhaust available connections and cause timeouts or out-of-file-descriptor errors.

The Problem

func fetch(url string) ([]byte, error) {
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    // resp.Body never closed!
    return io.ReadAll(resp.Body)
}

The Fix

func fetch(url string) ([]byte, error) {
    resp, err := http.Get(url)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()
    return io.ReadAll(resp.Body)
}

Step-by-Step Fix

  1. 1

    Identify unclosed bodies

    Find HTTP calls where resp.Body.Close() is not called or not deferred.

  2. 2

    Add defer close

    Add defer resp.Body.Close() immediately after the error check on the HTTP call.

  3. 3

    Handle the error check order

    Always check the error before deferring close, because resp may be nil on error.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free