Home  >  Article  >  Backend Development  >  How to Track POST Request Progress for Large Files in Go?

How to Track POST Request Progress for Large Files in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 14:57:30986browse

How to Track POST Request Progress for Large Files in Go?

Tracking POST Request Progress 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn