Golang不知道大家是否熟悉?今天我将给大家介绍《Go语言实现HTTP文件下载显示进度条》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!
我不久前看到一篇文章,其中使用了 github.com/cheggaaa/pb 包的进度条功能:
func download(destinationPath, downloadUrl string) error {
tempDestinationPath := destinationPath + ".tmp"
request, err := http.NewRequest("GET", downloadUrl, nil)
...
var progressBar *pb.ProgressBar
contentLength := strconv.Atoi(request.Header.Get("Content-Length"))
...
io.MultiWriter(writer, progressBar)
...
我在一些代码中使用了它,但是几天前我丢失了该代码,并且我无法在任何地方再次找到该函数。如果有人能帮我至少重写它,我将非常感激。它使用 io.writer 和 io.multiwriter 将数据写入文件并立即增加进度条。感谢您的帮助!
正确答案
我发现了一个类似的包。 https://github.com/schollz/progressbar
func download(destinationPath, downloadUrl string) error {
tempDestinationPath := destinationPath + ".tmp"
req, _ := http.NewRequest("GET", downloadUrl, nil)
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
f, _ := os.OpenFile(tempDestinationPath, os.O_CREATE|os.O_WRONLY, 0644)
bar := progressbar.DefaultBytes(
resp.ContentLength,
"downloading",
)
io.Copy(io.MultiWriter(f, bar), resp.Body)
os.Rename(tempDestinationPath, destinationPath)
return nil理论要掌握,实操不能落!以上关于《Go语言实现HTTP文件下载显示进度条》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
