Home > Backend Development > Golang > How to Monitor Upload Progress for POST Requests in Go?

How to Monitor Upload Progress for POST Requests in Go?

Susan Sarandon
Release: 2024-10-31 22:21:28
Original
1038 people have browsed it

How to Monitor Upload Progress for POST Requests in Go?

Monitoring Upload Progress for POST Requests in Go

When transmitting large files via HTTP POST requests, tracking the upload progress becomes crucial. In Go, there are several techniques to achieve this functionality.

Custom Reader with Progress Tracking

One approach is to create a custom io.Reader that encapsulates the actual reader. This customized reader can then report the progress each time the Read() method is invoked.

<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

In the main function, instantiate the ProgressReader with the file to be uploaded and a reporter function to output the progress.

<code class="go">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)
}</code>
Copy after login

This approach provides more flexibility and control over how the progress is reported. Additionally, it can be utilized for both HTTP and HTTPS sites.

The above is the detailed content of How to Monitor Upload Progress for POST Requests 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