I have this test program which will fetch url parallel, but when I increase the parallel number to about 1040, I start to get lookup www.httpbin.org: no such host error.
After some Google, I found others say that not close the response will cause the problem, but I do close that with res.Body.Close().
What’s the problem here? thanks very much.
package main
import (
"fmt"
"net/http"
"io/ioutil"
)
func get(url string) ([]byte, error) {
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return nil, err
}
bytes, read_err := ioutil.ReadAll(res.Body)
res.Body.Close()
fmt.Println(bytes)
return bytes, read_err
}
func main() {
for i := 0; i < 1040; i++ {
go get(fmt.Sprintf("http://www.httpbin.org/get?a=%d", i))
}
}
That’s because you may have up to 1040 concurrent calls in your code so you may very well be in a state with 1040 body opened and none yet closed.
You need to limit the number of goroutines used.
Here’s one possible solution with a limit to 100 concurrent calls max :
If you call this in the main function of your program, it may stop before all tasks are finished. You can use a
sync.WaitGroupto prevent it :