forked from Xzya/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
56 lines (47 loc) · 1.6 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"fmt" // just an optional helper
"io"
"time" // showcase the delay
"gopkg.in/kataras/iris.v6"
"gopkg.in/kataras/iris.v6/adaptors/httprouter"
)
func main() {
app := iris.New()
// output startup banner and error logs on os.Stdout
app.Adapt(iris.DevLogger())
// set the router, you can choose gorillamux too
app.Adapt(httprouter.New())
timeWaitForCloseStream := 4 * time.Second
app.Get("/", func(ctx *iris.Context) {
i := 0
// goroutine in order to no block and just wait,
// goroutine is OPTIONAL and not a very good option but it depends on the needs
// Look the streaming_simple_2 for an alternative code style
// Send the response in chunks and wait for a second between each chunk.
go ctx.StreamWriter(func(w io.Writer) bool {
i++
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 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) {
// Send the response in chunks and wait for a second between each chunk.
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
return false // stop and flush the contents
})
})
app.Listen(":8080")
}