A better http_responsewriter/stream-writer example, see SSE example for server-side events

Former-commit-id: 635cadf6bac376c2b7b805523ab8d9d6472a5502
This commit is contained in:
Gerasimos (Makis) Maropoulos 2018-04-21 20:46:16 +03:00 committed by GitHub
parent 4ccf31eb44
commit f113872b7d

View File

@ -11,40 +11,43 @@ import (
func main() { func main() {
app := iris.New() app := iris.New()
timeWaitForCloseStream := 4 * time.Second
app.Get("/", func(ctx iris.Context) { app.Get("/", func(ctx iris.Context) {
ctx.ContentType("text/html")
ctx.Header("Transfer-Encoding", "chunked")
i := 0 i := 0
// goroutine in order to no block and just wait, ints := []int{1, 2, 3, 5, 7, 9, 11, 13, 15, 17, 23, 29}
// goroutine is OPTIONAL and not a very good option but it depends on the needs // Send the response in chunks and wait for half a second between each chunk.
// Look the /alternative route for an alternative code style ctx.StreamWriter(func(w io.Writer) bool {
// Send the response in chunks and wait for a second between each chunk. fmt.Fprintf(w, "Message number %d<br>", ints[i])
go ctx.StreamWriter(func(w io.Writer) bool { time.Sleep(500 * time.Millisecond) // simulate delay.
i++ if i == len(ints)-1 {
fmt.Fprintf(w, "this is a message number %d\n", i) // write
time.Sleep(time.Second) // imaginary delay
if i == 4 {
return false // close and flush return false // close and flush
} }
i++
return true // continue write return true // continue write
}) })
// when this handler finished the client should be see the stream writer's contents
// simulate a job here...
time.Sleep(timeWaitForCloseStream)
}) })
app.Get("/alternative", func(ctx iris.Context) { type messageNumber struct {
// Send the response in chunks and wait for a second between each chunk. Number int `json:"number"`
ctx.StreamWriter(func(w io.Writer) bool { }
for i := 1; i <= 4; i++ {
fmt.Fprintf(w, "this is a message number %d\n", i) // write
time.Sleep(time.Second)
}
// when this handler finished the client should be see the stream writer's contents app.Get("/alternative", func(ctx iris.Context) {
return false // stop and flush the contents 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
}
i++
ctx.ResponseWriter().Flush()
}
}) })
app.Run(iris.Addr(":8080")) app.Run(iris.Addr(":8080"))