Last active
January 19, 2021 21:48
-
-
Save rogerwelin/8edc88baa73985a02a2e2a989db180f8 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" | |
) | |
type HttpResult struct { | |
Url string | |
StatusCode int | |
} | |
// 3 | |
func producer(ch chan<- HttpResult, url string, wg *sync.WaitGroup) { | |
defer wg.Done() | |
resp, err := http.Get(url) | |
if err != nil { | |
fmt.Errorf("url was error: %v", err) | |
} | |
ch <- HttpResult{Url: url, StatusCode: resp.StatusCode} | |
} | |
// 4 | |
func consumer(ch <-chan HttpResult, done chan<- bool) { | |
for msg := range ch { | |
fmt.Printf("%s -> %d\n", msg.Url, msg.StatusCode) | |
} | |
done <- true | |
} | |
func main() { | |
urlChan := make(chan HttpResult) | |
// 1 | |
doneChan := make(chan bool) | |
wg := sync.WaitGroup{} | |
urls := []string{"https://rogerwelin.github.io/", | |
"https://golang.org/", | |
"https://news.ycombinator.com/", | |
"https://www.google.se/shouldbe404", | |
"https://www.cpan.org/"} | |
// 2 | |
for _, url := range urls { | |
wg.Add(1) | |
go producer(urlChan, url, &wg) | |
} | |
go consumer(urlChan, doneChan) | |
// 5 | |
wg.Wait() | |
close(urlChan) | |
<-doneChan | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment