欢迎光临
我们一直在努力

go语言学习例子No.39-简单的并发下载带进度

参考:

https://jasonkayzk.github.io/2020/09/30/%E4%BD%BF%E7%94%A8Go%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E8%BF%9B%E5%BA%A6%E6%9D%A1%E5%B9%B6%E5%8F%91%E4%B8%8B%E8%BD%BD%E5%99%A8/

https://github.com/vbauerster/mpb

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"
	"sync"

	"github.com/vbauerster/mpb/v7"
	"github.com/vbauerster/mpb/v7/decor"
)

type Resource struct {
	Filename string
	Url      string
}
type DownLoad struct {
	Resources []Resource
	Dir       string
	wg        *sync.WaitGroup
}

func main() {

	d := NewDownload("./")
	d.AppendResource("1.zip", "http://192.168.1.50:5000/api/v3/file/get/96/Etcher_V1.5.70_XiTongZhiJia.zip?sign=f9hI4r4KXjCwew9J5l2Xvcia8CAd4FQc_qxBA_Kczg4%3D%3A0")
	d.AppendResource("2.exe", "http://192.168.1.50:5000/api/v3/file/get/97/JDSoft_SurfMill8.0_X64_Pro_Setup.exe?sign=V7d4TW1HzZhWcBQj_MtNyVD4BonhsMpVTN6yzJ7iZyY%3D%3A0")
	d.Start()

}
func NewDownload(dir string) *DownLoad {
	return &DownLoad{
		Dir: dir,
		wg:  &sync.WaitGroup{},
	}

}
func (d *DownLoad) AppendResource(filename, url string) {
	d.Resources = append(d.Resources, Resource{
		Filename: filename,
		Url:      url,
	})

}
func (d *DownLoad) Start() {
	p := mpb.New(mpb.WithWaitGroup(d.wg))
	for _, v := range d.Resources {
		d.wg.Add(1)
		go d.download(v, p)
	}
	p.Wait()
	d.wg.Wait()

}

func (d *DownLoad) download(r Resource, p *mpb.Progress) {
	defer d.wg.Done()
	req, err := http.NewRequest("GET", r.Url, nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Println("Get失败", err)
	}
	defer resp.Body.Close()
	fileSize, _ := strconv.Atoi(resp.Header.Get("Content-Length"))

	var total int64 = int64(fileSize)

	bar := p.Add(int64(fileSize),
		mpb.NewBarFiller(mpb.BarStyle().Rbound("|")),
		mpb.PrependDecorators(
			decor.Name(r.Filename, decor.WC{W: len(r.Filename) + 1, C: decor.DidentRight}),
			decor.CountersKibiByte("% .2f / % .2f"),
		),
		mpb.AppendDecorators(
			decor.EwmaETA(decor.ET_STYLE_GO, 90),
			decor.Name(" ] "),
			decor.EwmaSpeed(decor.UnitKiB, "% .2f", 60),
		),
	)

	file, err := os.Create(r.Filename)
	if err != nil {
		fmt.Println("创建文件失败", err)
	}
	defer file.Close()
	// create proxy reader
	reader := io.LimitReader(resp.Body, total)
	proxyReader := bar.ProxyReader(reader)
	defer proxyReader.Close()

	// copy from proxyReader, ignoring errors
	_, err = io.Copy(file, proxyReader)
	if err != nil {
		fmt.Println("写入文件失败", err)
	}

}
 收藏 (0) 打赏

您可以选择一种方式赞助本站

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:家里蹲的狐狸 » go语言学习例子No.39-简单的并发下载带进度

分享到: 生成海报
avatar

热门文章

评论 抢沙发

  • QQ号
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

登录

忘记密码 ?

切换登录

注册

我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活