I'm working on a chat server and am using redigo in order to publish messages across many web socket connections. I have a go routine that (per user connection) opens a connection to redis, subscribes to some channels and waits for a message. Waiting for this message -
msg := psc.Receive()
is a blocking operation in the fact that any code after the receive function will not run until a message comes in. However I would like to be able to watch for context -
ctx.Done()
or the like. Is this achievable using a select, or is there a more idiomatic way of writing this? I am attempting to do this as in the current implementation this function is run as a go routine, and if the web session ends I would like to end the redis connection and finish the go routine.
func relayRedisMessages (ctx context.Context, ws *websocket.Conn, rc []string) {
c, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
log.Println(err)
return
}
defer c.Close()
psc := redis.PubSubConn{c}
for _, channel := range rc {
psc.Subscribe(channel)
}
for {
msg := psc.Receive()
// Write message to websocket
var msg Message
json.Unmarshal(v.Data, &msg)
err = ws.WriteJSON(msg)
if err != nil {
log.Println(err)
break
}
}
}