等到handler完成才会结束请求

This commit is contained in:
Pan Qiancheng 2025-04-15 15:30:01 +08:00
parent 22c1bfc2b2
commit 3d3a3cee40
2 changed files with 13 additions and 5 deletions

View File

@ -175,7 +175,6 @@ func (t *UnixSocketTask) handleConnection(conn net.Conn) {
client := client.NewClient()
handleQuestion := func(question string) {
logger.Debug("question: %s", question)
if loading {
loading = false // 停止加载动画
t.writeMessage(conn, "\r")
@ -197,6 +196,7 @@ func (t *UnixSocketTask) handleConnection(conn net.Conn) {
}
// 结束后发送结束标记
t.writeMessage(conn, "\n\r")
t.writeMessage(conn, "[end]")
conn.Close() // 关闭连接防止客户端一直等待inf
logger.Debug("connection done.")

View File

@ -12,6 +12,7 @@ import (
"os"
"path"
"strings"
"sync"
"time"
)
@ -255,14 +256,18 @@ func (c *Client) PostToStream(uri string, body interface{}, query map[string]str
reader := bufio.NewReader(resp.Body)
var buffer strings.Builder
ticker := time.NewTicker(250 * time.Millisecond) // 每 250 ms处理一次
ticker := time.NewTicker(250 * time.Millisecond)
defer ticker.Stop()
done := make(chan struct{})
errChan := make(chan error, 1)
// 启动一个定时处理协程
var wg sync.WaitGroup
wg.Add(1)
// 处理数据的协程
go func() {
defer wg.Done()
for {
select {
case <-ticker.C:
@ -271,7 +276,6 @@ func (c *Client) PostToStream(uri string, body interface{}, query map[string]str
buffer.Reset()
}
case <-done:
// flush final
if buffer.Len() > 0 {
messageHandler(buffer.String())
}
@ -280,7 +284,7 @@ func (c *Client) PostToStream(uri string, body interface{}, query map[string]str
}
}()
// 读取数据的主循环
// 读取数据
go func() {
for {
chunk := make([]byte, 256)
@ -300,11 +304,15 @@ func (c *Client) PostToStream(uri string, body interface{}, query map[string]str
errChan <- nil
}()
// 等待读取是否有错误
if err := <-errChan; err != nil {
logger.Error("Error reading response stream")
return err
}
// 等待 messageHandler 完成处理
wg.Wait()
return nil
}