I'm trying to download a image from a site, and the steps are as follow:
- use
http.Get
to fetch the image - use
os.Create
to create a new file in current folder - use
io.copyN
to copy the image into the file
But it is weird if the io.CopyN
is failed at the first time, it seems never success later
code fragment:
download_again:
copy_byte, copy_err := io.CopyN(file, res.Body, res.ContentLength)
fmt.Fprintf(os.Stderr, "img(%s) size: %d
", name, res.ContentLength)
if copy_err == nil && res.ContentLength == copy_byte {
fmt.Fprintf(os.Stderr, "Success to download img(%s)[%f KB(%d B)]: %s
", img_url, float64(copy_byte)/1024, copy_byte, name)
} else {
if try_i > download_times {
fmt.Fprintf(os.Stderr, "[fatal] fail to download img(%s) %s
", img_url, name)
fout.WriteString(name + "
")
return
}
fmt.Fprintf(os.Stderr, "error in download img(%s)[%f KB(%d B)]: %s, try %d times
", img_url, float64(copy_byte)/1024, copy_byte, name, try_i)
try_i++
goto download_again
}
and the output message:
img(11085) size: 273047
error in download img(./style/images/dszp/11085.jpg)[171.447266 KB(175562 B)]: 11085 , try 1 times
img(11085) size: 273047
error in download img(./style/images/dszp/11085.jpg)[0.000000 KB(0 B)]: 11085 , try 2 times
img(11085) size: 273047
error in download img(./style/images/dszp/11085.jpg)[0.000000 KB(0 B)]: 11085, try 3 times
img(11085) size: 273047
error in download img(./style/images/dszp/11085.jpg)[0.000000 KB(0 B)]: 11085, try 4 times
img(11085) size: 273047
error in download img(./style/images/dszp/11085.jpg)[0.000000 KB(0 B)]: 11085, try 5 times
img(11085) size: 273047
error in download img(./style/images/dszp/11085.jpg)[0.000000 KB(0 B)]: 11085, try 6 times
Any help will be appreciated :)