Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http client memory leak #32110

Closed
0x000777 opened this issue May 17, 2019 · 2 comments
Closed

http client memory leak #32110

0x000777 opened this issue May 17, 2019 · 2 comments

Comments

@0x000777
Copy link

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

@FiloSottile
Copy link
Contributor

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.

@0x000777
Copy link
Author

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()
	}
}

@golang golang locked and limited conversation to collaborators May 16, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants