What could happen if I don't close response.Body?

后端 未结 4 2007
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 00:41

In Go, I have some http responses and I sometimes forget to call:

resp.Body.Close()

What happens in this case? will there be a memory leak

4条回答
  •  死守一世寂寞
    2020-11-29 00:53

    If Response.Body won't be closed with Close() method than a resources associated with a fd won't be freed. This is a resource leak.

    Closing Response.Body

    From response source:

    It is the caller's responsibility to close Body.

    So there is no finalizers bound to the object and it must be closed explicitly.

    Error handling and deferred cleanups

    On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned Response.Body is already closed.

    resp, err := http.Get("http://example.com/")
    if err != nil {
        // Handle error if error is non-nil
    }
    defer resp.Body.Close() // Close body only if response non-nil
    

提交回复
热议问题