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).

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

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办