- SSEvent: 此函数用于向客户端发送一个Server-Sent Event (SSE)。SSE是一种允许服务器端实时地向客户端推送消息的技术。函数接受两个参数:
name
(事件名称)和message
(事件数据)。通过调用c.Render
方法,将事件名称和数据打包成一个 SSE 事件,并将其写入响应流。 - Stream: 此函数用于发送一个流式响应。流式响应允许服务器在单个响应中持续地向客户端发送数据。函数接受一个参数:
step
(一个函数,它返回一个布尔值,指示是否继续保持连接)。Stream
函数通过循环,反复执行step
函数。如果客户端在传输过程中断开连接,函数将返回true
。如果step
函数返回false
,则表示不再发送数据,并结束流。
两者之间的区别:
- SSEvent 主要用于发送实时事件,而 Stream 用于持续发送数据流。
- SSEvent 使用 Server-Sent Event 格式发送数据,而 Stream 可以发送任意格式的数据。
- SSEvent 只负责发送一次事件,而 Stream 负责维护一个持续的数据流。
package main import ( "fmt" "io" "time" "github.com/gin-gonic/gin" ) type Context struct { *gin.Context } func main() { router := gin.Default() router.GET("/sse", func(c *gin.Context) { ctx := &Context{c} ctx.SSEvent("time", fmt.Sprintf("The current time is %s", time.Now().Format(time.RFC1123))) }) router.GET("/stream", func(c *gin.Context) { ctx := &Context{c} ctx.Stream(func(w io.Writer) bool { time.Sleep(1 * time.Second) _, err := w.Write([]byte(fmt.Sprintf("The current time is %s\n", time.Now().Format(time.RFC1123)))) return err == nil }) }) router.Run(":8080") }