dsyq40772 2013-07-05 13:23
浏览 67
已采纳

为什么此程序可以在liteIde中运行,但是从终端运行时却由于无效的指针引用而崩溃?

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条回答 默认 最新

  • douyuqing_12345 2013-07-05 13:32
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?