How do I stream large JSON arrays with Gin in Go?

This example shows how to stream large JSON arrays using the Gin framework in Go. It provides an efficient way to serve JSON data without overwhelming the server's memory.

Go, Gin, Streaming JSON, Large JSON Arrays, REST API

package main import ( "github.com/gin-gonic/gin" "net/http" "time" ) func main() { router := gin.Default() // Sample route to stream a large JSON array router.GET("/stream-json", func(c *gin.Context) { c.Stream(http.StatusOK, "application/json", func(w io.Writer) bool { // Simulating streaming of a large JSON array w.Write([]byte("[")) for i := 0; i < 1000; i++ { // Writing individual JSON objects w.Write([]byte(`{"id":` + fmt.Sprintf("%d", i) + `,"value":"example"}`)) // Add a comma after each item except the last if i < 999 { w.Write([]byte(",")) } time.Sleep(10 * time.Millisecond) // Simulate delay } w.Write([]byte("]")) return false // No more data to send }) }) router.Run(":8080") }

Go Gin Streaming JSON Large JSON Arrays REST API