I am trying to poll a website multiple times but I get:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x38 pc=0x400cca]
package main
import (
"fmt"
"net/http"
)
var urls = []string{
"http://site-centos-64:8080/examples/abc1.jsp",
}
type HttpResponse struct {
url string
response *http.Response
err error
}
var ch = make(chan *HttpResponse, 1000) // buffered
func abc(i int){
for _, url := range urls {
resp, err := http.Get(url)
resp.Body.Close()
ch <- &HttpResponse{url, resp, err}
}
}
func asyncHttpGets(urls []string) []*HttpResponse {
responses := []*HttpResponse{}
for i:=0;i<1000;i++{
go abc(i)
}
for {
select {
case r := <-ch:
responses = append(responses, r)
if len(responses) == 1000 {
return responses
}
}
}
return responses
}
func main() {
results := asyncHttpGets(urls)
for _, result := range results {
fmt.Printf("%s status: %s
", result.url,
result.response.Status)
}
}
Works absolutely fine when I do it for 500 times.
The go stacktrace
contains which line of your code caused the panic. There are probably a lot of goroutines running but you can grep for your filename. I'd assume that you have some connection issues with your server.
Proper handling of err
in your abc
function should tell you more.
In case of an error, don't call resp.Body.Close()
. And in your main
function result.response.Status
won't work either.