fix: try to fix panic #369

This commit is contained in:
CalciumIon 2024-07-17 16:38:56 +08:00
parent 11856ab39e
commit 4d0d18931d
2 changed files with 16 additions and 9 deletions

View File

@ -53,7 +53,10 @@ func OpenaiStreamHandler(c *gin.Context, resp *http.Response, info *relaycommon.
} }
data = data[6:] data = data[6:]
if !strings.HasPrefix(data, "[DONE]") { if !strings.HasPrefix(data, "[DONE]") {
service.StringData(c, data) err := service.StringData(c, data)
if err != nil {
common.LogError(c, "streaming error: "+err.Error())
}
streamItems = append(streamItems, data) streamItems = append(streamItems, data)
} }
} }

View File

@ -2,10 +2,10 @@ package service
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"one-api/common" "one-api/common"
"strings"
) )
func SetEventStreamHeaders(c *gin.Context) { func SetEventStreamHeaders(c *gin.Context) {
@ -16,11 +16,16 @@ func SetEventStreamHeaders(c *gin.Context) {
c.Writer.Header().Set("X-Accel-Buffering", "no") c.Writer.Header().Set("X-Accel-Buffering", "no")
} }
func StringData(c *gin.Context, str string) { func StringData(c *gin.Context, str string) error {
str = strings.TrimPrefix(str, "data: ") //str = strings.TrimPrefix(str, "data: ")
str = strings.TrimSuffix(str, "\r") //str = strings.TrimSuffix(str, "\r")
c.Render(-1, common.CustomEvent{Data: "data: " + str}) c.Render(-1, common.CustomEvent{Data: "data: " + str})
c.Writer.Flush() if c.Writer != nil {
c.Writer.Flush()
} else {
return errors.New("writer is nil")
}
return nil
} }
func ObjectData(c *gin.Context, object interface{}) error { func ObjectData(c *gin.Context, object interface{}) error {
@ -28,12 +33,11 @@ func ObjectData(c *gin.Context, object interface{}) error {
if err != nil { if err != nil {
return fmt.Errorf("error marshalling object: %w", err) return fmt.Errorf("error marshalling object: %w", err)
} }
StringData(c, string(jsonData)) return StringData(c, string(jsonData))
return nil
} }
func Done(c *gin.Context) { func Done(c *gin.Context) {
StringData(c, "[DONE]") _ = StringData(c, "[DONE]")
} }
func GetResponseID(c *gin.Context) string { func GetResponseID(c *gin.Context) string {