Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Tracking POST request progress

Tags:

http

post

go

upload

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() to send my requests, but I'd like to be able to track the upload progress for bigger files that take up to a minute to upload. The only way I can think of at the moment is manually opening a TCP connection on port 80 to the website and write the HTTP request in chunks, but I don't know if it would work on https sites and I'm not sure if it's the best way to do it.

Is there any other way to achieve this?

like image 553
Francesco Noferi Avatar asked Sep 26 '14 00:09

Francesco Noferi


1 Answers

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)
}
like image 138
OneOfOne Avatar answered Nov 10 '22 10:11

OneOfOne