I'm working on a simple waiter implementation, waiter - is a code that polls an external API until a desired response is received within a given period of time. I would like to keep it simple, but at the same time write it in the native Golang style. At the moment I come up with the following code (the actual API request is removed for brevity). I'm not entirely sure if the combination of a ticker and time.After is the right approach to achieve this, while it seems to be working as expected. I feel like there should be a common pattern for doing this.
package main
import (
"fmt"
"time"
)
func main() {
ticker := time.NewTicker(1 * time.Second)
tickerDone := make(chan bool, 1)
timeoutDone := make(chan bool, 1)
go func() {
defer ticker.Stop()
i := 1
for {
select {
case <-tickerDone:
fmt.Println("Stopping the ticker")
timeoutDone <- true
return
case t := <-ticker.C:
fmt.Println("Tick at", t)
if i == 3 {
fmt.Println("It's a 3rd tick, enought")
ticker.Stop()
tickerDone <- true
}
i += 1
}
}
}()
select {
case <-timeoutDone:
fmt.Println("Completed before the timeout")
case <-time.After(5 * time.Second):
fmt.Println("Timed out")
ticker.Stop()
tickerDone <- true
}
}
```