What happens if you don't close response.Body in Go? Memory leak and other problems
Hi everyone! I just started learning Go and I'm writing a simple HTTP client to get data from an API. I have this code:
```go
resp, err := http.Get("https://api.example.com/data")
if err != nil {
log.Fatal(err)
}
// I don't close resp.Body
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
```
Everything works, the data arrives. But I noticed that in many examples on Stack Overflow and in Go documentation they write `defer resp.Body.Close()`. Honestly, I don't understand why this is needed if the program terminates immediately after reading the data? What bad things can happen if I forget to close `response.Body`? Memory leak? Program slowdown? Or is it not critical at all for small scripts? Please explain in simple terms what happens under the hood. Thanks in advance!
No answers yet.
Log in to leave an answer