Skip to content

Instantly share code, notes, and snippets.

@marcosinger
Last active July 2, 2019 17:17
Show Gist options
  • Save marcosinger/a1a39c41ee9246d08f28486607b0e5c9 to your computer and use it in GitHub Desktop.
Save marcosinger/a1a39c41ee9246d08f28486607b0e5c9 to your computer and use it in GitHub Desktop.
Channel example
package main
import (
"fmt"
"sync"
"log"
"net/http"
)
type Response struct {
Status int
}
func main() {
content := make(chan Response)
urls := []string{
"https://google.com",
"https://tutorialedge.net",
"https://twitter.com",
}
var wg sync.WaitGroup
wg.Add(1)
go fetchWorker(&wg, urls, content)
wg.Add(1)
go printResponse(&wg, content)
wg.Wait()
fmt.Println("done!")
}
func fetchWorker(mainWG *sync.WaitGroup, urls []string, output chan<- Response) {
defer mainWG.Done()
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go fetch(&wg, url, output)
}
wg.Wait()
close(output)
}
func fetch(wg *sync.WaitGroup, url string, output chan<- Response) {
defer wg.Done()
resp, err := http.Get(url)
if err != nil {
fmt.Println(err)
}
output <- Response{
Status: resp.StatusCode,
}
}
func printResponse(wg *sync.WaitGroup, input <-chan Response) {
defer wg.Done()
for content := range input {
log.Printf("content %#v", content)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment