Skip to content

Commit

Permalink
improvement stream output
Browse files Browse the repository at this point in the history
  • Loading branch information
ljnchn committed Dec 23, 2023
1 parent a79d82f commit ccd37ab
Showing 1 changed file with 18 additions and 13 deletions.
31 changes: 18 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,19 +155,12 @@ func forwardRequest(c *gin.Context) {

c.Header("Content-Type", "text/event-stream; charset=utf-8")

// 创建一个缓冲读取器
reader := bufio.NewReader(resp.Body)

// 读取流并替换 "content":null 为 "content":""
for {
line, err := reader.ReadBytes('\n')
if err == io.EOF {
break
}
if err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
// 创建一个新的扫描器
scanner := bufio.NewScanner(resp.Body)

// 使用Scan方法来读取流
for scanner.Scan() {
line := scanner.Bytes()

// 替换 "content":null 为 "content":""
modifiedLine := bytes.Replace(line, []byte(`"content":null`), []byte(`"content":""`), -1)
Expand All @@ -177,6 +170,18 @@ func forwardRequest(c *gin.Context) {
c.AbortWithError(http.StatusInternalServerError, err)
return
}

// 添加一个换行符
if _, err := c.Writer.Write([]byte("\n")); err != nil {
c.AbortWithError(http.StatusInternalServerError, err)
return
}
}

if scanner.Err() != nil {
// 处理来自扫描器的任何错误
c.AbortWithError(http.StatusInternalServerError, scanner.Err())
return
}
return
}
Expand Down

0 comments on commit ccd37ab

Please sign in to comment.