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

rai*_*luo 1 go

我刚开始学习Go lang,我写了一个小演示,从txt读取图片网址,将网址放入数组,然后将响应保存到文件中.

这是我的代码

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 \n", line)
        picUrl = append(picUrl, string(line))
    } else {
        file.Close()
        break
    }
}
fmt.Printf("file loaded,read to download \n")
fetchPic(picUrl)

}
func fetchPic(picUrl []string) {

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

    fmt.Printf("key is : %d,this line is %s \n\n", key, value)
    httpRequest, err := http.Get(string(value))
    fmt.Print("load ok \n")

    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 \n")
    }
    len := len(string(result))
    fmt.Printf("length is %d", len)
    if err == nil {
        httpRequest = nil
        //result = nil
    } else {
        fmt.Print("load falt!!!!!!!!! \n")
    }
    defer httpRequest.Body.Close()
}

}
Run Code Online (Sandbox Code Playgroud)

跑吧,我得到了

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
Run Code Online (Sandbox Code Playgroud)

meinv.txt,每个网址一行有人帮忙吗?THKS

Vol*_*ker 6

httpRequest, err := http.Get(string(value))没有检查错误的情况下,您正在从httpRequest.Body中无条件阅读:如果http.Get失败,您将无法httpRequest.Body读取有效内容.

经验法则:立即检查每个错误.