receive a binary message from a channel with a timeout in go

To receive a binary message from a channel with a timeout in Go, we can use the select statement with a combination of time.After() and the channel receiving operation. Here is an example implementation:

main.go
// ReceiveBinaryWithTimeout blocks for a certain amount of time until a binary message is received from the given channel.
// If the timeout is reached before a message is received, it returns an error.
func ReceiveBinaryWithTimeout(ch <-chan []byte, timeout time.Duration) ([]byte, error) {
    select {
    case msg := <-ch:
        return msg, nil
    case <-time.After(timeout):
        return nil, fmt.Errorf("timeout of %v reached for receiving binary message", timeout)
    }
}
485 chars
11 lines

To receive a binary message from the channel myBinaryCh with a timeout of 5 seconds, we can call this function as follows:

main.go
msg, err := ReceiveBinaryWithTimeout(myBinaryCh, 5*time.Second)
if err != nil {
    log.Printf("Error receiving binary message: %v", err)
    return
}
// Process msg here...
174 chars
7 lines

In this example, if no message is received on myBinaryCh within 5 seconds, the function will return an error. Otherwise, it will return the received binary message.

gistlibby LogSnag