How do I stream responses with Fiber in Go?

Streaming responses in Fiber can improve performance by sending data to the client in chunks rather than waiting for the entire response to be ready. This is particularly useful for long-running processes or when sending large payloads.

streaming, Fiber, Go, HTTP responses, performance

This example demonstrates how to set up a simple streaming response using the Fiber web framework in Go.

package main import ( "github.com/gofiber/fiber/v2" "time" ) func main() { app := fiber.New() // Define a GET route to stream responses app.Get("/stream", func(c *fiber.Ctx) error { c.Set("Content-Type", "text/event-stream") c.Set("Transfer-Encoding", "chunked") for i := 0; i < 10; i++ { // Write a message to the response if err := c.WriteString("data: Streamed message " + fmt.Sprint(i) + "\n\n"); err != nil { return err } // Flush the response buffer if err := c.Context().Flush(); err != nil { return err } // Sleep for a second before sending the next message time.Sleep(1 * time.Second) } return nil }) app.Listen(":3000") }

streaming Fiber Go HTTP responses performance