Hi,
if `ws.Read` returns after a reasonable timeout, you can perform a
non-blocking receive on the quit channel to see if it has been
closed/something has been sent to it:
select {
case <-quit:
break
default:
// Nothing to do here
}
out, err := ws.Read()
/* more stuff in the loop */
Another approach would be to use a websocket library that supports
passing a context to the Read method (not sure if any of those exists).
For my usual go-to websocket library (github.com/gorilla/websocket), I
usually set a read deadline on the connection in cases like this and
more or less do the nonblocking read as above.
On 13.01.21 12:10, Sankar wrote:
I have a function that must be executed as a go routine infinitely until
a message comes in a channel. For example:
func readWebSocket(ws *websocket.socket, quit chan bool) {
for {
out, err = ws.Read()
log.Println(out, err)
}
}
Now I call this above function as a goroutine from main such as:
go readWebSocket(ws, quit)
where I want the for loop to go on until the `quit` channel receives a
message. The "select" loop seem to work only on multiple channels and
not on a channel + some looping code.
One alternative that I could think of was to create a second goroutine
(third if you include main) to which this readWebSocket can send the
output of "ws.Read" and the select loop can be run there with two
channels (the quit channel and the new channel which gets the "ws.Read"
output) but that would leak this reader go-routine infinitely or makes
the code more complex.
How to handle this situation gracefully in go channels, where I want a
go routine to run until a channel gets a message ?
Thanks.
--
You received this message because you are subscribed to the Google
Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send
an email to golang-nuts+unsubscr...@googlegroups.com
<mailto:golang-nuts+unsubscr...@googlegroups.com>.
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/32f04de0-4684-40eb-9b1b-8a9a7ff80602n%40googlegroups.com
<https://groups.google.com/d/msgid/golang-nuts/32f04de0-4684-40eb-9b1b-8a9a7ff80602n%40googlegroups.com?utm_medium=email&utm_source=footer>.
--
Gregor Best
b...@pferdewetten.de
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/0285534a-fa6e-4c1b-2cee-743fd7e442f7%40pferdewetten.de.