You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.0 KiB
46 lines
1.0 KiB
package core
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// 处理sse事件
|
|
func SseHandler(w http.ResponseWriter, r *http.Request) {
|
|
// 设置 CORS 头部
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
|
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
|
|
|
// 设置响应头
|
|
w.Header().Set("Content-Type", "text/event-stream")
|
|
w.Header().Set("Cache-Control", "no-cache")
|
|
w.Header().Set("Connection", "keep-alive")
|
|
|
|
// 模拟数据流
|
|
for {
|
|
// 生成推送消息
|
|
data, _ := json.Marshal(map[string]string{"timestamp": time.Now().Format(time.RFC3339)})
|
|
_, err := fmt.Fprintf(w, "data: %s\n\n", data)
|
|
if err != nil {
|
|
// 客户端断开连接,输出日志
|
|
fmt.Println("Client disconnected:", err)
|
|
return
|
|
}
|
|
|
|
// 刷新缓冲区
|
|
if flusher, ok := w.(http.Flusher); ok {
|
|
flusher.Flush()
|
|
}
|
|
|
|
// 检查是否应该关闭连接
|
|
select {
|
|
case <-r.Context().Done():
|
|
return
|
|
default:
|
|
time.Sleep(2 * time.Second) // 每2秒发送一次消息
|
|
}
|
|
}
|
|
}
|
|
|