Skip to content

Instantly share code, notes, and snippets.

@ak9999
Created December 29, 2019 23:10
Show Gist options
  • Save ak9999/b653e1b3df982b0fa96614c03c00c2e6 to your computer and use it in GitHub Desktop.
Save ak9999/b653e1b3df982b0fa96614c03c00c2e6 to your computer and use it in GitHub Desktop.
Downloads a file and saves it to a given location.
package main
import (
"fmt"
"io"
"net/http"
"os"
)
// DownloadFile will download a url to a local file.
// Writes file as it downloads and does not load the whole file into memory.
// https://golangcode.com/download-a-file-from-a-url/
func DownloadFile(filepath string, url string) error {
// Get the data
response, err := http.Get(url)
if err != nil {
return err
}
defer response.Body.Close()
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, response.Body)
return err
}
func main() {
args := os.Args[1:]
filename := args[0]
fileURL := args[1]
fmt.Printf("Downloading to: %s\nFrom: %s", filename, fileURL)
if err := DownloadFile(filename, fileURL); err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment