从函数获得响应而不返回 - Golang

时间:2016-10-21 16:31:10

标签: go response channel

我在Golang中有一个服务函数,运行无限循环。我想从这个函数中获取数据而不返回。什么是最佳解决方案,渠道或io.Writer?函数以及我在不同的包中调用它的地方,因为package something中的函数在我调用它的时候是主要的。通道有一个例子:

func Check(dst string, w chan string) bool {    
  for {
    w <- data
  }
  return false
}

在我称之为此功能的其他地方:

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)
}

在这种情况下,我只获得函数对通道的第一条消息。

1 个答案:

答案 0 :(得分:1)

频道是个不错的选择。要读取所有消息,只需从循环中读取通道直到它关闭:

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!")
}

playground

另一个选择是将回调传递给函数:

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)
}

playground