dongzecai0684 2014-01-10 12:11
浏览 84
已采纳

使用http.Get()时无效的内存地址或nil指针取消引用

I just start to learn Go lang,I wrote a small demo,read picture urls from txt,put urls in an array,then Save the Response into a file.

Here is my code

package main

import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
)

func main() {
fileName := "meinv.txt"
file, _ := os.Open(fileName)

picUrl := make([]string, 2000)
reader := bufio.NewReader(file)
for {
    line, _, err := reader.ReadLine()
    if err != io.EOF {
        fmt.Printf("file load %s 
", line)
        picUrl = append(picUrl, string(line))
    } else {
        file.Close()
        break
    }
}
fmt.Printf("file loaded,read to download 
")
fetchPic(picUrl)

}
func fetchPic(picUrl []string) {

var file string
for key, value := range picUrl {

    fmt.Printf("key is : %d,this line is %s 

", key, value)
    httpRequest, err := http.Get(string(value))
    fmt.Print("load ok 
")

    httpRequest.Body.Close()
    result, readErr := ioutil.ReadAll(httpRequest.Body)
    if readErr == nil {
        file = "pics/" + string(key) + ".jpg"
        ioutil.WriteFile(file, result, 0777)
        fmt.Print("Write ok 
")
    }
    len := len(string(result))
    fmt.Printf("length is %d", len)
    if err == nil {
        httpRequest = nil
        //result = nil
    } else {
        fmt.Print("load falt!!!!!!!!! 
")
    }
    defer httpRequest.Body.Close()
}

}

run it ,and I got

key is : 0,this line is  

load ok 
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x40 pc=0x40123f]

goroutine 1 [running]:
runtime.panic(0x5f8300, 0x877688)
/usr/local/go/src/pkg/runtime/panic.c:266 +0xb6
main.fetchPic(0xc21239d000, 0x38be7, 0x4223c)
/home/lyn/www/goOnDev/fetch.go:40 +0x24f
main.main()
/home/lyn/www/goOnDev/fetch.go:28 +0x1b8
exit status 2

meinv.txt ,one line per url Anyone help?THKS

  • 写回答

3条回答 默认 最新

  • dougu3591 2014-01-10 12:57
    关注

    You are reading unconditional from httpRequest.Body after doing httpRequest, err := http.Get(string(value)) without checking err: If http.Get fails you won't have a valid httpRequest.Body to read from.

    Rule of thumb: Check each and every error immediately.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)