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")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?