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!