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:
ctx.Header("Transfer-Encoding", "chunked")Then, define the response content type (when we use the ctx.Write methods), e.g.
ctx.ContentType("text/html")And we write the contents:
ctx.Writef("A message here")Finally, we must flush the contents with:
ctx.ResponseWriter().Flush()And repeat.
Iris gives you a helper method which sends streaming data until connection close or error returned:
StreamWriter(func(w io.Writer) error) errorThe 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.
JSON Example
Let's do the same using JSON.
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 updated
Was this helpful?