From 701a28d0da080ebe0b2a622b60768ec13d9fe17a Mon Sep 17 00:00:00 2001 From: CaIon <1808837298@qq.com> Date: Wed, 10 Jan 2024 19:26:11 +0800 Subject: [PATCH] fix: fix relay openai panic --- common/go-channel.go | 16 ++++++++++++++++ controller/relay-openai.go | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 common/go-channel.go diff --git a/common/go-channel.go b/common/go-channel.go new file mode 100644 index 0000000..73c5f51 --- /dev/null +++ b/common/go-channel.go @@ -0,0 +1,16 @@ +package common + +func SafeSend(ch chan bool, value bool) (closed bool) { + defer func() { + // Recover from panic if one occured. A panic would mean the channel was closed. + if recover() != nil { + closed = true + } + }() + + // This will panic if the channel is closed. + ch <- value + + // If the code reaches here, then the channel was not closed. + return false +} diff --git a/controller/relay-openai.go b/controller/relay-openai.go index c0d3df1..24cfd06 100644 --- a/controller/relay-openai.go +++ b/controller/relay-openai.go @@ -83,7 +83,7 @@ func openaiStreamHandler(c *gin.Context, resp *http.Response, relayMode int) (*O // wait data out time.Sleep(2 * time.Second) } - stopChan <- true + common.SafeSend(stopChan, true) }() setEventStreamHeaders(c) c.Stream(func(w io.Writer) bool {