2 changed files with 72 additions and 0 deletions
@ -0,0 +1,46 @@ |
|||||
|
package core |
||||
|
|
||||
|
import ( |
||||
|
"encoding/json" |
||||
|
"fmt" |
||||
|
"net/http" |
||||
|
"time" |
||||
|
) |
||||
|
|
||||
|
// 处理sse事件
|
||||
|
func handleEvents(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秒发送一次消息
|
||||
|
} |
||||
|
} |
||||
|
} |
||||
Loading…
Reference in new issue