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

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.go
func receiveWithTimeout(ch <-chan json.RawMessage, timeout time.Duration) (msg json.RawMessage, err error) {
    select {
    case msg = <-ch:
        return msg, nil
    case <-time.After(timeout):
        return nil, errors.New("timeout receiving message")
    }
}

func main() {
    ch := make(chan json.RawMessage)
    go func() {
        // Simulate sending a message after 1 second
        time.Sleep(time.Second)
        ch <- json.RawMessage(`{"foo": "bar"}`)
    }()

    // Receive message with a timeout of 2 seconds
    msg, err := receiveWithTimeout(ch, 2*time.Second)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(string(msg))
    }
}
681 chars
26 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