I want to download a file from an url in go lang using the go http package and save the image to disk for later display on my webpage. How do I do this?
I need to do this because I want to download images from instagram and save them to my public folder for display on my webpage.
I created an answer below for others to use the code I came up with.
After some research I came up with this.
import (
"os"
"net/http"
"io"
)
func downloadFile(filepath string, url string) (err error) {
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Writer the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
It works well but might need a bit of refinement for use in production.