如何在golang中使用gin-gonic服务器编写流API?试过c.Stream没工作

kun*_*lag 5 api streaming go goroutine go-gin

我想在golang中使用gin-gonic服务器创建一个流API.

func StreamData(c *gin.Context) {
    chanStream := make(chan int, 10)
    go func() {for i := 0; i < 5; i++ {
        chanStream <- i
        time.Sleep(time.Second * 1)
    }}()
    c.Stream(func(w io.Writer) bool {
        c.SSEvent("message", <-chanStream)
        return true
    })
}

router.GET("/stream", controller.StreamData)
Run Code Online (Sandbox Code Playgroud)

但是当我试图击中端点时,它只是卡住而没有响应.有人使用流功能,以便他/她可以指出我可能正在做的错误.谢谢!

mat*_*ttn 11

如果流结束,则应返回false.并关闭陈.

package main

import (
    "io"
    "time"

    "github.com/gin-gonic/contrib/static"
    "github.com/gin-gonic/gin"
    "github.com/mattn/go-colorable"
)

func main() {
    gin.DefaultWriter = colorable.NewColorableStderr()
    r := gin.Default()
    r.GET("/stream", func(c *gin.Context) {
        chanStream := make(chan int, 10)
        go func() {
            defer close(chanStream)
            for i := 0; i < 5; i++ {
                chanStream <- i
                time.Sleep(time.Second * 1)
            }
        }()
        c.Stream(func(w io.Writer) bool {
            if msg, ok := <-chanStream; ok {
                c.SSEvent("message", msg)
                return true
            }
            return false
        })
    })
    r.Use(static.Serve("/", static.LocalFile("./public", true)))
    r.Run()
}
Run Code Online (Sandbox Code Playgroud)

  • 发现问题....在gin路由器中使用gzip压缩.它不允许它传播事件.评论它,现在工作正常. (2认同)