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

后端 未结 4 2004
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  Happy的楠姐
    2020-11-29 00:56

    See https://golang.org/src/net/http/client.go
    "When err is nil, resp always contains a non-nil resp.Body."

    but they do not say when err != nil, resp always is nil. They go on to say:
    "If resp.Body is not closed, the Client's underlying RoundTripper (typically Transport) may not be able to re-use a persistent TCP connection to the server for a subsequent "keep-alive" request."

    So I have typically solved the issue like this:

    client := http.DefaultClient
    resp, err := client.Do(req)
    if resp != nil {
       defer resp.Body.Close()
    }
    if err != nil {
        return nil, err 
    }
    

提交回复
热议问题