forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
longpolling.go
47 lines (38 loc) · 1012 Bytes
/
longpolling.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
package controllers
import (
"github.com/revel/revel"
"github.com/revel/revel/samples/chat/app/chatroom"
)
type LongPolling struct {
*revel.Controller
}
func (c LongPolling) Room(user string) revel.Result {
chatroom.Join(user)
return c.Render(user)
}
func (c LongPolling) Say(user, message string) revel.Result {
chatroom.Say(user, message)
return nil
}
func (c LongPolling) WaitMessages(lastReceived int) revel.Result {
subscription := chatroom.Subscribe()
defer subscription.Cancel()
// See if anything is new in the archive.
var events []chatroom.Event
for _, event := range subscription.Archive {
if event.Timestamp > lastReceived {
events = append(events, event)
}
}
// If we found one, grand.
if len(events) > 0 {
return c.RenderJson(events)
}
// Else, wait for something new.
event := <-subscription.New
return c.RenderJson([]chatroom.Event{event})
}
func (c LongPolling) Leave(user string) revel.Result {
chatroom.Leave(user)
return c.Redirect(Application.Index)
}