How do I download a file with a http request in go language
10,642
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.
Author by
Pablo Jomer
I'm a software engineer currently stationed in Linköping, Sweden where I work at a small startup constructing automatic software for 3D-reconstruction of buildings. I enjoy programming, board games, math, hiking, art and hanging out with my girlfriend (soon to be wife).
Updated on June 05, 2022Comments
-
Pablo Jomer almost 2 years
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.