CaIon 2 лет назад
Родитель
Сommit
701a28d0da
2 измененных файлов с 17 добавлено и 1 удалено
  1. 16 0
      common/go-channel.go
  2. 1 1
      controller/relay-openai.go

+ 16 - 0
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
+}

+ 1 - 1
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 {