Go: http client memory leak

Created on 17 May 2019  ·  2Comments  ·  Source: golang/go

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

FrozenDueToAge

Most helpful comment

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.

All 2 comments

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()
    }
}
Was this page helpful?
0 / 5 - 0 ratings