package main
import (
"fmt"
"io"
"net/http"
"os"
"sync"
)
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() {
for _, v := range d.Resources {
d.wg.Add(1)
go download(v, d.wg)
}
d.wg.Wait()
}
func download(r Resource, wg *sync.WaitGroup) {
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"))
// fmt.Println("filesize:", fileSize)
file, err := os.Create(r.Filename)
defer file.Close()
if err != nil {
fmt.Println("创建文件失败", err)
}
_, err = io.Copy(file, resp.Body)
if err != nil {
fmt.Println("写入文件失败", err)
}
fmt.Println(r.Filename, "下载完成!")
wg.Done()
}
go语言学习例子No.38-简单的并发下载
未经允许不得转载:家里蹲的狐狸 » go语言学习例子No.38-简单的并发下载