main.go
This file
Path
examples/progress-download/main.go
107 lines · 2.1 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23import (4 "flag"5 "fmt"6 "io"7 "log"8 "net/http"9 "os"10 "path/filepath"1112 "charm.land/bubbles/v2/progress"13 tea "charm.land/bubbletea/v2"14)1516var p *tea.Program1718type progressWriter struct {19 total int20 downloaded int21 file *os.File22 reader io.Reader23 onProgress func(float64)24}2526func (pw *progressWriter) Start() {27 // TeeReader calls pw.Write() each time a new response is received28 _, err := io.Copy(pw.file, io.TeeReader(pw.reader, pw))29 if err != nil {30 p.Send(progressErrMsg{err})31 }32}3334func (pw *progressWriter) Write(p []byte) (int, error) {35 pw.downloaded += len(p)36 if pw.total > 0 && pw.onProgress != nil {37 pw.onProgress(float64(pw.downloaded) / float64(pw.total))38 }39 return len(p), nil40}4142func getResponse(url string) (*http.Response, error) {43 resp, err := http.Get(url) // nolint:gosec44 if err != nil {45 log.Fatal(err)46 }47 if resp.StatusCode != http.StatusOK {48 return nil, fmt.Errorf("receiving status of %d for url: %s", resp.StatusCode, url)49 }50 return resp, nil51}5253func main() {54 url := flag.String("url", "", "url for the file to download")55 flag.Parse()5657 if *url == "" {58 flag.Usage()59 os.Exit(1)60 }6162 resp, err := getResponse(*url)63 if err != nil {64 fmt.Println("could not get response", err)65 os.Exit(1)66 }67 defer resp.Body.Close() // nolint:errcheck6869 // Don't add TUI if the header doesn't include content size70 // it's impossible see progress without total71 if resp.ContentLength <= 0 {72 fmt.Println("can't parse content length, aborting download")73 os.Exit(1)74 }7576 filename := filepath.Base(*url)77 file, err := os.Create(filename)78 if err != nil {79 fmt.Println("could not create file:", err)80 os.Exit(1)81 }82 defer file.Close() // nolint:errcheck8384 pw := &progressWriter{85 total: int(resp.ContentLength),86 file: file,87 reader: resp.Body,88 onProgress: func(ratio float64) {89 p.Send(progressMsg(ratio))90 },91 }9293 m := model{94 pw: pw,95 progress: progress.New(progress.WithDefaultBlend()),96 }97 // Start Bubble Tea98 p = tea.NewProgram(m)99100 // Start the download101 go pw.Start()102103 if _, err := p.Run(); err != nil {104 fmt.Println("error running program:", err)105 os.Exit(1)106 }107}