Handle n != 0 && err != nil

This commit is contained in:
blank X 2022-02-08 17:27:23 +07:00
parent 3be014a4a8
commit 586186a355
Signed by: blankie
GPG Key ID: CC15FC822C7F61F5
2 changed files with 25 additions and 21 deletions

32
main.go
View File

@ -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()
}

View File

@ -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)
}