码迷,mamicode.com
首页 > Web开发 > 详细

黑窗口下带进度条的http下载

时间:2015-10-10 12:47:58      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:http下载   进度条   黑窗口   

package main


import (

"flag"

"fmt"

"io"

"log"

"net/http"

"os"

"strconv"

"strings"

"time"


"github.com/cheggaaa/pb"

)


var (

url = flag.String("url", "", "The download file URL.")

)


func Usage() {

fmt.Printf("Usage of %s:\n  -url=\"http://www.xxx.com/file.exe\": The download file URL.\n", os.Args[0])

os.Exit(1)

}


func main() {

flag.Parse()


if os.Args == nil || *url == "" {

Usage()

}


urlMap := strings.Split(*url, "/")

fileName := urlMap[len(urlMap)-1]


if strings.Contains(fileName, "=") {

splitName := strings.Split(fileName, "=")

fileName = splitName[len(splitName)-1]

}


resp, err := http.Get(*url)

if err != nil {

log.Fatal(err)

}


if resp.StatusCode == http.StatusOK {

log.Printf("[INFO] 正在下载: [%s]", fileName)

fmt.Print("\n")


downFile, err := os.Create(fileName)

if err != nil {

log.Fatal(err)

}

i, _ := strconv.Atoi(resp.Header.Get("Content-Length"))

sourceSiz := int64(i)

source := resp.Body


bar := pb.New(int(sourceSiz)).SetUnits(pb.U_BYTES).SetRefreshRate(time.Millisecond * 10)

bar.Start()


bar.ShowSpeed = true

bar.ShowFinalTime = true

bar.SetMaxWidth(80)


writer := io.MultiWriter(downFile, bar)


io.Copy(writer, source)

bar.Finish()


fmt.Print("\n")

log.Printf("[INFO] [%s]下载成功.", fileName)


} else {

fmt.Print("\n")

log.Printf("[ERROR] [%s]下载失败,%s.", fileName, resp.Status)

}


}


本文出自 “CodyGuo” 博客,请务必保留此出处http://codyguo.blog.51cto.com/10440635/1701368

黑窗口下带进度条的http下载

标签:http下载   进度条   黑窗口   

原文地址:http://codyguo.blog.51cto.com/10440635/1701368

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!