github.com/iikira/iikira-go-utils@v0.0.0-20230610031953-f2cb11cde33a/requester/downloader/example.go (about) 1 package downloader 2 3 import ( 4 "fmt" 5 "github.com/iikira/iikira-go-utils/requester/transfer" 6 "github.com/iikira/iikira-go-utils/utils/converter" 7 "io" 8 "os" 9 ) 10 11 // DoDownload 执行下载 12 func DoDownload(durl string, savePath string, cfg *Config) { 13 var ( 14 file *os.File 15 writer io.WriterAt 16 err error 17 ) 18 19 if savePath != "" { 20 writer, file, err = NewDownloaderWriterByFilename(savePath, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666) 21 if err != nil { 22 fmt.Println(err) 23 return 24 } 25 defer file.Close() 26 } 27 28 download := NewDownloader(durl, writer, cfg) 29 30 exitDownloadFunc := make(chan struct{}) 31 32 download.OnDownloadStatusEvent(func(status transfer.DownloadStatuser, workersCallback func(RangeWorkerFunc)) { 33 var ts string 34 if status.TotalSize() <= 0 { 35 ts = converter.ConvertFileSize(status.Downloaded(), 2) 36 } else { 37 ts = converter.ConvertFileSize(status.TotalSize(), 2) 38 } 39 40 fmt.Printf("\r ↓ %s/%s %s/s in %s ............", 41 converter.ConvertFileSize(status.Downloaded(), 2), 42 ts, 43 converter.ConvertFileSize(status.SpeedsPerSecond(), 2), 44 status.TimeElapsed(), 45 ) 46 }) 47 48 err = download.Execute() 49 close(exitDownloadFunc) 50 if err != nil { 51 fmt.Printf("err: %s\n", err) 52 } 53 }