refactor downloadFile to use buffered writer for improved performance

This commit is contained in:
2025-09-03 09:13:57 +08:00
parent a3fc1cd801
commit 4e709dd952

View File

@@ -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 {