This code has a memory leak. Memory grows with every request.
package main
import (
"fmt"
"net/http"
"io"
"io/ioutil"
"time"
)
func main() {
httpClient := &http.Client{}
for {
res, err := httpClient.Get("https://google.com/")
if err != nil {
return
}
defer res.Body.Close()
io.Copy(ioutil.Discard, res.Body)
fmt.Println(res.StatusCode)
time.Sleep( time.Second * 1 )
}
}
go version go1.12.5 windows/amd64
defer runs when the function (here main()) returns, so if you call it in a loop it is never going to run, and they will accumulate in memory, also keeping references to the request bodies.
Ok. I rewrote - the problem remains! Why do you close the ticket without checking in practice?
package main
import (
"fmt"
"net/http"
"io"
"io/ioutil"
"time"
)
func main() {
httpClient := &http.Client{}
for {
res, err := httpClient.Get("https://google.com/")
if err != nil {
return
}
io.Copy(ioutil.Discard, res.Body)
fmt.Println(res.StatusCode)
time.Sleep( time.Second * 1 )
res.Body.Close()
}
}
Most helpful comment
deferruns when the function (heremain()) returns, so if you call it in a loop it is never going to run, and they will accumulate in memory, also keeping references to the request bodies.