Stream
Content-Type: *
Chunked transfer encoding is a streaming data transfer mechanism available in HTTP/1.1. In chunked transfer encoding, the data stream is divided into a series of non-overlapping "chunks". The chunks are sent out and received independently of one another. No knowledge of the data stream outside the currently-being-processed chunk is necessary for both the sender and the receiver at any given time.
The chunked keyword in the Transfer-Encoding header is used to indicate chunked transfer.
HTTP/2 uses DATA frames to carry message payloads. The "chunked" transfer encoding defined in MUST NOT be used in HTTP/2.
References:
As we read above, the Transfer-Encoding: "chunked" header is required:
1
ctx.Header("Transfer-Encoding", "chunked")
Copied!
Then, define the response content type (when we use the ctx.Write methods), e.g.
1
ctx.ContentType("text/html")
Copied!
And we write the contents:
1
ctx.Writef("A message here")
Copied!
Finally, we must flush the contents with:
1
ctx.ResponseWriter().Flush()
Copied!
And repeat.
Iris gives you a helper method which sends streaming data until connection close or error returned:
1
StreamWriter(func(w io.Writer) error) error
Copied!
The second way for streaming data is with ctx.XXX response methods (as we've seen previously, e.g. ctx.JSON) following by a ctx.ResponseWriter().Flush()).

Example

Let's say that you want to send number messages from 1 to 29.
1
var errDone = errors.New("done")
2
3
func handler(ctx iris.Context) {
4
ctx.ContentType("text/html")
5
ctx.Header("Transfer-Encoding", "chunked")
6
i := 0
7
ints := []int{1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 23, 29}
8
// Send the response in chunks and
9
// wait for half a second between each chunk,
10
// until connection closed.
11
err := ctx.StreamWriter(func(w io.Writer) error {
12
ctx.Writef("Message number %d<br>", ints[i])
13
time.Sleep(500 * time.Millisecond) // simulate delay.
14
if i == len(ints)-1 {
15
return errDone // ends the loop.
16
}
17
i++
18
return nil // continue write
19
})
20
21
if err != errDone {
22
// Test it by canceling the request before the stream ends:
23
// [ERRO] $DATETIME stream: context canceled.
24
ctx.Application().Logger().Errorf("stream: %v", err)
25
}
26
}
Copied!

JSON Example

Let's do the same using JSON.
1
type messageNumber struct {
2
Number int `json:"number"`
3
}
4
5
func handler(ctx iris.Context) {
6
ctx.Header("Transfer-Encoding", "chunked")
7
i := 0
8
ints := []int{1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 23, 29}
9
// Send the response in chunks and wait
10
// for half a second between each chunk,
11
// until connection close.
12
notifyClose := ctx.Request().Context().Done()
13
for {
14
select {
15
case <-notifyClose:
16
// err := ctx.Request().Context().Err()
17
ctx.Application().Logger().Infof("Connection closed, loop end.")
18
return
19
default:
20
ctx.JSON(messageNumber{Number: ints[i]})
21
ctx.WriteString("\n")
22
time.Sleep(500 * time.Millisecond) // simulate delay.
23
if i == len(ints)-1 {
24
ctx.Application().Logger().Infof("Loop end.")
25
return
26
}
27
i++
28
ctx.ResponseWriter().Flush()
29
}
30
}
31
}
Copied!
Result
That's all. As you've noticed, the client receives messages while loading. Check the next chapter (Server-Sent Events) to see an alternative way of sending messages to the client with connection-alive and loaded page.
Last modified 1yr ago
Export as PDF
Copy link