gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:50:29 25 4
gpt4 key购买 nike

刚开始学习Go语言,写了一个小demo,从txt中读取图片url,将url放入数组,然后将Response保存到文件中。

这是我的代码

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()
}

}

运行它,我得到了

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 , 每个 url 一行有人帮忙吗?THKS

最佳答案

在执行 httpRequest, err := http.Get(string(value)) 之后,您正在无条件地从 httpRequest.Body 读取,而没有检查 err: If http.Get 失败你将没有一个有效的 httpRequest.Body 来读取。

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

关于go - 使用 http.Get() 时无效的内存地址或 nil 指针取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21044079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com