我想在 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)
但是当我试图到达终点时,它卡住了,没有任何反应。 是否有人使用了流功能,以便他/她可以指出我可能犯的错误。谢谢!
最佳答案
如果流结束,您应该返回 false。并关闭 chan。
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()
}
额外的
客户端代码应该是:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
var stream = new EventSource("/stream");
stream.addEventListener("message", function(e){
console.log(e.data);
});
</script>
</body>
</html>
关于api - 如何在 golang 中使用 gin-gonic 服务器编写流 API?试过 c.Stream 没用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44825244/