Reputation: 3113
I have a service function in Golang where running an endless for loop. I wanted to get data from this function without return. What is the best solution, a channel, or io.Writer? The function and where I call it in a different package, because the funcion in package something
while where I call it is the main. There is an example with channels:
func Check(dst string, w chan string) bool {
for {
w <- data
}
return false
}
On the otherside where I call this function:
var wg sync.WaitGroup
func main() {
messages := make(chan string, 10)
wg.Add(3)
go checking("10.1.1.1", messages)
msg := <-messages
fmt.Println(msg)
wg.Wait()
}
func checking(ip string, msg chan string) {
defer wg.Done()
w := worker.ContainerAliveIndicator{}
w.Check(ip, msg)
}
In this case I only get the first message what the function take to the channel.
Upvotes: 0
Views: 1097
Reputation: 23078
The channel is a good option. To read all messages, just read from channel in a loop until it closes:
func check(s string, ch chan<- string) {
for i := 0; i < 5; i++ {
//this could go forever, or until some condition is met
ch <- fmt.Sprintf("I did something %s %d", s, i)
time.Sleep(time.Millisecond)
}
close(ch)
}
func main() {
ch := make(chan string)
go check("FOO", ch)
for msg := range ch { //will break when ch closes
fmt.Println(msg)
}
fmt.Println("DONE!")
}
Another option is passing a callback into the function:
func check(s string, cb func(string)) {
for i := 0; i < 5; i++ {
//this could go forever, or until some condition is met
cb(fmt.Sprintf("I did something %s %d", s, i))
time.Sleep(time.Millisecond)
}
}
func main() {
msgs := []string{}
check("FOO", func(s string) { msgs = append(msgs, s) })
fmt.Println(msgs)
}
Upvotes: 1