英文:
Why does this program work in liteIde but crashes with invalid pointer reference when run from terminal?
问题
当我在LiteIDE中运行此代码时,通过构建和运行命令,它可以正常工作。但是当我通过以下方式运行它时:
go run scraper.go
或者
go build scraper.go
./scraper
它在r.Body.Close()行失败,并显示错误信息:
panic: runtime error: invalid memory address or nil pointer dereference
以下是有问题的代码:
r, err := http.Get(job.Url)
defer r.Body.Close() //无论是否使用defer,都会出现相同的错误
脚本在这里:https://gist.github.com/meddulla/5934457,但基本上它通过post请求接受要爬取的URL,例如:
curl -X POST -d "[{\"url\": \"http://localhost:8888/IBTX/proj/dev/article.html\"}]" http://localhost:8080/jobs/add
我无法理解为什么它在LiteIDE中可以工作,但在终端中直接运行时却不行(程序可以正常启动,所以不是GOPATH设置或其他问题,只有在响应post请求时才会失败)。
有什么想法吗?
英文:
When I run this code in LiteIDE, via the build and run command, it works. But when I run it by
go run scraper.go
Or
go build scraper.go
./scraper
it fails in the r.Body.Close() line with the error
panic: runtime error: invalid memory address or nil pointer dereference
Here's the offending code:
r, err := http.Get(job.Url)
defer r.Body.Close() //same error with or without defer
The script is here: https://gist.github.com/meddulla/5934457 but it basically accepts urls to scrape via post requests, eg
curl -X POST -d "[{\"url\": \"http://localhost:8888/IBTX/proj/dev/article.html\"}]" http://localhost:8080/jobs/add
and I can't understand why it would work in liteIde but not when i run it directly in the terminal (the program starts ok, so its not a GOPATH setting or something, it only fails when responding to post requests)
Any ideias why?
答案1
得分: 6
你需要首先检查err是否为nil。
r, err := http.Get(job.Url)
if err != nil {
log.Fatal(err)
}
defer r.Body.Close() //无论是否使用defer,错误都是相同的
英文:
You need to check err isn't nil at first.
r, err := http.Get(job.Url)
if err != nil {
log.Fatal(err)
}
defer r.Body.Close() //same error with or without defer
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论