dsx58940 2015-04-24 06:38
浏览 14
已采纳

http.client的图“无效的内存地址……”来源

I learning the go and struggling with this panic error... it working for some time, but soon end up with such exception panic: runtime error: invalid memory address or nil pointer dereference

The function simply iterate over map of proxies until it successfully get the content of the "address". It must be not very idiomatic, especially using map instead of slice and the last return, but I hope that is not the reason of panic crush... if I omitted something possible important please, let me know, I will update the post, I just do not want to flood it with unnecessary info. proxies is a struct with map field with methods for concurrent safe read/delete.

func getContent(address string) string {
localProxies := proxies.Get()
for proxy := range localProxies {
    proxyUrl, _ := url.Parse("http://" + proxy)

    transport := http.Transport{
        Dial:  dialTimeout,
        Proxy: http.ProxyURL(proxyUrl),
    }
    httpClient := http.Client{Transport: &transport, Timeout: timeout}
    req, err := http.NewRequest("GET", address, nil)
    if err != nil {
        fmt.Println("Request error: ", err.Error())
    }
    req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0")
    res, err := httpClient.Do(req)
    defer res.Body.Close()

    if err != nil {
        //          fmt.Println("Broken ", proxy)
        fmt.Println("Response error: ", err.Error())
        proxies.Del(proxy)
        continue
    }
    if res.StatusCode != 200 {
        //          fmt.Println("Status error: ", res.Status)
        proxies.Del(proxy)
        continue
    }
    out, err := ioutil.ReadAll(res.Body)
    if err != nil {
        fmt.Println("Read error: ", err.Error())
        proxies.Del(proxy)
        continue
    }
    return string(out)
}
return "error"

}

go version go1.4.2 linux/amd64

  • 写回答

1条回答 默认 最新

  • dragon202076 2015-04-24 06:44
    关注

    Until I see more information, this is simply a guess based on what I could gather from the code you posted.

    The call

    res.Body.Close()
    

    should come after your check for error, not before. So change:

     res, err := httpClient.Do(req)
     defer res.Body.Close()
     if err != nil {
         ...
     }
    

    to

     res, err := httpClient.Do(req)
     if err != nil {
         ...
     }
     defer res.Body.Close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求一下解题思路,完全不懂
  • ¥15 tensorflow
  • ¥15 densenet网络结构中,特征以cat方式复用后是怎么进行误差回传的
  • ¥15 STM32G471芯片spi设置了8位,总是发送16位
  • ¥15 R语言并行计算beta-NTI中tree文件的类型
  • ¥15 如何解读marsbar导出的ROI数据?
  • ¥20 求友友协助弄一下基于STC89C52单片机的声光控制灯原理图
  • ¥15 arduino双向交通灯设计
  • ¥15 有没有会粒子群算法的大能(○゜ε^○)求带不会出收敛图😭
  • ¥15 Matlab读取根元素出错