golang 進度下載檔案

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//一個沒找到工作的下午獨自擼起來的代碼//很不美觀臨時作品package mainimport (   "net/http"   "fmt"   "os"   "errors"   "io"   "strconv")func main() {   downloadFile("http://localhost:8089/ThunderSpeed1.0.35.366.exe", func(length, downLen int64) {      fmt.Println(length, downLen, float32(downLen)/float32(length))   })}func downloadFile(url string, fb func(length, downLen int64)) error {   var (      fsize   int64      buf     = make([]byte, 32*1024)      written int64   )   //建立一個http client   client := new(http.Client)   //get方法擷取資源   resp, err := client.Get(url)   if err != nil {      return err   }   //讀取伺服器返回的檔案大小   fsize, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 32)   if err != nil {      fmt.Println(err)   }   //建立檔案   file, err := os.Create("test.exe")   if err != nil {      return err   }   defer file.Close()   if resp.Body == nil {      return errors.New("body is null")   }   defer resp.Body.Close()   //下面是 io.copyBuffer() 的簡化版本   for {      //讀取bytes      nr, er := resp.Body.Read(buf)      if nr > 0 {         //寫入bytes         nw, ew := file.Write(buf[0:nr])         //資料長度大於0         if nw > 0 {            written += int64(nw)         }         //寫入出錯         if ew != nil {            err = ew            break         }         //讀取是資料長度不等於寫入的資料長度         if nr != nw {            err = io.ErrShortWrite            break         }      }      if er != nil {         if er != io.EOF {            err = er         }         break      }      //沒有錯誤了快使用 callback      fb(fsize, written)   }   return err}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.