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

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计