Last active
December 3, 2018 14:24
-
-
Save lotusirous/18ca518acb706ab419e0b3b78e81f202 to your computer and use it in GitHub Desktop.
fetch a list of urls in parallel by go
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/ioutil" | |
| "log" | |
| "net/http" | |
| "sync" | |
| ) | |
| func check(err error) { | |
| if err != nil { | |
| log.Fatal(err) | |
| return | |
| } | |
| } | |
| func fetchUrls(urls []string) <-chan string { | |
| out := make(chan string) | |
| var wg sync.WaitGroup | |
| wg.Add(len(urls)) | |
| for _, url := range urls { | |
| // Increment the WaitGroup counter. | |
| // Launch a goroutine to fetch the URL. | |
| go func(url string) { | |
| // Decrement the counter when the goroutine completes. | |
| defer wg.Done() | |
| // Fetch the URL. | |
| resp, err := http.Get(url) | |
| check(err) | |
| defer resp.Body.Close() | |
| body, err := ioutil.ReadAll(resp.Body) | |
| check(err) | |
| out <- string(body) | |
| }(url) | |
| } | |
| // Wait for all HTTP fetches to complete. | |
| go func() { | |
| wg.Wait() | |
| defer close(out) | |
| }() | |
| return out | |
| } | |
| func main() { | |
| urls := []string{"https://httpbin.org/uuid", "https://httpbin.org/uuid"} | |
| body := fetchUrls(urls) | |
| for v := range body { | |
| fmt.Println(v) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment