Last active
July 21, 2021 23:41
-
-
Save maderaka/e719a6ae3cb594573286 to your computer and use it in GitHub Desktop.
Download file using Golang. Inspired by https://www.socketloop.com/tutorials/golang-download-file-example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/url" | |
"strings" | |
"net/http" | |
"os" | |
"io" | |
"fmt" | |
) | |
var ( | |
fileName string | |
fullUrlFile string | |
) | |
func main() { | |
fullUrlFile = "https://www.google.co.id/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" | |
// Build fileName from fullPath | |
buildFileName() | |
// Create blank file | |
file := createFile() | |
// Put content on file | |
putFile(file, httpClient()) | |
} | |
func putFile(file *os.File, client *http.Client) { | |
resp, err := client.Get(fullUrlFile) | |
checkError(err) | |
defer resp.Body.Close() | |
size, err := io.Copy(file, resp.Body) | |
defer file.Close() | |
checkError(err) | |
fmt.Println("Just Downloaded a file %s with size %d", fileName, size) | |
} | |
func buildFileName() { | |
fileUrl, err := url.Parse(fullUrlFile) | |
checkError(err) | |
path := fileUrl.Path | |
segments := strings.Split(path, "/") | |
fileName = segments[len(segments)-1] | |
} | |
func httpClient() *http.Client { | |
client := http.Client{ | |
CheckRedirect:func(r *http.Request, via []*http.Request) error { | |
r.URL.Opaque = r.URL.Path | |
return nil | |
}, | |
} | |
return &client | |
} | |
func createFile() *os.File { | |
file, err := os.Create(fileName) | |
checkError(err) | |
return file | |
} | |
func checkError(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
fmt.Println("Just Downloaded a file %s with size %d", fileName, size)
on line 45 should befmt.Printf("Just Downloaded a file %s with size %d", fileName, size)