2017-03-24 01:25:00 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt" // just an optional helper
|
|
|
|
"io"
|
|
|
|
"time" // showcase the delay
|
|
|
|
|
2019-10-25 00:27:02 +02:00
|
|
|
"github.com/kataras/iris/v12"
|
2017-03-24 01:25:00 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
app := iris.New()
|
|
|
|
|
2017-08-27 19:35:23 +02:00
|
|
|
app.Get("/", func(ctx iris.Context) {
|
2018-04-21 19:46:16 +02:00
|
|
|
ctx.ContentType("text/html")
|
|
|
|
ctx.Header("Transfer-Encoding", "chunked")
|
2017-03-24 01:25:00 +01:00
|
|
|
i := 0
|
2018-04-21 19:46:16 +02:00
|
|
|
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.
|
|
|
|
ctx.StreamWriter(func(w io.Writer) bool {
|
|
|
|
fmt.Fprintf(w, "Message number %d<br>", ints[i])
|
|
|
|
time.Sleep(500 * time.Millisecond) // simulate delay.
|
|
|
|
if i == len(ints)-1 {
|
2017-03-24 01:25:00 +01:00
|
|
|
return false // close and flush
|
|
|
|
}
|
2018-04-21 19:46:16 +02:00
|
|
|
i++
|
2017-03-24 01:25:00 +01:00
|
|
|
return true // continue write
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2018-04-21 19:46:16 +02:00
|
|
|
type messageNumber struct {
|
|
|
|
Number int `json:"number"`
|
|
|
|
}
|
|
|
|
|
2017-08-27 19:35:23 +02:00
|
|
|
app.Get("/alternative", func(ctx iris.Context) {
|
2018-04-21 19:46:16 +02:00
|
|
|
ctx.ContentType("application/json")
|
|
|
|
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.
|
|
|
|
for {
|
|
|
|
ctx.JSON(messageNumber{Number: ints[i]})
|
|
|
|
ctx.WriteString("\n")
|
|
|
|
time.Sleep(500 * time.Millisecond) // simulate delay.
|
|
|
|
if i == len(ints)-1 {
|
|
|
|
break
|
2017-03-24 01:25:00 +01:00
|
|
|
}
|
2018-04-21 19:46:16 +02:00
|
|
|
i++
|
|
|
|
ctx.ResponseWriter().Flush()
|
|
|
|
}
|
2017-03-24 01:25:00 +01:00
|
|
|
})
|
|
|
|
|
2020-03-05 21:41:27 +01:00
|
|
|
app.Listen(":8080")
|
2017-03-24 01:25:00 +01:00
|
|
|
}
|