aboutsummaryrefslogtreecommitdiff
path: root/requestctx_setbodystreamwriter_example_test.go
blob: af9b09c5c1bf2f10bf409441d7899a3b32eb4da2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package fasthttp_test

import (
	"bufio"
	"fmt"
	"log"
	"time"

	"github.com/valyala/fasthttp"
)

func ExampleRequestCtx_SetBodyStreamWriter() {
	// Start fasthttp server for streaming responses.
	if err := fasthttp.ListenAndServe(":8080", responseStreamHandler); err != nil {
		log.Fatalf("unexpected error in server: %v", err)
	}
}

func responseStreamHandler(ctx *fasthttp.RequestCtx) {
	// Send the response in chunks and wait for a second between each chunk.
	ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
		for i := 0; i < 10; i++ {
			fmt.Fprintf(w, "this is a message number %d", i)

			// Do not forget flushing streamed data to the client.
			if err := w.Flush(); err != nil {
				return
			}
			time.Sleep(time.Second)
		}
	})
}