For those using Gin, and struggling to get c.Stream
or c.Writer.Flush()
working, this example will stream JSON data.
// package main
// import "github.com/gin-gonic/gin"
func readItemList(c *gin.Context) {
type Item struct {
Shape string `json:"shape"`
Color string `json:"color"`
}
var itemList = []Item{
{"circle", "blue"},
{"square", "green"},
{"triangle", "yellow"},
}
c.Header("content-type", "application/json")
c.Writer.WriteHeader(http.StatusOK)
enc := json.NewEncoder(c.Writer)
for _, item := range itemList {
if err := enc.Encode(item); err != nil {
// print error
}
c.Writer.Flush()
time.Sleep(1 * time.Second)
}
}
// func main() {
// r := gin.Default()
// r.GET("/items", readItemList)
// r.Run() // listen and serve on 0.0.0.0:8080
// }
Do not use Postman, as it will not print streams correctly... but instead use cURL...
curl localhost:8080/items
Comment From: ex-tag
Warning: Gzip compression will cause problems for your stream.
You need to compress each chunk, instead of the entire response. Do not use the Gzip middleware as that will compress the entire response, and the browser will decompress only after the entire response has been received.
r := gin.New()
// This common Gzip middleware will cause problems for your stream
r.Use(gzip.Gzip(gzip.DefaultCompression))