Stream Response
Learn how to send streaming responses in Iris.
Basic Streaming
go
package main
import (
"time"
"github.com/kataras/iris/v12"
)
func main() {
app := iris.New()
app.Get("/stream", func(ctx iris.Context) {
ctx.ContentType("text/plain")
for i := 0; i < 10; i++ {
ctx.Writef("Message %d\n", i)
ctx.ResponseWriter().Flush()
time.Sleep(time.Second)
}
})
app.Listen(":8080")
}
Stream Writer
go
app.Get("/writer", func(ctx iris.Context) {
ctx.StreamWriter(func(w *bufio.Writer) bool {
msg := fmt.Sprintf("Server time: %s\n", time.Now().Format(time.RFC3339))
w.WriteString(msg)
w.Flush()
time.Sleep(time.Second)
return true // continue streaming
})
})
JSON Streaming
go
app.Get("/json-stream", func(ctx iris.Context) {
ctx.ContentType("application/json")
enc := json.NewEncoder(ctx.ResponseWriter())
for i := 0; i < 10; i++ {
data := iris.Map{
"message": fmt.Sprintf("Message %d", i),
"time": time.Now(),
}
enc.Encode(data)
ctx.ResponseWriter().Flush()
time.Sleep(time.Second)
}
})
Best Practices
Implementation:
- Handle timeouts
- Monitor connections
- Flush regularly
- Handle errors
- Clean resources
Performance:
- Buffer appropriately
- Monitor memory
- Handle backpressure
- Optimize writes
- Regular cleanup
Headers:
- Set content type
- Configure chunked
- Handle compression
- Monitor client
- Set timeouts
Maintenance:
- Monitor streams
- Handle disconnects
- Regular testing
- Document usage
- Review performance