在 Gin
(后端)和 Vue3
(前端)中實現 Server-Sent Events(SSE)推送,主要分為以下幾個步驟:
后端(Gin)實現 SSE
Gin 框架可以使用 c.SSEvent
方法來推送 SSE 事件。
1. 安裝 Gin
確保你的 Go 項目已安裝 gin
:
go get -u github.com/gin-gonic/gin
2. Gin SSE 服務器
創建一個 SSE 端點 /sse
,用于持續向前端推送消息:
package mainimport ("fmt""net/http""time""github.com/gin-gonic/gin"
)func main() {r := gin.Default()// SSE 推送r.GET("/sse", func(c *gin.Context) {// 設置 SSE 相關 Headerc.Writer.Header().Set("Content-Type", "text/event-stream")c.Writer.Header().Set("Cache-Control", "no-cache")c.Writer.Header().Set("Connection", "keep-alive")// 監聽客戶端斷開連接notify := c.Writer.CloseNotify()// 模擬持續推送for {select {case <-notify:fmt.Println("客戶端斷開連接")returndefault:// 發送數據c.SSEvent("message", gin.H{"time": time.Now().Format("15:04:05")})c.Writer.Flush() // 立即刷新time.Sleep(2 * time.Second)}}})r.Run(":8080")
}
前端(Vue3 + Composition API)監聽 SSE
Vue3 通過 EventSource
監聽 SSE 事件。
1. Vue3 組件實現
創建 SseComponent.vue
:
<template><div><h2>SSE 推送數據</h2><p v-if="message">時間:{{ message }}</p><button @click="stopSSE">斷開連接</button></div>
</template><script setup>
import { ref, onMounted, onUnmounted } from "vue";let eventSource = null;
const message = ref("");const startSSE = () => {eventSource = new EventSource("http://localhost:8080/sse");eventSource.onmessage = (event) => {const data = JSON.parse(event.data);message.value = data.time;};eventSource.onerror = () => {console.error("SSE 連接錯誤");eventSource.close();};
};const stopSSE = () => {if (eventSource) {eventSource.close();console.log("SSE 連接已關閉");}
};onMounted(startSSE);
onUnmounted(stopSSE);
</script>
3. 運行 Gin 服務器和 Vue 前端
啟動 Gin 服務器:
go run main.go
啟動 Vue3:
npm run dev
然后在瀏覽器訪問 Vue 頁面,即可看到 SSE 推送的消息不斷更新。
這樣,我們就完成了 Gin + Vue3 的 SSE 實時推送,適用于實時通知、股票行情、日志監控等場景 🎉。