
上一篇通过node实现了SSE,下面介绍下golang实现
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type Message struct {
Text string `json:"text"`
}
func main() {
fs := http.FileServer(http.Dir("./"))
http.Handle("/", http.StripPrefix("/", fs))
http.HandleFunc("/sse", func(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")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// w.Header().Set("Access-Control-Allow-Credentials", "true")
// 解析请求体
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
http.Error(w, "Error reading request body", http.StatusInternalServerError)
return
}
if len(body) == 0 {
for i := 0; i < 100; i++ {
fmt.Fprintf(w, "data: The message is: %v\n\n", i)
w.(http.Flusher).Flush() // 刷新数据到客户端
}
return
}
var msg Message
err = json.Unmarshal(body, &msg)
if err != nil {
http.Error(w, "Error parsing request body", http.StatusBadRequest)
return
}
// 使用请求体中的消息向客户端发送事件
for {
fmt.Fprintf(w, "data: The message is: %v\n\n", msg.Text)
w.(http.Flusher).Flush() // 刷新数据到客户端
time.Sleep(time.Second)
}
})
http.ListenAndServe(":8080", nil)
}首先我们看到实现了三个头
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")然后通过"data: 开头的消息,将内容发送给客户端
fmt.Fprintf(w, "data: The message is: %v\n\n", i)
w.(http.Flusher).Flush() // 刷新数据到客户端接着看下客户端代码的实现
<!DOCTYPE html>
<html>
<head>
<script>
var source = new EventSource("http://127.0.0.1:8080/sse");
source.onmessage = function (event) {
document.body.innerHTML += event.data + "<br>";
};
// source.addEventListener('customEvent', (e) => {
// console.log('自定义事件:', e.data);
// });
</script>
</head>
<body>
sse
</body>
</html>最后看下效果
http://127.0.0.1:8080/sse/server/client.htmlThe message is: 37
The message is: 38
...
The message is: 52
The message is: 53整体来说,sse并不是什么新鲜东西,只是一个保持长连接的http请求,非常适合一个请求返回很多数据,或者需要不断推送结果的场景,比如LLM。
本文分享自 golang算法架构leetcode技术php 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!