golang 流式讀取和發(fā)送使用場景示例
場景
- 部分大模型(如gpt)的流式讀取,可以增加用戶體驗。
- gin框架的流式問答,與前端交互。
使用方法
- 我在使用框架req 的時候,發(fā)現(xiàn)無法從resp.Body流式讀取數(shù)據(jù),只能完整讀出來
原因是框架自動幫我們讀取了resp,導致我們無法讀取流式的消息。
正常我們獲取返回值應該是這樣的:
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ā)送的詳細內(nèi)容,更多關于golang流式讀取和發(fā)送的資料請關注腳本之家其它相關文章!
相關文章
Golang并發(fā)讀取文件數(shù)據(jù)并寫入數(shù)據(jù)庫的項目實踐
本文主要介紹了Golang并發(fā)讀取文件數(shù)據(jù)并寫入數(shù)據(jù)庫的項目實踐,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-06-06GO利用channel協(xié)調(diào)協(xié)程的實現(xiàn)
本文主要介紹了GO利用channel協(xié)調(diào)協(xié)程的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-05-05利用go-zero在Go中快速實現(xiàn)JWT認證的步驟詳解
這篇文章主要介紹了如何利用go-zero在Go中快速實現(xiàn)JWT認證,本文分步驟通過實例圖文相結合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2020-10-10