Browse Source

增加sse推送代码

master
xyiege 4 months ago
parent
commit
a475758c8f
  1. 46
      aufs/core/sse.go
  2. 26
      aufs/main.go

46
aufs/core/sse.go

@ -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秒发送一次消息
}
}
}

26
aufs/main.go

@ -3,9 +3,33 @@ package main
import (
"aufs/config"
"fmt"
"log"
"net/http"
"os"
)
// 启动web服务
func startWeb() {
//创建一个文件服务器,会去www目录下找index.html
fileServer := http.FileServer(http.Dir("./fsw"))
// 将 "/" 路径映射到文件服务器
http.Handle("/", fileServer)
//扫描指定的目录
http.HandleFunc("/sc", core.SerInfo)
// 数据库基础信息
http.HandleFunc("/bs", core.BfsInfo)
// 文件接收
http.HandleFunc("/rc", core.ReceiveHandler)
// 发送zip文件
http.HandleFunc("/sendZip", core.SendZip)
fmt.Printf("Starting server at port 9099\n")
// 启动HTTP服务器并监听端口 80,如果出现错误,则打印错误信息并退出
if err := http.ListenAndServe(":9099", nil); err != nil {
log.Fatal(err)
}
}
func main() {
// 执行的时候,没有附带参数默认为客户端
// 获取ip地址
@ -39,4 +63,6 @@ func main() {
// current work directory
config.G.FilePath = curdir
}
// web service
startWeb()
}

Loading…
Cancel
Save