Skip to content

Instantly share code, notes, and snippets.

@nevermosby
Created August 22, 2016 09:14
Show Gist options
  • Select an option

  • Save nevermosby/b54d473ea9153bb75eebd14d8d816544 to your computer and use it in GitHub Desktop.

Select an option

Save nevermosby/b54d473ea9153bb75eebd14d8d816544 to your computer and use it in GitHub Desktop.
Use goroutine to download multiple files
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