Last active
June 21, 2021 20:35
-
-
Save remylavergne/98c7fcab85dc3d617e4ca8f0868206bd to your computer and use it in GitHub Desktop.
[Go] [Golang] How to download file
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
func downloadFile(fullUrl string) { | |
// Extract filename from path | |
fileURL, err := url.Parse(fullUrl) | |
if err != nil { | |
check(err) | |
} | |
path := fileURL.Path | |
segments := strings.Split(path, "/") | |
fileName := segments[len(segments)-1] | |
fmt.Println("Start downloading:", fileName) | |
// Create blank file | |
file, err := os.Create(fileName) | |
if err != nil { | |
check(err) | |
} | |
// Create HTTP client | |
client := http.Client{ | |
CheckRedirect: func(r *http.Request, via []*http.Request) error { | |
r.URL.Opaque = r.URL.Path | |
return nil | |
}, | |
} | |
// Put content on file | |
resp, err := client.Get(fullUrl) | |
if err != nil { | |
check(err) | |
} | |
defer resp.Body.Close() | |
size, err := io.Copy(file, resp.Body) | |
defer file.Close() | |
fmt.Printf("Downloaded a file %s with size %d\n", fileName, size) | |
wg.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment