golang 流式讀取和發(fā)送使用場景示例
場景
- 部分大模型(如gpt)的流式讀取,可以增加用戶體驗(yàn)。
- gin框架的流式問答,與前端交互。
使用方法
- 我在使用框架req 的時(shí)候,發(fā)現(xiàn)無法從resp.Body流式讀取數(shù)據(jù),只能完整讀出來
原因是框架自動幫我們讀取了resp,導(dǎo)致我們無法讀取流式的消息。
正常我們獲取返回值應(yīng)該是這樣的:
resp := c.c.Post(url).SetQueryParam("key", c.key).SetBody(msg).Do(ctx)
data := resp.String()想要讀取流式可以這么做:
resp := c.c.DisableAutoReadResponse().Post(url).SetQueryParam("key", c.key).SetBody(msg).Do(ctx)
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if strings.Contains(line, "text") {
fmt.Println(line)
}
}- 現(xiàn)在我們知道了如何從外部讀取流式數(shù)據(jù),那么我們?nèi)绾卫脀eb框架發(fā)送流式數(shù)據(jù)呢?
以gin框架為例
可以使用func (c *Context) Stream(step func(w io.Writer) bool) bool函數(shù)
==具體使用方法如下==(這里我用了自己的代碼做了演示):
如果前端有需求,需要加上Header
c.Header("Content-Type", "application/octet-stream")用bufio緩沖區(qū)向前端寫數(shù)據(jù)
stop := c.Stream(func(w io.Writer) bool {
bw := bufio.NewWriter(w)
if len(r.Choices) != 0 {
gptResult.Detail = &r
gptResult.Id = r.ID
gptResult.Role = openai.ChatMessageRoleAssistant
gptResult.Text += r.Choices[0].Delta.Content // 流傳輸
marshal, _ := json.Marshal(gptResult)
if _, err := fmt.Fprintf(bw, "%s\n", marshal); err != nil {
fmt.Println(err)
return true
}
bw.Flush()
}
return false
}) //stop
if stop {
fmt.Println("stop")
break
}順便講一下flush吧,按官方文檔來說,是為了將寫好的數(shù)據(jù)發(fā)送給客戶端。
// The Flusher interface is implemented by ResponseWriters that allow
// an HTTP handler to flush buffered data to the client.
type Flusher interface {
// Flush sends any buffered data to the client.
Flush()
}以上就是golang流式讀取和發(fā)送的詳細(xì)內(nèi)容,更多關(guān)于golang流式讀取和發(fā)送的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Go語言實(shí)現(xiàn)簡單聊天系統(tǒng)
本文介紹了如何使用Go語言和WebSocket技術(shù)構(gòu)建一個(gè)簡單的多人聊天室系統(tǒng),包括客戶端連接管理、消息廣播和并發(fā)處理,最后,通過編寫main.go、hub.go和client.go等核心代碼模塊,具有一定的參考價(jià)值,感興趣的可以了解一下2024-10-10
基于golang如何實(shí)現(xiàn)error工具包詳解
Go 語言使用 error 類型來返回函數(shù)執(zhí)行過程中遇到的錯(cuò)誤,下面這篇文章主要給大家介紹了關(guān)于如何基于golang實(shí)現(xiàn)error工具包的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2018-09-09
Go語言實(shí)現(xiàn)socket實(shí)例
這篇文章主要介紹了Go語言實(shí)現(xiàn)socket的方法,實(shí)例分析了socket客戶端與服務(wù)器端的實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-02-02

