您可以创建自己io.Reader的包装实际读者,然后每次Read调用时都可以输出进度.
有点像:
type ProgressReader struct {
io.Reader
Reporter func(r int64)
}
func (pr *ProgressReader) Read(p []byte) (n int, err error) {
n, err = pr.Reader.Read(p)
pr.Reporter(int64(n))
return
}
func main() {
file, _ := os.Open("/tmp/blah.go")
total := int64(0)
pr := &ProgressReader{file, func(r int64) {
total += r
if r > 0 {
fmt.Println("progress", r)
} else {
fmt.Println("done", r)
}
}}
io.Copy(ioutil.Discard, pr)
}
Run Code Online (Sandbox Code Playgroud)
将作为请求正文传递的阅读器包装在报告进度的内容中。例如,
type progressReporter struct {
r io.Reader
max int
sent int
}
func (pr *progressReader) Read(p []byte) (int, error) {
n, err := pr.r.Read(p)
pr.sent += n
if err == io.EOF {
pr.atEOF = true
}
pr.report()
return n, err
}
func (pr *progressReporter) report() {
fmt.Printf("sent %d of %d bytes\n", pr.sent, pr.max)
if pr.atEOF {
fmt.Println("DONE")
}
}
Run Code Online (Sandbox Code Playgroud)
如果之前你打电话
client.Post(u, contentType, r)
Run Code Online (Sandbox Code Playgroud)
然后将代码更改为
client.Post(u, contentType, &progressReader{r:r, max:max})
Run Code Online (Sandbox Code Playgroud)
max您希望发送的字节数在哪里。修改 progressReporter.report() 方法并向 progressReporter 添加字段以满足您的特定需求。
| 归档时间: |
|
| 查看次数: |
1558 次 |
| 最近记录: |