receive a message from a channel with a timeout in go

To receive a message from a channel with a timeout in Go, you can use the select statement with a time.After channel. Here's an example code snippet:

main.go
msgCh := make(chan string)

// Wait for a message with a timeout of 1 second
select {
case msg := <-msgCh:
    fmt.Println("Received message:", msg)
case <-time.After(time.Second):
    fmt.Println("Timeout: no message received")
}
231 chars
10 lines

In this code, we first create a channel msgCh for receiving messages. Then, we use the select statement to wait for either a message from msgCh or a signal from the time.After channel, whichever comes first.

The time.After function creates a channel that will send a single message after the given duration. In this case, we use it to create a channel that will send a message after 1 second.

If a message is received from msgCh before the timeout, the first case block is executed and the received message is printed. Otherwise, the second case block is executed and a timeout message is printed.

gistlibby LogSnag