问题描述
我目前正在开发一个桌面应用程序,该应用程序使用Electron并通过websocket与Go二进制文件进行大部分后端计算的通信。
例如,我有
import (
"fmt"
socketio "github.com/googollee/go-socket.io"
)
func foo() bool {
fmt.Println("Hello World!")
return true
}
我将使用go-socket
模块代表我的websocket服务器
server.OnEvent("/","test",func(s socketio.Conn,value string) bool {
return foo()
}
我的应用程序非常大且很深,因此为了简单起见,我已将一般概念降至最低。我希望将foo()
作为goroutine运行,并将给定的值返回到我的套接字服务器。
做到这一点的最佳方法是什么?
编辑
现在,我已经考虑了更多,我相信最好不要返回foo()
的值,而应将其作为goroutine启动,而是将响应发送到前端的单独接收器,结束。
解决方法
您可以这样做,但可能不是一个好方法:
server.OnEvent("/","test",func(s socketio.Conn,value string) bool {
c := make(chan bool)
var x bool
go func() {
x = foo()
c <- true
}()
<-c
return x
}
我已经使用通道首先执行goroutine。成功执行goroutine之后,将执行主例程。