1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| package main
import ( "crypto/md5" "encoding/hex" "fmt" "io" "net/http" "strconv" )
func main() { ret, err := download("http://....") if err != nil { fmt.Println(err) } fmt.Println(ret) }
func download(url string) (string, error) { var ( err error resp *http.Response contentLen int64 downloadLen int ) if resp, err = http.Get(url); err != nil { return "", err }
if contentLen, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64); err != nil { return "", err }
defer func() { _ = resp.Body.Close() fmt.Print("\n") }()
h := md5.New() for { buf := make([]byte, 1024) c, e := resp.Body.Read(buf) if e != nil && e != io.EOF { return "", e } downloadLen += c
printProgress(downloadLen, contentLen)
h.Write(buf[0:c])
if e != nil && e == io.EOF { break } } return hex.EncodeToString(h.Sum(nil)), nil }
func printProgress(downloadLen int, contentLen int64) { fmt.Printf("\r") fmt.Printf("Downloading... %d of %d", downloadLen, contentLen) }
|