如何在Golang中使用gin-gonic服务器编写流API?尝试c.Stream没有工作 [英] How to write a stream API using gin-gonic server in golang? Tried c.Stream didnt work
本文介绍了如何在Golang中使用gin-gonic服务器编写流API?尝试c.Stream没有工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在golang中使用gin-gonic服务器创建一个流API.
I wanted to create one streaming API using gin-gonic server in golang.
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)
但是,当我尝试触碰端点时,它只是卡住而没有任何响应. 是否有人使用流功能,以便他/她可以指出我可能正在做的错误.谢谢!
But when I am trying to hit the endpoint, it just stucks and no response comes. Has someone used the stream function so that he/she can point the mistake which I might be doing. Thanks!
推荐答案
如果流结束,则应返回false.并关闭chan.
You should return false if the stream ended. And close the 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>
这篇关于如何在Golang中使用gin-gonic服务器编写流API?尝试c.Stream没有工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文