1. 带进度条大文件下载
1.1.2. 带进度条的大文件下载
import (
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/dustin/go-humanize"
)
type WriteCounter struct {
Total uint64
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.PrintProgress()
}
func (wc WriteCounter) PrintProgress() {
fmt.Printf("\r%s", strings.Repeat(" ", 35))
fmt.Printf("\rDownloading... %s complete", humanize.Bytes(wc.Total))
}
func main() {
fmt.Println("Download Started")
fileUrl := "http://topgoer.com/static/2/9.png"
err := DownloadFile("9.png", fileUrl)
if err != nil {
panic(err)
}
fmt.Println("Download Finished")
}
if err != nil {
return err
}
resp, err := http.Get(url)
if err != nil {
out.Close()
return err
}
defer resp.Body.Close()
counter := &WriteCounter{}
if _, err = io.Copy(out, io.TeeReader(resp.Body, counter)); err != nil {
out.Close()
return err
}
fmt.Print("\n")
out.Close()
if err = os.Rename(filepath+".tmp", filepath); err != nil {
return err
}
}