Skip to content

Resource leak in select chapter: HTTP response bodies not closed #888

@penev-ff

Description

@penev-ff

While running the Racer example from the select chapter, I noticed a connection/file descriptor leak.
Each call to http.Get in measureResponseTime and ping opens a connection that isn't closed:

func measureResponseTime(url string) time.Duration {
	start := time.Now()
	http.Get(url)  // Response body is never closed
	return time.Since(start)
}

I wrote a test to count open file descriptors before and after calling Racer multiple times:

go test  -v
=== RUN   TestRacerLeaksFDs
    racer_leak_test.go:29: FDs before: 18
    racer_leak_test.go:36: FDs after: 218
    racer_leak_test.go:39: LEAKED: 200 file descriptors
--- FAIL: TestRacerLeaksFDs (0.06s)
FAIL
exit status 1
FAIL    temp    0.074s

Adding a defer resp.Body.Close() after a successful http.Get call resolves the leak:

func measureResponseTime(url string) time.Duration {
	start := time.Now()
	resp, err := http.Get(url)
	if err == nil {
		defer resp.Body.Close()
	}
	return time.Since(start)
}
go test  -v
=== RUN   TestRacerLeaksFDs
    racer_leak_test.go:29: FDs before: 18
    racer_leak_test.go:36: FDs after: 18
--- PASS: TestRacerLeaksFDs (0.04s)
PASS
ok      temp    0.048s

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions