Go: Tracking POST request progress

前端 未结 2 427
时光说笑
时光说笑 2020-12-10 09:27

I\'m coding a ShareX clone for Linux in Go that uploads files and images to file sharing services through http POST requests.

I\'m currently using http.Client and Do

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 09:49

    You can create your own io.Reader to wrap the actual reader and then you can output the progress each time Read is called.

    Something along the lines of:

    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)
    }
    

提交回复
热议问题