Golang : Download file example
Continuing from previous tutorial on how to use http.Get()
function, in this tutorial, we will learn how to download/get file from another server via the http.Get()
function and save the content into a file.
This program will
figure out the filename to be created based on the given URL
check if there is redirection and handle it
report the Get status
save the content to a file
print out the bytes downloaded.
downloadfile.go
package main
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
)
func main() {
fmt.Println("Downloading file...")
rawURL := "https://d1ohg4ss876yi2.cloudfront.net/golang-resize-image/big.jpg"
fileURL, err := url.Parse(rawURL)
if err != nil {
panic(err)
}
path := fileURL.Path
segments := strings.Split(path, "/")
fileName := segments[2] // change the number to accommodate changes to the url.Path position
file, err := os.Create(fileName)
if err != nil {
fmt.Println(err)
panic(err)
}
defer file.Close()
check := http.Client{
CheckRedirect: func(r *http.Request, via []*http.Request) error {
r.URL.Opaque = r.URL.Path
return nil
},
}
resp, err := check.Get(rawURL) // add a filter to check redirect
if err != nil {
fmt.Println(err)
panic(err)
}
defer resp.Body.Close()
fmt.Println(resp.Status)
size, err := io.Copy(file, resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("%s with %v bytes downloaded", fileName, size)
}
Output :
Downloading file...
200 OK
big.jpg with 150042 bytes downloaded
References :
See also : Golang : http.Get example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.3k Golang : How to stop user from directly running an executable file?
+25k Golang : Convert long hexadecimal with strconv.ParseUint example
+17.8k Golang : Convert IPv4 address to decimal number(base 10) or integer
+12k Golang : List running EC2 instances and descriptions
+15.4k Golang : Get current time from the Internet time server(ntp) example
+8k Golang : Auto-generate reply email with text/template package
+9.6k Golang : Get current, epoch time and display by year, month and day
+13.8k Golang : Reverse IP address for reverse DNS lookup example
+7k Golang : Dealing with postal or zip code example
+18.6k Golang : Padding data for encryption and un-padding data for decryption
+22.5k Golang : untar or extract tar ball archive example
+6.9k Golang : Use modern ciphers only in secure connection