Forked from nevermosby/goroutine-download-file.go
Created
September 28, 2018 08:24
-
-
Save dirkarnez/98b3ef1aa19a8540ede54028f90b57d8 to your computer and use it in GitHub Desktop.
Use goroutine to download multiple files
This file contains hidden or 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 ( | |
| "fmt" | |
| "io" | |
| "log" | |
| "net/http" | |
| "os" | |
| "strings" | |
| "sync" | |
| ) | |
| func main() { | |
| urls := []string{ | |
| "http://example.com/file1", | |
| "http://example.com/file2", | |
| "http://example.com/file3", | |
| } | |
| var wg sync.WaitGroup | |
| wg.Add(len(urls)) | |
| for _, url := range urls { | |
| go func(url string) { | |
| defer wg.Done() | |
| tokens := strings.Split(url, "/") | |
| fileName := tokens[len(tokens)-1] | |
| fmt.Println("Downloading", url, "to", fileName) | |
| output, err := os.Create(fileName) | |
| if err != nil { | |
| log.Fatal("Error while creating", fileName, "-", err) | |
| } | |
| defer output.Close() | |
| res, err := http.Get(url) | |
| if err != nil { | |
| log.Fatal("http get error: ", err) | |
| } else { | |
| defer res.Body.Close() | |
| _, err = io.Copy(output, res.Body) | |
| if err != nil { | |
| log.Fatal("Error while downloading", url, "-", err) | |
| } else { | |
| fmt.Println("Downloaded", fileName) | |
| } | |
| } | |
| }(url) | |
| } | |
| wg.Wait() | |
| fmt.Println("Done") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment