mirror of
https://github.com/wgh136/nysoure.git
synced 2025-09-27 04:17:23 +00:00
refactor downloadFile to use buffered writer for improved performance
This commit is contained in:
@@ -1,6 +1,7 @@
|
|||||||
package service
|
package service
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"context"
|
"context"
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
@@ -521,6 +522,7 @@ func downloadFile(ctx context.Context, url string, path string) error {
|
|||||||
return model.NewInternalServerError("failed to open file for writing")
|
return model.NewInternalServerError("failed to open file for writing")
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
writer := bufio.NewWriter(file)
|
||||||
|
|
||||||
buf := make([]byte, 64*1024)
|
buf := make([]byte, 64*1024)
|
||||||
for {
|
for {
|
||||||
@@ -530,12 +532,15 @@ func downloadFile(ctx context.Context, url string, path string) error {
|
|||||||
default:
|
default:
|
||||||
n, readErr := resp.Body.Read(buf)
|
n, readErr := resp.Body.Read(buf)
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
if _, writeErr := file.Write(buf[:n]); writeErr != nil {
|
if _, writeErr := writer.Write(buf[:n]); writeErr != nil {
|
||||||
return model.NewInternalServerError("failed to write to file")
|
return model.NewInternalServerError("failed to write to file")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if readErr != nil {
|
if readErr != nil {
|
||||||
if readErr == io.EOF {
|
if readErr == io.EOF {
|
||||||
|
if err := writer.Flush(); err != nil {
|
||||||
|
return model.NewInternalServerError("failed to flush writer")
|
||||||
|
}
|
||||||
return nil // Download completed successfully
|
return nil // Download completed successfully
|
||||||
}
|
}
|
||||||
if ctx.Err() != nil {
|
if ctx.Err() != nil {
|
||||||
|
Reference in New Issue
Block a user