Fixes for examples/progress-download (#444)

This commit is contained in:
Matt Joiner
2022-09-27 14:42:43 +10:00
committed by GitHub
parent 900a842f50
commit d79ebda5cf
2 changed files with 16 additions and 17 deletions

View File

@@ -27,9 +27,7 @@ func (pw *progressWriter) Start() {
// TeeReader calls pw.Write() each time a new response is received // TeeReader calls pw.Write() each time a new response is received
_, err := io.Copy(pw.file, io.TeeReader(pw.reader, pw)) _, err := io.Copy(pw.file, io.TeeReader(pw.reader, pw))
if err != nil { if err != nil {
if p != nil { p.Send(progressErrMsg{err})
p.Send(progressErrMsg{err})
}
} }
} }
@@ -68,10 +66,17 @@ func main() {
} }
defer resp.Body.Close() defer resp.Body.Close()
// Don't add TUI if the header doesn't include content size
// it's impossible see progress without total
if resp.ContentLength <= 0 {
fmt.Println("can't parse content length, aborting download")
os.Exit(1)
}
filename := filepath.Base(*url) filename := filepath.Base(*url)
file, err := os.Create(filename) file, err := os.Create(filename)
if err != nil { if err != nil {
fmt.Println("could not create file: ", err) fmt.Println("could not create file:", err)
os.Exit(1) os.Exit(1)
} }
defer file.Close() defer file.Close()
@@ -81,9 +86,7 @@ func main() {
file: file, file: file,
reader: resp.Body, reader: resp.Body,
onProgress: func(ratio float64) { onProgress: func(ratio float64) {
if p != nil { p.Send(progressMsg(ratio))
p.Send(progressMsg(ratio))
}
}, },
} }
@@ -91,18 +94,14 @@ func main() {
pw: pw, pw: pw,
progress: progress.New(progress.WithDefaultGradient()), progress: progress.New(progress.WithDefaultGradient()),
} }
// Start Bubble Tea
p = tea.NewProgram(m)
// Start the download // Start the download
go pw.Start() go pw.Start()
// Don't add TUI if the header doesn't include content size if err := p.Start(); err != nil {
// it's impossible see progress without total fmt.Println("error running program:", err)
if resp.ContentLength > 0 { os.Exit(1)
// Start Bubble Tea
p = tea.NewProgram(m)
if err := p.Start(); err != nil {
fmt.Println("error running program:", err)
os.Exit(1)
}
} }
} }

View File

@@ -57,7 +57,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmds []tea.Cmd var cmds []tea.Cmd
if msg >= 1.0 { if msg >= 1.0 {
cmds = append(cmds, tea.Sequentially(finalPause(), tea.Quit)) cmds = append(cmds, tea.Sequence(finalPause(), tea.Quit))
} }
cmds = append(cmds, m.progress.SetPercent(float64(msg))) cmds = append(cmds, m.progress.SetPercent(float64(msg)))