I am writing just a simple Go pipeline, the goal is to fetch the urls and print status.
On fetchUrl, I need to close out channel to notify main, there will be no data comming so release the main go routine. However i can't really close channel on fetchurl function after loop because it will be too soon. I don't want to add wait groups the application because whole goal is for me at the moment understand channels.
On fetchurl function, channel called two is for just making sure there will be only 2 jobs at once.
package main
import (
"fmt"
"net/http"
"os"
)
func gen(val []string) <-chan string {
out := make(chan string, len(val))
for _, val := range val {
out <- val
}
close(out)
return out
}
func fetchUrl(in <-chan string) <-chan string {
out := make(chan string)
two := make(chan struct{}, 2)
fmt.Println("blocked")
for url := range in {
two <- struct{}{}
go fetchWorker(url, two, out)
}
return out
}
func fetchWorker(url string, two chan struct{}, out chan string) {
res, err := http.Get("https://" + url)
if err != nil {
panic(err)
}
<-two
out <- fmt.Sprintf("[%d] %s\n", res.StatusCode, url)
}
func main() {
for val := range fetchUrl(gen(os.Args[1:])) {
fmt.Println(val)
}
}