From e007125f78963f7436cd1f7b4f019ef690b3208e Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Thu, 9 Mar 2023 15:34:13 -0800 Subject: [PATCH] lnutils: add RecvOrTimeout This abstracts out a common pattern where we wait for a send on a channel, and timeout otherwise. --- lnutils/chan.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 lnutils/chan.go diff --git a/lnutils/chan.go b/lnutils/chan.go new file mode 100644 index 000000000..b85c0de96 --- /dev/null +++ b/lnutils/chan.go @@ -0,0 +1,18 @@ +package lnutils + +import ( + "fmt" + "time" +) + +// RecvOrTimeout attempts to recv over chan c, returning the value. If the +// timeout passes before the recv succeeds, an error is returned +func RecvOrTimeout[T any](c <-chan T, timeout time.Duration) (*T, error) { + select { + case m := <-c: + return &m, nil + + case <-time.After(timeout): + return nil, fmt.Errorf("timeout hit") + } +}