mirror of
https://github.com/kataras/iris.git
synced 2025-12-17 18:07:01 +00:00
use Request().Context().Done() channel instead of the ResponseWriter().CloseNotify() one
Former-commit-id: e380a3624c03faada74c9efc24266679c3ff5e2b
This commit is contained in:
@@ -1,13 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt" // just an optional helper
|
||||
"errors"
|
||||
"io"
|
||||
"time" // showcase the delay
|
||||
|
||||
"github.com/kataras/iris/v12"
|
||||
)
|
||||
|
||||
var errDone = errors.New("done")
|
||||
|
||||
func main() {
|
||||
app := iris.New()
|
||||
|
||||
@@ -17,15 +19,21 @@ func main() {
|
||||
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])
|
||||
err := ctx.StreamWriter(func(w io.Writer) error {
|
||||
ctx.Writef("Message number %d<br>", ints[i])
|
||||
time.Sleep(500 * time.Millisecond) // simulate delay.
|
||||
if i == len(ints)-1 {
|
||||
return false // close and flush
|
||||
return errDone // ends the loop.
|
||||
}
|
||||
i++
|
||||
return true // continue write
|
||||
return nil // continue write
|
||||
})
|
||||
|
||||
if err != errDone {
|
||||
// Test it by canceling the request before the stream ends:
|
||||
// [ERRO] $DATETIME stream: context canceled.
|
||||
ctx.Application().Logger().Errorf("stream: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
type messageNumber struct {
|
||||
@@ -33,7 +41,6 @@ func main() {
|
||||
}
|
||||
|
||||
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}
|
||||
@@ -52,3 +59,10 @@ func main() {
|
||||
|
||||
app.Listen(":8080")
|
||||
}
|
||||
|
||||
/*
|
||||
Look the following methods too:
|
||||
- Context.OnClose(callback)
|
||||
- Context.OnConnectionClose(callback) and
|
||||
- Context.Request().Context().Done()/.Err() too
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user