This post shows how you can download a file in Go from a URL. We use the std lib (standard library) http.Get() [docs] and io.Copy() [docs] functions to help us with this. This function should be efficient as it will stream the data into the file, as opposed to downloading it all into memory, then to file.
The file will be saved in the same directory as your program.
We also show an alternative below if you want to take the filename from the URL.
packagemainimport("fmt""io""net/http""os")funcmain(){fileUrl:="https://gophercoding.com/img/logo-original.png"// Download the file, params:
// 1) name of file to save as
// 2) URL to download FROM
err:=DownloadFile("saveas.png",fileUrl)iferr!=nil{fmt.Println("Error downloading file: ",err)return}fmt.Println("Downloaded: "+fileUrl)}// DownloadFile will download from a given url to a file. It will
// write as it downloads (useful for large files).
funcDownloadFile(filepathstring,urlstring)error{// Get the data
resp,err:=http.Get(url)iferr!=nil{returnerr}deferresp.Body.Close()// Create the file
out,err:=os.Create(filepath)iferr!=nil{returnerr}deferout.Close()// Write the body to file
_,err=io.Copy(out,resp.Body)returnerr}
Alternative Filename
In our example above, you needed to provide it with a file name to save as - but we can replace this, if we want, to use the original filename in the url. We’ve added a line to work out the filename from the url: path.Base(resp.Request.URL.String()).
funcDownloadFile(urlstring)error{// Get the data
resp,err:=http.Get(url)iferr!=nil{returnerr}deferresp.Body.Close()// Create the file
filepath:=path.Base(resp.Request.URL.String())out,err:=os.Create(filepath)iferr!=nil{returnerr}deferout.Close()// Write the body to file
_,err=io.Copy(out,resp.Body)returnerr}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.