| | |
| | | import ( |
| | | "bytes" |
| | | "encoding/json" |
| | | "fmt" |
| | | "github.com/ajg/form" |
| | | "io" |
| | | "io/ioutil" |
| | | "net/http" |
| | | "os" |
| | | "strings" |
| | | "github.com/dustin/go-humanize" |
| | | ) |
| | | |
| | | const ( |
| | |
| | | return resultBytes, err |
| | | } |
| | | return resultBytes, nil |
| | | } |
| | | } |
| | | |
| | | |
| | | type WriteCounter struct { |
| | | Total uint64 |
| | | } |
| | | |
| | | func (wc WriteCounter) PrintProgress() { |
| | | fmt.Printf("\r%s", strings.Repeat(" ", 35)) |
| | | fmt.Printf("/rDownloading... %s complete", humanize.Bytes(wc.Total)) |
| | | } |
| | | |
| | | func (wc *WriteCounter) Write(p []byte) (int, error) { |
| | | n := len(p) |
| | | wc.Total = uint64(n) |
| | | wc.PrintProgress() |
| | | return n, nil |
| | | } |
| | | |
| | | //下载文件 |
| | | func DownloadFile(fPath string, url string) error { |
| | | f, err := os.Create(fPath) |
| | | if err != nil { |
| | | return err |
| | | } |
| | | resp, err := http.Get(url) |
| | | if err != nil { |
| | | f.Close() |
| | | return err |
| | | } |
| | | defer resp.Body.Close() |
| | | counter := &WriteCounter{} |
| | | if _, err = io.Copy(f, io.TeeReader(resp.Body, counter)); err != nil { |
| | | f.Close() |
| | | return err |
| | | } |
| | | fmt.Printf("\n") |
| | | f.Close() |
| | | if err = os.Rename(fPath, fPath);err != nil { |
| | | return err |
| | | } |
| | | return nil |
| | | } |
| | | |