From 34ad7bea0175041d942b3b81f74157e528d675d8 Mon Sep 17 00:00:00 2001 From: Rob Bradford Date: Tue, 22 Nov 2016 19:31:06 +0000 Subject: [PATCH] ciao-cli: For image downloads don't save the whole file into memory Use io.Copy() to stream from source to destination rather than loading entirely into memory. Fixes: #662 Signed-off-by: Rob Bradford --- ciao-cli/image.go | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/ciao-cli/image.go b/ciao-cli/image.go index 4f4487406..7beb3b1ba 100644 --- a/ciao-cli/image.go +++ b/ciao-cli/image.go @@ -20,7 +20,7 @@ import ( "errors" "flag" "fmt" - "io/ioutil" + "io" "os" "strings" "text/template" @@ -350,7 +350,7 @@ func (cmd *imageDownloadCommand) parseArgs(args []string) []string { return cmd.Flag.Args() } -func (cmd *imageDownloadCommand) run(args []string) error { +func (cmd *imageDownloadCommand) run(args []string) (err error) { client, err := imageServiceClient(*identityUser, *identityPassword, *tenantID) if err != nil { fatalf("Could not get Image service client [%s]\n", err) @@ -361,19 +361,25 @@ func (cmd *imageDownloadCommand) run(args []string) error { fatalf("Could not download image [%s]\n", err) } - b, err := ioutil.ReadAll(r) - if err != nil { - fatalf("Could not read [%s]\n", err) - } - - if cmd.file == "" { - fmt.Printf("%s\n", b) - } else { - err := ioutil.WriteFile(cmd.file, b, 0644) + dest := os.Stdout + if cmd.file != "" { + dest, err = os.Create(cmd.file) + defer func() { + closeErr := dest.Close() + if err == nil { + err = closeErr + } + }() if err != nil { - fatalf("Could not write image to file [%s]\n", err) + fatalf("Could not create destination file: %s: %v", cmd.file, err) } } + + _, err = io.Copy(dest, r) + if err != nil { + fatalf("Error copying to destination: %v", err) + } + return nil }