Golang : Get download file size
Part of a good user experience is to let your users know in advance what are the next expected actions and the information related to the actions. For example, information such as the number of bytes or file size to be allocated in their hard disk before hitting the download button. Knowing the file size before downloading is also useful in creating gauge bar or progress bar.
For this tutorial, we will learn how to get a file name and the size from a given URL. First, by extracting the filename from the given URL and then get the download file size information from response header.
Here we go!
package main
import (
"fmt"
"net/http"
"os"
"strconv"
"strings"
)
func main() {
url := "https://d1ohg4ss876yi2.cloudfront.net/preview/golang.png"
// we are interested in getting the file or object name
// so take the last item from the slice
subStringsSlice := strings.Split(url, "/")
fileName := subStringsSlice[len(subStringsSlice)-1]
resp, err := http.Head(url)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Is our request ok?
if resp.StatusCode != http.StatusOK {
fmt.Println(resp.Status)
os.Exit(1)
// exit if not ok
}
// the Header "Content-Length" will let us know
// the total file size to download
size, _ := strconv.Atoi(resp.Header.Get("Content-Length"))
downloadSize := int64(size)
fmt.Println("Will be downloading ", fileName, " of ", downloadSize, " bytes.")
}
Sample output :
Will be downloading golang.png of 113857 bytes.
See also : Golang : Download file 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
+13k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+9.9k Golang : Edge detection with Sobel method
+9.6k Golang : Qt get screen resolution and display on center example
+27.3k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+17.5k Golang : Read data from config file and assign to variables
+11.9k Golang : Detect user location with HTML5 geo-location
+12.9k Golang : Calculate elapsed years or months since a date
+16.2k Golang : Check if a string contains multiple sub-strings in []string?
+10.7k Golang : Get UDP client IP address and differentiate clients by port number
+7.3k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+6.4k Elasticsearch : Shutdown a local node
+5.6k Unix/Linux : How to test user agents blocked successfully ?