dongwen4630 2018-01-02 06:18
浏览 35
已采纳

第一次循环迭代后无效的内存地址或nil指针取消引用

When I return (A map slice) from GetCompanyFilingListRes and print the output my code runs fine for one iteration. But on the second iteration I get a panic: runtime error: invalid memory address or nil pointer dereference.

package main

import (
    "data/edgar"
    "fmt"
    "net/http"
)

func main() {
    url := "calltomylocalserver.com/page.html"
    res, _ := http.Get(url)
    for i := 0; i < 100000; i++ {
        // GetCompanyFilingListRes comsumes res.Body 
        // before returning a slice of maps
        m := edgar.GetCompanyFilingListRes(res)
        fmt.Println(m)
    }
}

I'm sure this is something quite simple I'm missing but I don't why res doesn't seem to be accessible after the first iteration. Is the GC removing it from memory? How would I stop this happening? Thanks.

Edit:

I think my mistake with this question was not including the fact that GetCompanyFilingListRes consumes the res.Body. And as leaf bebop mentioned it can only be consumed once.

There's a related answer I found here.

  • 写回答

1条回答 默认 最新

  • douqiao8032 2018-01-02 06:40
    关注

    It seems very likely to be because res is a Response and Response.Body is a ReadCloser which can only be consumed once.

    If you want to re-use the body, read it into a buffer (like []byte or a string) using ioutil.ReadAll. If you want extra data from res, use a struct to wrap it.

    If your use case auctually use different responses (which make more sense to me), move the http.Get into the loop. (Warning: fetch an url 1e5 times can cause trouble).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致