From 586186a35568a1e306c249bf64b5db7b35b781f3 Mon Sep 17 00:00:00 2001 From: blank X Date: Tue, 8 Feb 2022 17:27:23 +0700 Subject: [PATCH] Handle n != 0 && err != nil --- main.go | 32 +++++++++++--------------------- utils.go | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/main.go b/main.go index ee2d8cb..87cfa90 100644 --- a/main.go +++ b/main.go @@ -241,38 +241,28 @@ func main() { writer := bufio.NewWriter(file) defer writer.Flush() reader := bufio.NewReader(response.Body) - contentLengthString := "" - if response.ContentLength >= 0 { - contentLengthString = FormatBytes(float64(response.ContentLength)) - } lastOutputLength := 0 bytesDownloaded := 0 toWrite := make([]byte, 1024*1024) for { - output := fmt.Sprintf("%s downloaded", FormatBytes(float64(bytesDownloaded))) - if response.ContentLength >= 0 { - output = fmt.Sprintf("%s out of %s downloaded (%.2f%%)", FormatBytes(float64(bytesDownloaded)), contentLengthString, float64(bytesDownloaded)/float64(response.ContentLength)*100.0) - } - fmt.Print(output) - for i := 0; i < lastOutputLength-len(output); i++ { - fmt.Print(" ") - } - lastOutputLength = len(output) - fmt.Print("\r") + lastOutputLength = PrintStatus(float64(bytesDownloaded), float64(response.ContentLength), lastOutputLength) n, err := reader.Read(toWrite) - if n == 0 && errors.Is(err, io.EOF) { + if n > 0 { + _, writeErr := writer.Write(toWrite[:n]) + if writeErr != nil { + fmt.Fprintf(os.Stderr, "Failed to write response: %s\n", writeErr) + os.Exit(1) + } + bytesDownloaded += n + lastOutputLength = PrintStatus(float64(bytesDownloaded), float64(response.ContentLength), lastOutputLength) + } + if errors.Is(err, io.EOF) { break } if err != nil { fmt.Fprintf(os.Stderr, "Failed to read response: %s\n", err) os.Exit(1) } - _, err = writer.Write(toWrite[:n]) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to write response: %s\n", err) - os.Exit(1) - } - bytesDownloaded += n } fmt.Println() } diff --git a/utils.go b/utils.go index b94fc80..4ebdba3 100644 --- a/utils.go +++ b/utils.go @@ -295,3 +295,17 @@ func GetExtension(mimeType string) (string, error) { fmt.Println(exts) return exts[0], nil } + +func PrintStatus(bytesDownloaded, contentLength float64, lastOutputLength int) int { + output := fmt.Sprintf("%s downloaded", FormatBytes(bytesDownloaded)) + if contentLength >= 0 { + contentLengthString := FormatBytes(contentLength) + output = fmt.Sprintf("%s out of %s downloaded (%.2f%%)", FormatBytes(bytesDownloaded), contentLengthString, bytesDownloaded/contentLength*100.0) + } + fmt.Print(output) + for i := 0; i < lastOutputLength-len(output); i++ { + fmt.Print(" ") + } + fmt.Print("\r") + return len(output) +}