Skip to content

Commit

Permalink
Add ProgressReader and use it in UploadFile
Browse files Browse the repository at this point in the history
  • Loading branch information
moshe-kabala committed Nov 26, 2024
1 parent 5e86373 commit 7549ce4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pkg/api/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,14 @@ func UploadFile(url string, file io.Reader, fileSize int64) error {
s.Start()
defer s.Stop()

req, err := http.NewRequest(http.MethodPut, url, file)
progressReader := log.NewProgressReader(
file,
fileSize,
s.UpdateProgress,
)

req, err := http.NewRequest(http.MethodPut, url, progressReader)

if err != nil {
return err
}
Expand Down
28 changes: 28 additions & 0 deletions pkg/log/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ package log

import (
"fmt"
"io"
"os"
"sync/atomic"
"time"

"github.com/briandowns/spinner"
Expand All @@ -25,6 +27,32 @@ func ConnectFileToVerboseLogOutput(filePath string) (close func(), err error) {
return
}

type ProgressReader struct {
reader io.Reader
totalSize int64
bytesRead int64
updateFunc func(percent int)
}

func NewProgressReader(reader io.Reader, totalSize int64, updateFunc func(percent int)) *ProgressReader {
return &ProgressReader{
reader: reader,
totalSize: totalSize,
updateFunc: updateFunc,
}
}

// Read reads from the underlying reader and updates the progress.
func (pr *ProgressReader) Read(p []byte) (int, error) {
n, err := pr.reader.Read(p)
if n > 0 {
atomic.AddInt64(&pr.bytesRead, int64(n))
percent := int(float64(pr.bytesRead) / float64(pr.totalSize) * 100)
pr.updateFunc(percent)
}
return n, err
}

// Spinner is a custom type that wraps a spinner with additional functionality.
type Spinner struct {
s *spinner.Spinner
Expand Down

0 comments on commit 7549ce4

Please sign in to comment.