黑窗口下带进度条的http下载
packagemainimport("flag""fmt""io""log""net/http""os""strconv""strings""time""github.com/cheggaaa/pb")var(url=flag.String("url","","ThedownloadfileURL."))funcUsage(){fmt.Printf("Usageof%s:\n-url=\"http://www.xxx.com/file.exe\":ThedownloadfileURL.\n",os.Args[0])os.Exit(1)}funcmain(){flag.Parse()ifos.Args==nil||*url==""{Usage()}//解析/后的文件名字urlMap:=strings.Split(*url,"/")fileName:=urlMap[len(urlMap)-1]//解析带?=fileName的文件名字ifstrings.Contains(fileName,"="){splitName:=strings.Split(fileName,"=")fileName=splitName[len(splitName)-1]}resp,err:=http.Get(*url)iferr!=nil{log.Fatal(err)}//判断geturl的状态码,StatusOK=200ifresp.StatusCode==http.StatusOK{log.Printf("[INFO]正在下载:[%s]",fileName)fmt.Print("\n")downFile,err:=os.Create(fileName)iferr!=nil{log.Fatal(err)}//不要忘记关闭打开的文件.deferdownFile.Close()//获取下载文件的大小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.ShowSpeed=true//显示剩余时间bar.ShowTimeLeft=true//显示完成时间bar.ShowFinalTime=truebar.SetMaxWidth(80)bar.Start()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)}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。