How to write a stream API using gin-gonic server in golang? Tried c.Stream didnt work

后端 未结 1 925
孤城傲影
孤城傲影 2021-02-15 15:44

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          


        
1条回答
  •  一向
    一向 (楼主)
    2021-02-15 16:15

    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()
    }
    

    Additional

    Client code should be:

    
    
    
        
        
    
    
        
    
    
    

    0 讨论(0)
提交回复
热议问题