golang實現多協程下載文件(支持斷點續傳)

引言

寫這篇文章主要是周末休息太無聊,看瞭看別人代碼,發現基本上要麼是多協程下載文件要麼就隻有單協程的斷點續傳,所以就試瞭試有進度條的多協程下載文件(支持斷點續傳)

package main

import (
 "fmt"
 "io"
 "os"
 "regexp"
 "strconv"
 "sync"

 "github.com/qianlnk/pgbar"
)

/**
* 需求:
1. 多協程下載文件
2.斷點續連
**/
func main() {
 //獲取要下載文件
 DownloadFileName := "./123.zip"
 //copy的文件
 copyFileName := "./test.zip"
 storgeFileName := "./current.txt"
 //打開文件
 sfile, err := os.Open(DownloadFileName)
 if err != nil {
  panic(err)
 }
 defer sfile.Close()
 //獲取文件大小
 info, _ := sfile.Stat()
 downloadSize := info.Size()
 var scount int64 = 1
 if downloadSize%5 == 0 {
  scount *= 5
 } else {
  scount *= 10
 }
 //分給每個協程的大小
 si := downloadSize / scount
 fmt.Printf("文件總大小:%v, 分片數:%v,每個分片大小:%v\n", downloadSize, scount, si)
 //open copy file
 copyFile, err := os.OpenFile(copyFileName, os.O_CREATE|os.O_WRONLY, os.ModePerm)
 if err != nil {
  panic(err)
 }
 storgeFile, err := os.OpenFile(storgeFileName, os.O_CREATE|os.O_RDWR, os.ModePerm)
 if err != nil {
  panic(err)
 }
 defer copyFile.Close()

 var currentIndex int64 = 0
 wg := sync.WaitGroup{}
 fmt.Println("協程進度條")
 pgb := pgbar.New("")
 for ; currentIndex < scount; currentIndex++ {
  wg.Add(1)
  go func(current int64) {
   p := pgb.NewBar(fmt.Sprint((current+1))+"st", int(si))
   // p.SetSpeedSection(900, 100)
   b := make([]byte, 1024)
   bs := make([]byte, 16)
   currentIndex, _ := storgeFile.ReadAt(bs, current*16)
   //取出所有整數
   reg := regexp.MustCompile(`\d+`)
   countStr := reg.FindString(string(bs[:currentIndex]))
   total, _ := strconv.ParseInt(countStr, 10, 0)
   progressBar := 1
   for {
    if total >= si {
     wg.Done()
     break
    }
    //從指定位置開始讀
    n, err := sfile.ReadAt(b, current*si+total)
    if err == io.EOF {
     wg.Done()
     break
    }
    //從指定位置開始寫
    copyFile.WriteAt(b, current*si+total)
    storgeFile.WriteAt([]byte(strconv.FormatInt(total, 10)+" "), current*16)
    total += int64(n)
    if total >= si/10*int64(progressBar) {
     progressBar += 1
     p.Add(int(si / 10))
    }

   }

  }(currentIndex)
 }
 wg.Wait()
 storgeFile.Close()
 os.Remove(storgeFileName)
 fmt.Println("下載完成")
}

到此這篇關於golang實現多協程下載文件(支持斷點續傳)的文章就介紹到這瞭,更多相關golang 多協程下載文件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: