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

How to Monitor Upload Progress for POST Requests in Go?

Susan Sarandon
Susan SarandonOriginal
2024-10-31 22:21:28939browse

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>

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>

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!

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