Download a zip file from a URL

182 views
Skip to first unread message

Gaurav

unread,
Mar 10, 2022, 12:54:30 AM3/10/22
to golang-nuts
I am trying to download a zip file using a simple http Get. This program downloads the file but the downloaded file is corrupted.

package main
import (
"fmt"
"io"
"net/http"
"os"
)

func DownloadFile(url string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()

filepath := "test.zip"

_, err = os.Stat(filepath)
if err == nil {
err := os.Remove(filepath)
if err != nil {
return err
}
}

out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()

_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}

return nil
}

func main() {
if err != nil {
fmt.Println(err)
}
}

What am I missing here? Regards
Gaurav

Tamás Gulácsi

unread,
Mar 10, 2022, 3:06:52 AM3/10/22
to golang-nuts
You miss the error returned by out.Close(). So, finish DownloadFile with "return out.Close()"
And os.Create will truncate the file, no need to Remove it - though if you want to remove, just "_ = os.Remove(filepath) "- don't check the error.
Reply all
Reply to author
Forward
0 new messages