mirror of
https://github.com/kataras/iris.git
synced 2025-12-17 18:07:01 +00:00
reorganization of _examples and add some new examples such as iris+groupcache+mysql+docker
Former-commit-id: ed635ee95de7160cde11eaabc0c1dcb0e460a620
This commit is contained in:
54
_examples/response-writer/stream-writer/main.go
Normal file
54
_examples/response-writer/stream-writer/main.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt" // just an optional helper
|
||||
"io"
|
||||
"time" // showcase the delay
|
||||
|
||||
"github.com/kataras/iris/v12"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
app.Get("/", func(ctx iris.Context) {
|
||||
ctx.ContentType("text/html")
|
||||
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.
|
||||
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 {
|
||||
return false // close and flush
|
||||
}
|
||||
i++
|
||||
return true // continue write
|
||||
})
|
||||
})
|
||||
|
||||
type messageNumber struct {
|
||||
Number int `json:"number"`
|
||||
}
|
||||
|
||||
app.Get("/alternative", func(ctx iris.Context) {
|
||||
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.Listen(":8080")
|
||||
}
|
||||
Reference in New Issue
Block a user