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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?