当前的OpenAI 接口在回复的消息时候,前端不是采用长轮询的方式,而是采用SSE 的方式进行服务端消息推送,以减少消息传输的网络延时。
以下是Go 语言服务端进行SSE 消息推送的实现:
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
// 设置HTTP路由
http.HandleFunc("/events", handleEvents)
// 启动HTTP服务器
fmt.Println("Server started at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
func handleEvents(w http.ResponseWriter, r *http.Request) {
// 设置响应头,声明服务器支持SSE
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
// 发送实时事件
for {
// 通过Write方法向客户端发送SSE消息
fmt.Fprintf(w, "data: %s\n\n", time.Now().Format(time.Stamp))
w.(http.Flusher).Flush() // 刷新响应流
time.Sleep(1 * time.Second) // 每秒发送一次事件
}
}
执行代码:
go run main.go
另起一个终端,通过curl 来访问:
curl localhost:8080/events
在终端上可以看到每隔1秒钟收到一条消息:
image.png