🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ### 理解 ***** 只显示总长度,跟已经下载长度的进度 ``` package main import ( "errors" "fmt" "io" "net/http" "os" "strconv" ) type printlen func(int64, int64) func main() { url := "http://108.61.224.82/627/Chrome53_Goflyway_2019.6.27.7z" downfile(url, barlen) } func downfile(url string, fb printlen ) error{ var ( fsize int64 buf = make([]byte, 32*1024) written int64 ) name := "Chrome53_Goflyway_2019.6.27.7z" // MARK:- 创建一个http client client := new(http.Client) // MARK:- get方法获取资源 resp, err := client.Get(url) if nil != err { return err } // MARK:- 读取服务器返回的文件大小 fsize, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 32) if nil != err { fmt.Print(err) } //MARK:- 创建文件 file, err := os.Create(name) if nil != err { fmt.Print(err) } defer file.Close() if resp.Body == nil { return errors.New("body is nil") } //MARK:- io.copyBuffer()的简化版本 for { // MARK:- 读取bytes nr, er := resp.Body.Read(buf) if nil != er{ err = er break } if nr > 0 { // MARK:- 写入buf nw, ew := file.Write(buf[0:nr]) if nw > 0 { written += int64(nw) } if ew != nil { //写入错误 err = ew break } if nr != nw { err = io.ErrShortWrite break } if nil != er { if er != io.EOF { err = er } break } fb(fsize, written) } } return err } func barlen(length, downLen int64) { fmt.Println(length, downLen, float32(downLen)/float32(length)) } ``` ### 拿来主义 ``` package main import ( "fmt" "io" "log" "net/http" "os" "strconv" "strings" "time" "gopkg.in/cheggaaa/pb.v1" ) func main() { url := "http://108.61.224.82/627/Chrome53_Goflyway_2019.6.27.7z" // 解析/后的文件名字 urlMap := strings.Split(url, "/") fileName := urlMap[len(urlMap)-1] // 解析带? = fileName 的文件名字 if strings.Contains(fileName, "=") { splitName := strings.Split(fileName, "=") fileName = splitName[len(splitName)-1] } client := http.DefaultClient client.Timeout = time.Second * 60 * 10 //设置超时时间 resp, err := client.Get(url) if err != nil { log.Fatal(err) } // 判断get url的状态码, StatusOK = 200 if resp.StatusCode == http.StatusOK { log.Printf("[INFO] 正在下载: [%s]", fileName) fmt.Print("\n") downFile, err := os.Create(fileName) if err != nil { log.Fatal(err) } // 不要忘记关闭打开的文件. defer downFile.Close() // 获取下载文件的大小 i, _ := strconv.Atoi(resp.Header.Get("Content-Length")) sourceSiz := int64(i) source := resp.Body // 创建一个进度条 bar := pb.New(int(sourceSiz)).SetUnits(pb.U_BYTES_DEC).SetRefreshRate(time.Millisecond * 10) // 显示下载速度 bar.ShowSpeed = true // 显示剩余时间 bar.ShowTimeLeft = true // 显示完成时间 bar.ShowFinalTime = true bar.SetWidth(80) bar.Start() writer := io.MultiWriter(downFile, bar) io.Copy(writer, source) bar.Finish() fmt.Print("\n") log.Printf("[INFO] [%s]下载成功.", fileName) } else { fmt.Print("\n") log.Printf("[ERROR] [%s]下载失败,%s.", fileName, resp.Status) } } ```