Last active
October 21, 2019 22:33
-
-
Save netrebel/235a21271884d88eeddef2d987fbc481 to your computer and use it in GitHub Desktop.
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
package main | |
import ( | |
"fmt" | |
"net/http" | |
"sync" | |
"time" | |
) | |
type result struct { | |
URL string | |
Dur time.Duration | |
} | |
// getter executes the HTTP GET request against url, prints out the duration of the call | |
// (or an error message if it failed), and calls wg.Done() when it finishes. | |
// it's meant to be run in a goroutine. | |
func getter(url string, ch chan<- result) { | |
// defer close(ch) | |
start := time.Now() | |
if _, err := http.Get(url); err != nil { | |
ch <- result{URL: url, Dur: time.Duration(-1)} | |
return | |
} | |
ch <- result{URL: url, Dur: time.Now().Sub(start)} | |
} | |
func oldMain() { | |
urls := []string{"https://google.com", "https://yahoo.com", "https://bing.com", "https://duckduckgo.com"} | |
durCh := make(chan result) | |
var wg sync.WaitGroup | |
wg.Add(len(urls)) | |
for _, url := range urls { | |
ch := make(chan result) | |
go getter(url, ch) | |
go func() { | |
defer wg.Done() | |
t := <-ch | |
durCh <- t | |
}() | |
} | |
go func() { | |
wg.Wait() | |
close(durCh) | |
}() | |
for t := range durCh { | |
fmt.Println(t) | |
} | |
} | |
func main() { | |
urls := []string{"https://google.com", "https://yahoo.com", "https://bing.com", "https://duckduckgo.com"} | |
var wg sync.WaitGroup | |
ch := make(chan result) | |
wg.Add(len(urls)) | |
for _, url := range urls { | |
go getter(url, ch) | |
wg.Done() | |
} | |
wg.Wait() | |
for range urls { | |
out := <-ch | |
fmt.Println(out) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment