我刚开始学习 Go lang,我写了一个小演示,从 txt 中读取图片 url,将 url 放在一个数组中,然后将响应保存到一个文件中。这是我的代码package mainimport ("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 stringfor 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 +0xb6main.fetchPic(0xc21239d000, 0x38be7, 0x4223c)/home/lyn/www/goOnDev/fetch.go:40 +0x24fmain.main()/home/lyn/www/goOnDev/fetch.go:28 +0x1b8exit status 2meinv.txt ,每个 url 一行 有人帮忙吗?谢谢
3 回答
- 3 回答
- 0 关注
- 232 浏览
添加回答
举报
0/150
提交
取消