To receive a JSON message from a channel with a timeout in Go, we can use the select
statement and a separate Goroutine to monitor the timeout. Here's an example:
main.go681 chars26 lines
In this example, receiveWithTimeout
is a function that receives from a channel ch
and return a message and error. If receiving from the channel takes longer than timeout
, it returns an error.
The main
function creates a channel and a Goroutine that sends a JSON message after 1 second. It then calls receiveWithTimeout
with a timeout of 2 seconds to receive the message. If the message is received within 2 seconds, it prints the JSON string. Otherwise, it prints the error message.
gistlibby LogSnag