From a877b44caf62e43719238e66408c342d02003758 Mon Sep 17 00:00:00 2001 From: zengwei2000 <102871671+zengwei2000@users.noreply.github.com> Date: Sun, 25 Jun 2023 09:44:10 +0000 Subject: [PATCH] Replace the combination of os. ReadFile() and os. WriteFile() with io. Copy() Use io. Copy() instead of the combination of os. ReadFile() and os. WriteFile() to avoid reading the entire file into memory and writing it back to disk. This can reduce memory usage and improve efficiency --- utils/fileutil/filetutil.go | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/utils/fileutil/filetutil.go b/utils/fileutil/filetutil.go index f126b66..396d6ea 100644 --- a/utils/fileutil/filetutil.go +++ b/utils/fileutil/filetutil.go @@ -96,15 +96,26 @@ func CopyDirHasSuffix(src, dst, suffix string) error { // CopyFile copies the file from the source to the destination func CopyFile(src, dst string) error { - s, err := os.ReadFile(src) - if err != nil { - return err - } - err = os.WriteFile(dst, s, 0o600) - if err != nil { - return err - } - return nil + fsrc, err := os.Open(src) + if err != nil { + return err + } + defer fsrc.Close() + + fdst, err := os.Create(dst) + if err != nil { + return err + } + defer fdst.Close() + + if _, err := io.Copy(fdst, fsrc); err != nil { + return err + } + + if err := fdst.Sync(); err != nil { + return err + } + return nil } // ItemName returns the filename from the provided path