Created
May 2, 2020 00:47
-
-
Save rogerwelin/dbd917bc9485386d82691429069acef9 to your computer and use it in GitHub Desktop.
channels
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 | |
} | |
// 4 | |
func makeRequest(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} | |
} | |
// 5 | |
func collect(ch <-chan HttpResult) { | |
for msg := range ch { | |
fmt.Printf("%s -> %d\n", msg.Url, msg.StatusCode) | |
} | |
} | |
func main() { | |
// 1 | |
urlChan := make(chan HttpResult) | |
var 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 | |
go collect(urlChan) | |
// 3 | |
for _, url := range urls { | |
wg.Add(1) | |
go makeRequest(urlChan, url, &wg) | |
} | |
// 6 | |
wg.Wait() | |
close(urlChan) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment