golang sse demo

ddatsh

dev #go
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSE Demo</title>
</head>
<body>
<h1>Server-Sent Events Demo</h1>
<div id="time">Waiting for server time...</div>

<script>
    var source = new EventSource('/stream');
    source.onmessage = function(event) {
        document.getElementById('time').innerHTML = 'Server time: ' + event.data;
    };
    source.onerror = function(event) {
        source.close();
    };
</script>
</body>
</html>
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")
}