1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-17 18:07:01 +00:00

update stream example

Former-commit-id: a62ee01e0811f2595e292b3d50b844d999ccb4d3
This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-07-01 14:43:24 +03:00
parent 134e2531bf
commit 2d9485326b
3 changed files with 25 additions and 14 deletions

View File

@@ -18,7 +18,8 @@ func main() {
ctx.Header("Transfer-Encoding", "chunked")
i := 0
ints := []int{1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 23, 29}
// Send the response in chunks and wait for half a second between each chunk.
// Send the response in chunks and wait for half a second between each chunk,
// until connection close.
err := ctx.StreamWriter(func(w io.Writer) error {
ctx.Writef("Message number %d<br>", ints[i])
time.Sleep(500 * time.Millisecond) // simulate delay.
@@ -40,20 +41,30 @@ func main() {
Number int `json:"number"`
}
app.Get("/alternative", func(ctx iris.Context) {
app.Get("/json", func(ctx iris.Context) {
ctx.Header("Transfer-Encoding", "chunked")
i := 0
ints := []int{1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 23, 29}
// Send the response in chunks and wait for half a second between each chunk.
// Send the response in chunks and wait for half a second between each chunk,
// until connection close.
notifyClose := ctx.Request().Context().Done()
for {
ctx.JSON(messageNumber{Number: ints[i]})
ctx.WriteString("\n")
time.Sleep(500 * time.Millisecond) // simulate delay.
if i == len(ints)-1 {
break
select {
case <-notifyClose:
// err := ctx.Request().Context().Err()
ctx.Application().Logger().Infof("Connection closed, loop end.")
return
default:
ctx.JSON(messageNumber{Number: ints[i]})
ctx.WriteString("\n")
time.Sleep(500 * time.Millisecond) // simulate delay.
if i == len(ints)-1 {
ctx.Application().Logger().Infof("Loop end.")
return
}
i++
ctx.ResponseWriter().Flush()
}
i++
ctx.ResponseWriter().Flush()
}
})