Skip to content

Instantly share code, notes, and snippets.

@heppu
Last active June 28, 2017 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heppu/8114997c980609fb5a3ce82c78636e99 to your computer and use it in GitHub Desktop.
Save heppu/8114997c980609fb5a3ce82c78636e99 to your computer and use it in GitHub Desktop.
Go http client file descriptor leak
/*
File that demostrates file descriptor leak
in case the client forgets to close response body
*/
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"sync"
)
const CLOSE = false
func main() {
wg := &sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
resp, err := http.Get("https://github.com/")
if err != nil {
fmt.Println(err)
return
}
if CLOSE {
resp.Body.Close()
}
}()
}
wg.Wait()
pid := fmt.Sprint(os.Getpid())
if files, err := ioutil.ReadDir(path.Join("/proc", pid, "/fd")); err != nil {
fmt.Println(err)
} else {
fmt.Println(len(files))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment