From 15e90971aa86270e6710d27d9abea8cda3a151d1 Mon Sep 17 00:00:00 2001 From: Donnie Adams Date: Fri, 28 Jun 2024 16:21:36 -0400 Subject: [PATCH] fix: set wait function before spinning off goroutine In special circumstances, the goroutine might finish before the wait function was set, causing a panic. Signed-off-by: Donnie Adams --- run.go | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/run.go b/run.go index 785890b..c706b61 100644 --- a/run.go +++ b/run.go @@ -244,6 +244,17 @@ func (r *Run) request(ctx context.Context, payload any) (err error) { r.events = make(chan Frame, 100) r.lock.Lock() + + r.wait = func() { + <-cancelCtx.Done() + if err := context.Cause(cancelCtx); !errors.Is(err, context.Canceled) && r.err == nil { + r.state = Error + r.err = err + } else if r.state != Continue && r.state != Error { + r.state = Finished + } + } + go func() { var ( err error @@ -385,16 +396,6 @@ func (r *Run) request(ctx context.Context, payload any) (err error) { } }() - r.wait = func() { - <-cancelCtx.Done() - if err := context.Cause(cancelCtx); !errors.Is(err, context.Canceled) && r.err == nil { - r.state = Error - r.err = err - } else if r.state != Continue && r.state != Error { - r.state = Finished - } - } - return nil }