使用go协程和channel管道实现下载
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
// "strconv"
"strings"
)
func download(url string, name string, ret chan<- struct{}) {
// fmt.Println(name)
if name == "" {
names := strings.Split(url, "/")
name = names[len(names)-1]
}
// fmt.Println(name)
response, err := http.Get(url)
defer response.Body.Close()
if err != nil {
fmt.Println(err)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err)
}
file, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
fmt.Println(err)
}
defer file.Close()
_, er := file.Write(body)
if er != nil {
fmt.Println(er)
}
// fmt.Println(string(body))
// close(ret)
ret <- struct{}{}
}
func main() {
urls := []string{"https://gloimg.zafcdn.com/zaful/pdm-product-pic/Clothing/2017/10/23/source-img/20171023104754_59693.png", "https://gloimg.zafcdn.com/zaful/pdm-product-pic/Clothing/2018/05/26/source-img/20180526163835_98732.png"}
ret := make(chan struct{}, len(urls))
// fmt.Println(len(urls))
i := 0
for _, url := range urls {
go download(url, "", ret)
i += 2
}
// select {}
for i := 0; i < len(urls); i++ {
// fmt.Println(<-ret)
<-ret
}
}
result: