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

Mary-Kate Olsen
Release: 2024-10-28 14:57:30
Original
995 people have browsed it

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>
Copy after login

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>
Copy after login

Subsequently, the progress can be tracked by copying the content to a discarding location:

<code class="go">io.Copy(ioutil.Discard, pr)</code>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!