Home >Backend Development >Golang >How to Track POST Request Progress for Large Files in Go?
Problem:
Developers aiming to build file-sharing applications in Go using POST requests face challenges in monitoring upload progress for large files that require extended upload times.
Solution:
Wrapped io.Reader with Progress Tracking:
Instead of leveraging an intermediary TCP connection, an alternative approach is to create a custom io.Reader wrapper around the actual file reader. This allows for progress tracking each time the Read function is invoked.
Code Implementation:
Here's an example implementation:
<code class="go">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 }</code>
To utilize this wrapper, wrap the actual file reader within the ProgressReader:
<code class="go">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) } }}</code>
Subsequently, the progress can be tracked by copying the content to a discarding location:
<code class="go">io.Copy(ioutil.Discard, pr)</code>
This method enables seamless monitoring of upload progress for large files using POST requests.
The above is the detailed content of How to Track POST Request Progress for Large Files in Go?. For more information, please follow other related articles on the PHP Chinese website!