func check(name string) string {
resp, err := http.Get(endpoint + name)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return string(body)
}
func worker(name string, wg *sync.WaitGroup, names chan string) {
defer wg.Done()
var a = check(name)
names <- a
}
func main() {
names := make(chan string)
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker("www"+strconv.Itoa(i), &wg, names)
}
fmt.Println(<-names)
}
The expected result would be 5 results but, only one executes and the process ends. Is there something I am missing? New to go. The endpoint is a generic API that returns json
You are launching 5 goroutines, but are reading from the names
channel only once.
fmt.Println(<-names)
As soon as that first channel read is done, main()
exits.
That means everything stops before having the time to be executed.
To know more about channels, see "Concurrency made easy" from Dave Cheney:
- If you have to wait for the result of an operation, it’s easier to do it yourself.
- Release locks and semaphores in the reverse order you acquired them.
- Channels aren’t resources like files or sockets, you don’t need to close them to free them.
- Acquire semaphores when you’re ready to use them.
- Avoid mixing anonymous functions and goroutines
- Before you start a goroutine, always know when, and how, it will stop