gpt4 book ai didi

arrays - 跟踪并显示下载文件摘要(百分比) - Go lang

转载 作者:IT王子 更新时间:2023-10-29 00:54:25 26 4
gpt4 key购买 nike

我正在执行一个通过传递的 url 参数下载文件的过程。下载正在正确完成,但我不能做的是打印已完成下载百分比的摘要。 (每秒)

我构建了一种模拟的这种摘要,但它没有下载任何东西,它只是为了展示我想要它的方式。

我试图将 io.copy 放入我的源代码中,这样我就可以在复制完成时更改它,但它失败了。

有人可以帮助我吗?谢谢

 package main

import (
"fmt"
"io"
"net/http"
"os"
"strings"
// "time"
)

func downloadFromUrl(url string) {
tokens := strings.Split(url, "/")
fileName := tokens[len(tokens)-1]
fmt.Println("Downloading", url, "to", fileName)

//create file
output, err := os.Create(fileName)
if err != nil {
fmt.Println("Error while creating", fileName, "-", err)
return
}
fmt.Println("Creating", fileName)
defer output.Close()

//get url
response, err := http.Get(url)
if err != nil {
fmt.Println("Error while downloading", url, "-", err)
return
}
defer response.Body.Close()

//copy and bytes
n, err := io.Copy(output, response.Body)
if err != nil {
fmt.Println("Error while downloading", url, "-", err)
return
}

//track progress
for i := 1; float64(i) < float64(n); i++ {
fmt.Println("",float64(i),float64(n))
percent := float64(i) / (float64(n) / float64(100))
percentTot := fmt.Sprintf(" %#.02f%% ", percent)
fmt.Println(percentTot,"downloaded\n")
//time.Sleep(3000 * time.Millisecond)
}


}

func main() {
//read args
args := os.Args

//loop args
for i := 1; i < len(args); i++ {
url := args[i]
//call download
downloadFromUrl(url)
}
}


**Output:**
go run main.go http://download.geonames.org/export/dump/AD.zip
Downloading http://download.geonames.org/export/dump/AD.zip to AD.zip
Creating AD.zip
1 64639
0.00% downloaded

2 64639
0.00% downloaded

3 64639
0.00% downloaded

4 64639
0.01% downloaded

5 64639
0.01% downloaded

最佳答案

我已经在我的 senvgo project 中做到了使用 io.Reader 包装器

// PassThru wraps an existing io.Reader.
//
// It simply forwards the Read() call, while displaying
// the results from individual calls to it.
type PassThru struct {
io.Reader
total int64 // Total # of bytes transferred
length int64 // Expected length
progress float64
}

您在该包装器上定义一个 Read() 方法(使其成为一个 io.Reader)

// Read 'overrides' the underlying io.Reader's Read method.
// This is the one that will be called by io.Copy(). We simply
// use it to keep track of byte counts and then forward the call.
func (pt *PassThru) Read(p []byte) (int, error) {
n, err := pt.Reader.Read(p)
if n > 0 {
pt.total += int64(n)
percentage := float64(pt.total) / float64(pt.length) * float64(100)
i := int(percentage / float64(10))
is := fmt.Sprintf("%v", i)
if percentage-pt.progress > 2 {
fmt.Fprintf(os.Stderr, is)
pt.progress = percentage
}
}

return n, err
}

然后您使用 io.Reader 阅读 Response (您的 http 请求的结果):

client := &http.Client{
CheckRedirect: redirectPolicyFunc,
}
response, err := client.Get("http://example.com/something/large.zip")
defer response.Body.Close()
readerpt := &PassThru{Reader: response.Body, length: response.ContentLength}
body, err := ioutil.ReadAll(readerpt)

ReadAll() 调用触发实际下载,PassThru.Read() 将根据预期长度打印下载的百分比(response.ContentLength )


灵感:

关于arrays - 跟踪并显示下载文件摘要(百分比) - Go lang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25645363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com