package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func sseHandler(c *gin.Context) {
// 设置响应头为Server-Sent Events
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
flusher, ok := c.Writer.(http.Flusher)
if !ok {
c.Status(http.StatusInternalServerError)
return
}
for i := 0; ; i++ {
// 发送事件数据
data := fmt.Sprintf("data: %d - %s\n\n", i, time.Now().Format(time.RFC1123))
if _, err := c.Writer.WriteString(data); err != nil {
c.Error(err)
return
}
flusher.Flush() // 刷新响应,确保即时发送数据
time.Sleep(1 * time.Second) // 每秒发送一次数据
}
}
func main() {
r := gin.Default()
r.GET("/stream", sseHandler)
r.StaticFile("/", "./static/index.html")
r.Run(":8080")
}