introduction
I wrote this article mainly because I was too bored to have a weekend break. After looking at other people's code, I found that basically either multiple coroutine download files or only single coroutine interrupts, so I tried multi-coroutine download files with progress bars (supported breakpoint continuous transmission)
package main import ( "fmt" "io" "os" "regexp" "strconv" "sync" "/qianlnk/pgbar" ) /** * need: 1. Multi-coroutine download file 2. Breakpoints continue **/ func main() { //Get the file to be downloaded DownloadFileName := "./" //copy file copyFileName := "./" storgeFileName := "./" //Open the file sfile, err := (DownloadFileName) if err != nil { panic(err) } defer () //Get file size info, _ := () downloadSize := () var scount int64 = 1 if downloadSize%5 == 0 { scount *= 5 } else { scount *= 10 } //The size assigned to each coroutine si := downloadSize / scount ("Total file size: %v, number of shards: %v, size of each shard: %v\n", downloadSize, scount, si) //open copy file copyFile, err := (copyFileName, os.O_CREATE|os.O_WRONLY, ) if err != nil { panic(err) } storgeFile, err := (storgeFileName, os.O_CREATE|os.O_RDWR, ) if err != nil { panic(err) } defer () var currentIndex int64 = 0 wg := {} ("Coprocess progress bar") pgb := ("") for ; currentIndex < scount; currentIndex++ { (1) go func(current int64) { p := (((current+1))+"st", int(si)) // (900, 100) b := make([]byte, 1024) bs := make([]byte, 16) currentIndex, _ := (bs, current*16) //Take out all integers reg := (`\d+`) countStr := (string(bs[:currentIndex])) total, _ := (countStr, 10, 0) progressBar := 1 for { if total >= si { () break } //Read from the specified location n, err := (b, current*si+total) if err == { () break } //Start write from the specified location (b, current*si+total) ([]byte((total, 10)+" "), current*16) total += int64(n) if total >= si/10*int64(progressBar) { progressBar += 1 (int(si / 10)) } } }(currentIndex) } () () (storgeFileName) ("Download Completed") }
This is the article about golang implementing multi-coroutine download files (supporting breakpoint continuous transmission). For more related golang multi-coroutine download files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!