Why does this program work in liteIde but crashes with invalid pointer reference when run from terminal?

huangapple go评论79阅读模式
英文:

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

huangapple
  • 本文由 发表于 2013年7月5日 21:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/17489977.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定