英文:
Goroutine gives error
问题
我正在尝试多次轮询一个网站,但是出现了以下错误:
panic: 运行时错误:无效的内存地址或空指针解引用
[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 状态: %s\n", result.url,
result.response.Status)
}
}
当我将其执行500次时,完全正常。
英文:
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\n", result.url,
result.response.Status)
}
}
Works absolutely fine when I do it for 500 times.
答案1
得分: 1
go的stacktrace
包含了导致panic的代码行。可能有很多goroutine在运行,但你可以使用grep命令查找你的文件名。
我猜你的服务器有一些连接问题。
在你的abc
函数中正确处理err
应该能提供更多信息。
如果发生错误,不要调用resp.Body.Close()
。在你的main
函数中,result.response.Status
也不会起作用。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论