mirror of
https://github.com/kataras/iris.git
synced 2026-01-04 02:37:14 +00:00
Add a very simple usage-example for sending server side events
Former-commit-id: 6df287d915a772bcae3f2f98445676aba39a2bc6
This commit is contained in:
51
_examples/http_responsewriter/sse-third-party/main.go
vendored
Normal file
51
_examples/http_responsewriter/sse-third-party/main.go
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/kataras/iris"
|
||||
"github.com/r3labs/sse"
|
||||
)
|
||||
|
||||
// First of all install the sse third-party package (you can use other if you don't like this approach)
|
||||
// $ go get -u github.com/r3labs/sse
|
||||
func main() {
|
||||
app := iris.New()
|
||||
s := sse.New()
|
||||
/*
|
||||
This creates a new stream inside of the scheduler.
|
||||
Seeing as there are no consumers, publishing a message
|
||||
to this channel will do nothing.
|
||||
Clients can connect to this stream once the iris handler is started
|
||||
by specifying stream as a url parameter, like so:
|
||||
http://localhost:8080/events?stream=messages
|
||||
*/
|
||||
s.CreateStream("messages")
|
||||
|
||||
app.Any("/events", iris.FromStd(s.HTTPHandler))
|
||||
|
||||
go func() {
|
||||
// You design when to send messages to the client,
|
||||
// here we just wait 5 seconds to send the first message
|
||||
// in order to give u time to open a browser window...
|
||||
time.Sleep(5 * time.Second)
|
||||
// Publish a payload to the stream.
|
||||
s.Publish("messages", &sse.Event{
|
||||
Data: []byte("ping"),
|
||||
})
|
||||
|
||||
time.Sleep(3 * time.Second)
|
||||
s.Publish("messages", &sse.Event{
|
||||
Data: []byte("second message"),
|
||||
})
|
||||
time.Sleep(2 * time.Second)
|
||||
s.Publish("messages", &sse.Event{
|
||||
Data: []byte("third message"),
|
||||
})
|
||||
|
||||
}() // ...
|
||||
|
||||
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
|
||||
}
|
||||
|
||||
/* For a golang SSE client you can look at: https://github.com/r3labs/sse#example-client */
|
||||
@@ -17,7 +17,7 @@ func main() {
|
||||
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
|
||||
// Look the /alternative route 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++
|
||||
|
||||
Reference in New Issue
Block a user