【问题标题】:HTTP file download progress bar in GoGo 中的 HTTP 文件下载进度条
【发布时间】:2022-10-15 13:41:52
【问题描述】:

不久前我看到一个帖子,其中包含使用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 将数据写入文件并立即增加进度条。感谢您的帮助!

【问题讨论】:

    标签: http go


    【解决方案1】:

    我发现了一个类似的包。 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
    

    【讨论】:

      【解决方案2】:

      还有很多其他的开源包,试试这个: https://github.com/schollz/progressbar

      例子:

      【讨论】:

        猜你喜欢
        • 2013-10-31
        • 1970-01-01
        • 2016-10-01
        • 2013-10-17
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 2016-07-30
        相关资源
        最近更新 更多