Skip to content

Instantly share code, notes, and snippets.

@maderaka
Last active July 21, 2021 23:41
Show Gist options
  • Save maderaka/e719a6ae3cb594573286 to your computer and use it in GitHub Desktop.
Save maderaka/e719a6ae3cb594573286 to your computer and use it in GitHub Desktop.
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)
}
}
@majorthorn
Copy link

fmt.Println("Just Downloaded a file %s with size %d", fileName, size) on line 45 should be fmt.Printf("Just Downloaded a file %s with size %d", fileName, size)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment