Tracking io.Copy Progress in Go
If you are writing Go code for any period, you must have used the io.Copy
function. It takes an io.Writer
and an io.Reader
and copies everything from the reader to the writer until it reaches the end of file (EOF).
The function returns the number of bytes copied and an error (if any, other than io.EOF
).
But this function blocks until the copy completes. How do you track the progress of io.Copy
?
You can write a custom io.Writer
wrapper:
|
|
The ProgressWriter
wraps any io.Writer
and proxies all Write
calls to it. As it proxies the call, it tracks the number of bytes written to the io.Writer
.
The method N
can be called on the ProgressWriter
to read the total number of bytes written to the io.Writer
. It is safe to call N
from different or multiple goroutines since the ProgressWriter
stores and reads the total number of bytes from an atomic.Int64
.
|
|
The second goroutine will print the total number of bytes copied to the io.Writer
every second.
This post is 89th of my #100DaysToOffload challenge. Want to get involved? Find out more at 100daystooffload.com.
comments powered by Disqus