下载文件时如何打印字节?-golang
时间:2023-04-11
浏览:382
作者:佚名
对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《下载文件时如何打印字节?-golang》,主要介绍了golang,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
问题内容
我想知道是否可以在下载文件时计算和打印下载的字节数。
out, err := os.Create("file.txt")
defer out.Close()
if err != nil {
fmt.Println(fmt.Sprint(err) )
panic(err)
}
resp, err := http.Get("http://example.com/zip")
defer resp.Body.Close()
if err != nil {
fmt.Println(fmt.Sprint(err) )
panic(err)
}
n, er := io.Copy(out, resp.Body)
if er != nil {
fmt.Println(fmt.Sprint(err) )
}
fmt.Println(n, "bytes ")
正确答案
如果我理解正确,您希望在数据传输时显示读取的字节数。大概是为了维护某种进度条什么的。在这种情况下,您可以使用 Go
的组合数据结构将读取器或写入器包装在自定义io.Reader或io.Writer实现中。
它只是将相应的Read或Write调用转发到底层流,同时对(int, error)它们返回的值进行一些额外的工作。这是一个可以在Go
操场上运行的示例。
package main
import (
"bytes"
"fmt"
"io"
"os"
"strings"
)
// 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
}
// 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)
pt.total += int64(n)
if err == nil {
fmt.Println("Read", n, "bytes for a total of", pt.total)
}
return n, err
}
func main() {
var src io.Reader // Source file/url/etc
var dst bytes.Buffer // Destination file/buffer/etc
// Create some random input data.
src = bytes.NewBufferString(strings.Repeat("Some random input data", 1000))
// Wrap it with our custom io.Reader.
src = &PassThru{Reader: src}
count, err := io.Copy(&dst, src)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Transferred", count, "bytes")
}
它生成的输出是这样的:
Read 512 bytes for a total of 512 Read 1024 bytes for a total of 1536 Read 2048 bytes for a total of 3584 Read 4096 bytes for a total of 7680 Read 8192 bytes for a total of 15872 Read 6128 bytes for a total of 22000 Transferred 22000 bytes
今天带大家了解了golang的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
