Golang下载文件显示进度条

xiaohai 2021-05-05 21:46:53 3544人围观 标签: Go 
简介如何在命令行中使用下载文件的进度条

如何在命令行中使用下载文件的进度条,在Golang中的实现如下:

安装依赖库
go get github.com/cheggaaa/pb/v3
代码实现
package main

import (
    "github.com/cheggaaa/pb/v3"
    "io"
    "log"
    "net/http"
    "os"
    "strconv"
    "strings"
    "time"
)

func main() {
    url := "http://cdn.apifox.cn/download/apifox-win64-latest.zip"

    //获取文件名称
    urls := strings.Split(url, "/")
    filename := urls[len(urls)-1]

    client := http.DefaultClient
    client.Timeout = 60 * 10 * time.Second
    reps, err := client.Get(url)
    if err != nil {
        log.Panic(err.Error())
    }
    if reps.StatusCode == http.StatusOK {
        //保存文件
        file, err := os.Create(filename)
        if err != nil {
            log.Panic(err.Error())
        }
        defer file.Close() //关闭文件

        //获取下载文件的大小
        length := reps.Header.Get("Content-Length")
        size, _ := strconv.ParseInt(length, 10, 64)
        body := reps.Body //获取文件内容

        bar := pb.Full.Start64(size)
        bar.SetWidth(120)                         //设置进度条宽度
        bar.SetRefreshRate(10 * time.Millisecond) //设置刷新速率

        defer bar.Finish()
        // create proxy reader
        barReader := bar.NewProxyReader(body)

        //写入文件
        writer := io.Writer(file)
        io.Copy(writer, barReader)

    }
}
运行结果
> go run download.go
58.88 MiB / 58.88 MiB [-----------------------------------------------------------------------] 100.00% 11.46 MiB p/s 5s